diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 71ea9353f154..f93364778c7f 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -22,3 +22,9 @@ /librarian.yaml @googleapis/cloud-sdk-java-team @googleapis/cloud-sdk-librarian-team /java-cloud-bom/ @googleapis/cloud-sdk-java-team /java-shared-config/ @googleapis/cloud-sdk-java-team + +# Bigtable CI configs +/.kokoro/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team +/.kokoro/presubmit/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team +/.kokoro/nightly/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team +/.github/workflows/java-bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team diff --git a/.github/workflows/java-storage-nio-ci.yaml b/.github/workflows/java-storage-nio-ci.yaml index 73c25a96b88d..a9eb1678c249 100644 --- a/.github/workflows/java-storage-nio-ci.yaml +++ b/.github/workflows/java-storage-nio-ci.yaml @@ -77,7 +77,12 @@ jobs: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 with: persist-credentials: false - - uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0 + - name: Cache Temurin JDK 8 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: /opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/8.* + key: ${{ runner.os }}-temurin-jdk8 + - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0 with: java-version: 8 distribution: temurin @@ -87,7 +92,7 @@ jobs: # https://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#jvm run: echo "SUREFIRE_JVM_OPT=-Djvm=${JAVA_HOME}/bin/java -P !java17" >> $GITHUB_ENV shell: bash - - uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0 + - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0 with: java-version: 17 distribution: temurin diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml deleted file mode 100644 index 20de49ff37ca..000000000000 --- a/.github/workflows/scorecard.yml +++ /dev/null @@ -1,72 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. They are provided -# by a third-party and are governed by separate terms of service, privacy -# policy, and support documentation. - -name: Scorecard supply-chain security -on: - # For Branch-Protection check. Only the default branch is supported. See - # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection - branch_protection_rule: - # To guarantee Maintained check is occasionally updated. See - # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained - # schedule: - # - cron: '43 11 * * 5' - # push: - # branches: [ "main" ] - -# Declare default permissions as read only. -permissions: read-all - -jobs: - analysis: - name: Scorecard analysis - runs-on: ubuntu-latest - permissions: - # Needed to upload the results to code-scanning dashboard. - security-events: write - # Needed to publish results and get a badge (see publish_results below). - id-token: write - # Uncomment the permissions below if installing in a private repository. - # contents: read - # actions: read - - steps: - - name: "Checkout code" - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # v3.1.0 - with: - persist-credentials: false - - - name: "Run analysis" - uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # v2.1.2 - with: - results_file: results.sarif - results_format: sarif - # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: - # - you want to enable the Branch-Protection check on a *public* repository, or - # - you are installing Scorecard on a *private* repository - # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. - # repo_token: ${{ secrets.SCORECARD_TOKEN }} - - # Public repositories: - # - Publish results to OpenSSF REST API for easy access by consumers - # - Allows the repository to include the Scorecard badge. - # - See https://github.com/ossf/scorecard-action#publishing-results. - # For private repositories: - # - `publish_results` will always be set to `false`, regardless - # of the value entered here. - publish_results: true - - # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF - # format to the repository Actions tab. - - name: "Upload artifact" - uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 # v3.1.0 - with: - name: SARIF file - path: results.sarif - retention-days: 5 - - # Upload the results to GitHub's code scanning dashboard. - - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@17573ee1cc1b9d061760f3a006fc4aac4f944fd5 # v2.2.4 - with: - sarif_file: results.sarif diff --git a/.kokoro/presubmit/bigtable-integration-cfe.cfg b/.kokoro/presubmit/bigtable-integration-cfe.cfg index 9e60b33c7da6..91c1d537d732 100644 --- a/.kokoro/presubmit/bigtable-integration-cfe.cfg +++ b/.kokoro/presubmit/bigtable-integration-cfe.cfg @@ -8,7 +8,7 @@ env_vars: { env_vars: { key: "INTEGRATION_TEST_ARGS" - value: "-P bigtable-cfe-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests" + value: "-P bigtable-cfe-it,bigtable-classic-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests" } env_vars: { diff --git a/.kokoro/presubmit/bigtable-integration-dp.cfg b/.kokoro/presubmit/bigtable-integration-dp.cfg index a9d32aa6b83b..a6a07f7471f0 100644 --- a/.kokoro/presubmit/bigtable-integration-dp.cfg +++ b/.kokoro/presubmit/bigtable-integration-dp.cfg @@ -8,7 +8,7 @@ env_vars: { env_vars: { key: "INTEGRATION_TEST_ARGS" - value: "-P bigtable-directpath-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests" + value: "-P bigtable-directpath-it,bigtable-classic-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests" } env_vars: { diff --git a/.kokoro/presubmit/bigtable-integration.cfg b/.kokoro/presubmit/bigtable-integration.cfg index 5d0f0ff7523b..24114fc19743 100644 --- a/.kokoro/presubmit/bigtable-integration.cfg +++ b/.kokoro/presubmit/bigtable-integration.cfg @@ -8,7 +8,7 @@ env_vars: { env_vars: { key: "INTEGRATION_TEST_ARGS" - value: "-P bigtable-prod-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests" + value: "-P bigtable-prod-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests -Dbigtable.expected-protocol=CLASSIC" } env_vars: { diff --git a/.mvn/maven.config b/.mvn/maven.config index e2ac57dd9106..ad46e44a8de7 100644 --- a/.mvn/maven.config +++ b/.mvn/maven.config @@ -1,3 +1,7 @@ -Daether.remoteRepositoryFilter.prefixes=false -Daether.remoteRepositoryFilter.groupId=false -Daether.syncContext.named.time=900 +-Daether.connector.http.retryHandler.count=5 +-Daether.connector.http.retryHandler.interval=5000 +-Daether.connector.http.retryHandler.intervalMax=60000 +-Daether.connector.http.retryHandler.serviceUnavailable=429,502,503,504 diff --git a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java index 1e4adf96a5c8..741aa982e930 100644 --- a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java +++ b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java @@ -36,10 +36,12 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.util.Clock; import com.google.auth.Credentials; import com.google.auth.TestUtils; @@ -67,6 +69,7 @@ import java.security.GeneralSecurityException; import java.time.Duration; import java.util.Base64; +import java.util.Date; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -91,17 +94,23 @@ class ClientSideCredentialAccessBoundaryFactoryTest { static class MockStsTransportFactory implements HttpTransportFactory { MockStsTransport transport = new MockStsTransport(); - private CountDownLatch refreshEntryLatch = new CountDownLatch(0); + private volatile CountDownLatch refreshEntryLatch = new CountDownLatch(0); + private volatile CountDownLatch refreshRequestLatch = new CountDownLatch(0); void setRefreshEntryLatch(CountDownLatch refreshEntryLatch) { this.refreshEntryLatch = refreshEntryLatch; } + /** Sets a latch counted down once a refresh request has been issued to the mock transport. */ + void setRefreshRequestLatch(CountDownLatch refreshRequestLatch) { + this.refreshRequestLatch = refreshRequestLatch; + } + @Override public HttpTransport create() { // Request 0 is the initial token fetch. On subsequent refresh requests (requestCount >= 1) - // in multi-threaded tests, pause the in-flight STS request until all concurrent threads have - // evaluated determineRefreshType() and attached to the existing refreshTask. + // in concurrent/async tests, pause the in-flight STS request until the test releases + // refreshEntryLatch, then signal refreshRequestLatch once buildRequest() has recorded it. if (transport.getRequestCount() >= 1) { try { if (!refreshEntryLatch.await(5, TimeUnit.SECONDS)) { @@ -111,6 +120,14 @@ public HttpTransport create() { Thread.currentThread().interrupt(); throw new RuntimeException(e); } + return new HttpTransport() { + @Override + protected LowLevelHttpRequest buildRequest(String method, String url) { + LowLevelHttpRequest request = transport.buildRequest(method, url); + refreshRequestLatch.countDown(); + return request; + } + }; } return transport; } @@ -158,10 +175,7 @@ void fetchIntermediateCredentials() throws Exception { @Test void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException { String universeDomain = "foobar"; - GoogleCredentials sourceCredentials = - getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder() - .setUniverseDomain(universeDomain) - .build(); + GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain); ClientSideCredentialAccessBoundaryFactory factory = ClientSideCredentialAccessBoundaryFactory.newBuilder() @@ -174,7 +188,7 @@ void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException // Verify domain. String url = mockStsTransportFactory.transport.getRequest().getUrl(); - assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); + assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url); } @Test @@ -282,37 +296,41 @@ void refreshCredentialsIfRequired_blockingSingleThread() throws IOException { } @Test - void refreshCredentialsIfRequired_asyncSingleThread() throws IOException { + void refreshCredentialsIfRequired_asyncSingleThread() throws IOException, InterruptedException { final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC); + CountDownLatch allowAsyncRefresh = new CountDownLatch(1); + CountDownLatch refreshCompleted = new CountDownLatch(1); + mockStsTransportFactory.setRefreshEntryLatch(allowAsyncRefresh); + mockStsTransportFactory.setRefreshRequestLatch(refreshCompleted); // Call refreshCredentialsIfRequired() once to initialize the intermediate credentials. This // should make one request to the STS endpoint. factory.refreshCredentialsIfRequired(); assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); - // Subsequent calls to refreshCredentialsIfRequired() in an async mode should NOT - // immediately call the STS endpoint. They should schedule an asynchronous refresh. - int numRefresh = 3; - for (int i = 0; i < numRefresh; i++) { - factory.refreshCredentialsIfRequired(); - } - - // Verify that only the initial call resulted in an immediate STS request. The async refresh - // is still pending. - assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); - - // Introduce a small delay to allow the asynchronous refresh task to complete. This is - // necessary because the async task runs on a separate thread. try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new IOException(e); + // Subsequent calls to refreshCredentialsIfRequired() in an async mode should NOT + // immediately call the STS endpoint. They should schedule an asynchronous refresh. + int numRefresh = 3; + for (int i = 0; i < numRefresh; i++) { + factory.refreshCredentialsIfRequired(); + } + + // Verify that only the initial call resulted in an immediate STS request. The async refresh + // is still paused behind allowAsyncRefresh. + assertEquals(1, mockStsTransportFactory.transport.getRequestCount()); + } finally { + allowAsyncRefresh.countDown(); } - // After the delay, the request count should be 2 (initial fetch + one async refresh). - // Subsequent calls to refreshCredentialsIfRequired() in ASYNC mode re-use the in-progress - // refresh task, so they don't trigger additional STS requests. + assertTrue( + refreshCompleted.await(5, TimeUnit.SECONDS), + "Timed out waiting for asynchronous refresh request"); + + // After the async refresh executes, the request count should be 2 (initial fetch + one async + // refresh). Subsequent calls to refreshCredentialsIfRequired() in ASYNC mode re-use the + // in-progress refresh task, so they don't trigger additional STS requests. assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } @@ -354,8 +372,10 @@ void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, Interru // Wait for all 5 threads to make both clock.currentTimeMillis() calls (outside and inside // synchronized (refreshLock)) before the background STS refresh completes. CountDownLatch refreshEntryLatch = new CountDownLatch(numThreads * 2); + CountDownLatch refreshCompleted = new CountDownLatch(1); final ClientSideCredentialAccessBoundaryFactory factory = getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC, refreshEntryLatch); + mockStsTransportFactory.setRefreshRequestLatch(refreshCompleted); // Call refreshCredentialsIfRequired() once to initialize the intermediate credentials. This // should make one request to the STS endpoint. @@ -367,15 +387,12 @@ void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, Interru // trigger additional refreshes while the background refresh is still pending. triggerConcurrentRefresh(factory, numThreads, refreshEntryLatch); - // Introduce a small delay to allow the asynchronous refresh task to complete. - try { - Thread.sleep(100); - } catch (InterruptedException e) { - throw new IOException(e); - } + assertTrue( + refreshCompleted.await(5, TimeUnit.SECONDS), + "Timed out waiting for asynchronous refresh request"); - // After the delay, the request count should be 2, indicating that the initial fetch and a - // single async refresh occurred (not one per thread). + // After the async refresh executes, the request count should be 2, indicating that the initial + // fetch and a single async refresh occurred (not one per thread). assertEquals(2, mockStsTransportFactory.transport.getRequestCount()); } @@ -611,6 +628,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials( return sourceCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform"); } + private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) { + return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() { + return new AccessToken( + "customUniverseAccessToken", + new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); + } + }; + } + private ClientSideCredentialAccessBoundaryFactory getClientSideCredentialAccessBoundaryFactory( RefreshType refreshType) throws IOException { return getClientSideCredentialAccessBoundaryFactory(refreshType, new CountDownLatch(0)); diff --git a/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java b/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java index e9aad1c5c830..98c9ce551032 100644 --- a/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java +++ b/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java @@ -47,6 +47,20 @@ * GoogleCredentials/OAuth2Credentials, as it does not provide an access token and is not considered * an OAuth2 credential. * + *

WARNING: API keys do not carry universe domain metadata and cannot be validated + * against a client's configured universe domain or endpoint. When no universe domain is configured + * on the client, requests default to {@code googleapis.com}. Callers are solely responsible for + * ensuring the API key matches the client's configured universe domain, as the client will not + * prevent sending an API key to an unintended universe domain. + * + *

Quota project: {@code ApiKeyCredentials} does not support overriding the quota project + * ID. The Google Cloud project associated with the API key is used as the quota and billing + * project. Setting a quota project ID on the client sends {@code x-goog-user-project}, which is + * ignored for resource-based APIs and rejected for client-based APIs because standard API keys do + * not identify an IAM principal. See Set + * the quota project for details. + * *


  * Credentials credentials = ApiKeyCredentials.create("your api key");
  * 
@@ -60,6 +74,19 @@ public class ApiKeyCredentials extends Credentials { this.apiKey = apiKey; } + /** + * Creates an {@link ApiKeyCredentials} instance for the given API key. + * + *

WARNING: API keys do not carry universe domain metadata and cannot be + * validated against a client's configured universe domain or endpoint. Callers are solely + * responsible for ensuring the API key matches the client's configured universe domain (which + * defaults to {@code googleapis.com}), as the client will not prevent sending an API key to an + * unintended universe domain. + * + * @param apiKey the API key string + * @return the credentials instance + * @throws IllegalArgumentException if {@code apiKey} is null or empty + */ public static ApiKeyCredentials create(String apiKey) { if (apiKey == null || apiKey.isEmpty()) { throw new IllegalArgumentException("API key cannot be null or blank"); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java index 6c150079271f..c7595556d009 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java @@ -881,9 +881,8 @@ public byte[] sign(byte[] toSign) { try { String account = getAccount(); return IamUtils.sign( - account, + String.format(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, this.getUniverseDomain(), account), this, - this.getUniverseDomain(), transportFactory.create(), toSign, Collections.emptyMap()); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java index 5e0325266915..9d41e0811afe 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java @@ -115,25 +115,34 @@ String getCredentialName() { /** * Returns the credentials instance from the given access token. * + *

The returned credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code + * googleapis.com}). Callers with an access token for a non-default universe domain should use + * {@link #create(String, AccessToken)} to specify the universe domain explicitly. + * * @param accessToken the access token * @return the credentials instance */ public static GoogleCredentials create(AccessToken accessToken) { - return GoogleCredentials.newBuilder().setAccessToken(accessToken).build(); + return create(null, accessToken); } /** * Returns the credentials instance from the given access token and universe domain. * - * @param universeDomain the universe domain + *

If {@code universeDomain} is {@code null} or blank, the returned credentials default to + * {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). + * + * @param universeDomain the universe domain, or {@code null} or blank to default to {@link + * Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}) * @param accessToken the access token * @return the credentials instance */ - public static GoogleCredentials create(String universeDomain, AccessToken accessToken) { - return GoogleCredentials.newBuilder() - .setAccessToken(accessToken) - .setUniverseDomain(universeDomain) - .build(); + public static GoogleCredentials create(@Nullable String universeDomain, AccessToken accessToken) { + Builder builder = GoogleCredentials.newBuilder().setAccessToken(accessToken); + if (universeDomain != null && !universeDomain.trim().isEmpty()) { + builder.setUniverseDomain(universeDomain); + } + return builder.build(); } /** @@ -419,11 +428,17 @@ protected GoogleCredentials() { /** * Constructor with an explicit access token and quotaProjectId. * - *

Deprecated, please use the {@link GoogleCredentials#GoogleCredentials(Builder)} constructor - * whenever possible. + *

Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers + * with an access token for a non-default universe domain should use {@link #create(String, + * AccessToken)} (or {@link #newBuilder()} with {@link Builder#setAccessToken(AccessToken)} and + * {@link Builder#setUniverseDomain(String)}) to specify the universe domain explicitly. * * @param accessToken initial or temporary access token * @param quotaProjectId a quotaProjectId, a project id to be used for billing purposes + * @deprecated Use {@link #GoogleCredentials(Builder)} for subclasses, or {@link #newBuilder()} + * with {@link Builder#setAccessToken(AccessToken)} and {@link + * Builder#setQuotaProjectId(String)} (and {@link Builder#setUniverseDomain(String)} for a + * non-default universe domain). */ @Deprecated protected GoogleCredentials(@Nullable AccessToken accessToken, @Nullable String quotaProjectId) { @@ -436,7 +451,13 @@ protected GoogleCredentials(@Nullable AccessToken accessToken, @Nullable String /** * Constructor with explicit access token. * + *

Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers + * with an access token for a non-default universe domain should use {@link #create(String, + * AccessToken)} to specify the universe domain explicitly. + * * @param accessToken initial or temporary access token + * @deprecated Use {@link #create(AccessToken)} for {@code googleapis.com}, or {@link + * #create(String, AccessToken)} to specify a universe domain explicitly. */ @Deprecated public GoogleCredentials(AccessToken accessToken) { @@ -467,10 +488,15 @@ protected GoogleCredentials(Builder builder) { /** * Constructor with explicit access token and refresh margins. * - *

Deprecated, please use the {@link GoogleCredentials#GoogleCredentials(Builder)} constructor - * whenever possible. + *

Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers + * with an access token for a non-default universe domain should use {@link #create(String, + * AccessToken)} (or {@link #newBuilder()} with {@link Builder#setAccessToken(AccessToken)} and + * {@link Builder#setUniverseDomain(String)}) to specify the universe domain explicitly. * * @param accessToken initial or temporary access token + * @deprecated Use {@link #GoogleCredentials(Builder)} for subclasses, or {@link #newBuilder()} + * with {@link Builder#setAccessToken(AccessToken)} and {@link + * Builder#setUniverseDomain(String)} for a non-default universe domain. */ @Deprecated protected GoogleCredentials( @@ -686,6 +712,15 @@ public Builder setQuotaProjectId(@Nullable String quotaProjectId) { return this; } + /** + * Sets the universe domain for the credential. + * + *

If unset, {@code null}, or blank, defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} + * ({@code googleapis.com}). + * + * @param universeDomain the universe domain (for example, {@code googleapis.com}) + * @return this builder + */ public Builder setUniverseDomain(String universeDomain) { this.universeDomain = universeDomain; return this; diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java index 3111bef92402..f47505069a30 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java @@ -85,7 +85,7 @@ class IamUtils { /** * Returns a signature for the provided bytes. * - * @param serviceAccountEmail the email address for the service account used for signing + * @param signBlobUrl the IAM signBlob endpoint for the service account used for signing * @param credentials credentials required for making the IAM call * @param transport transport used for building the HTTP request * @param toSign bytes to sign @@ -94,9 +94,8 @@ class IamUtils { * @throws ServiceAccountSigner.SigningException if signing fails */ static byte[] sign( - String serviceAccountEmail, + String signBlobUrl, Credentials credentials, - String universeDomain, HttpTransport transport, byte[] toSign, Map additionalFields) { @@ -105,13 +104,7 @@ static byte[] sign( transport.createRequestFactory(new HttpCredentialsAdapter(credentials)); String signature; try { - signature = - getSignature( - serviceAccountEmail, - universeDomain, - base64.encode(toSign), - additionalFields, - factory); + signature = getSignature(signBlobUrl, base64.encode(toSign), additionalFields, factory); } catch (IOException ex) { throw new ServiceAccountSigner.SigningException("Failed to sign the provided bytes", ex); } @@ -119,14 +112,8 @@ static byte[] sign( } private static String getSignature( - String serviceAccountEmail, - String universeDomain, - String bytes, - Map additionalFields, - HttpRequestFactory factory) + String signBlobUrl, String bytes, Map additionalFields, HttpRequestFactory factory) throws IOException { - String signBlobUrl = - String.format(IAM_SIGN_BLOB_ENDPOINT_FORMAT, universeDomain, serviceAccountEmail); GenericUrl genericUrl = new GenericUrl(signBlobUrl); GenericData signRequest = new GenericData(); @@ -240,7 +227,8 @@ private static String getStatusMessageOrDefault(HttpResponse response) { /** * Returns an IdToken issued to the serviceAccount with a specified targetAudience * - * @param serviceAccountEmail the email address for the service account to get an ID Token for + * @param idTokenUrl the IAM generateIdToken endpoint for the service account to get an ID Token + * for * @param credentials credentials required for making the IAM call * @param transport transport used for building the HTTP request * @param targetAudience the audience the issued ID token should include @@ -252,18 +240,14 @@ private static String getStatusMessageOrDefault(HttpResponse response) { * href="https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/generateIdToken">... */ static IdToken getIdToken( - String serviceAccountEmail, + String idTokenUrl, Credentials credentials, HttpTransport transport, String targetAudience, boolean includeEmail, Map additionalFields, - CredentialTypeForMetrics credentialTypeForMetrics, - String universeDomain) + CredentialTypeForMetrics credentialTypeForMetrics) throws IOException { - - String idTokenUrl = - String.format(IAM_ID_TOKEN_ENDPOINT_FORMAT, universeDomain, serviceAccountEmail); GenericUrl genericUrl = new GenericUrl(idTokenUrl); GenericData idTokenRequest = new GenericData(); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java index 64a8e202f989..cf3dedffa9d6 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java @@ -113,6 +113,9 @@ public class ImpersonatedCredentials extends GoogleCredentials private static final long serialVersionUID = -2133257318957488431L; private static final int TWELVE_HOURS_IN_SECONDS = 43200; private static final int DEFAULT_LIFETIME_IN_SECONDS = 3600; + private static final String GENERATE_ACCESS_TOKEN_ACTION = ":generateAccessToken"; + private static final String SIGN_BLOB_ACTION = ":signBlob"; + private static final String GENERATE_ID_TOKEN_ACTION = ":generateIdToken"; private volatile GoogleCredentials sourceCredentials; private transient volatile @Nullable AccessToken cachedStsAccessToken; private transient volatile @Nullable KeyStore cachedStsKeyStore; @@ -367,19 +370,34 @@ public void setTransportFactory(HttpTransportFactory httpTransportFactory) { public byte[] sign(byte[] toSign) { try { return IamUtils.sign( - getAccount(), + getIamEndpoint(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, SIGN_BLOB_ACTION), sourceCredentials, - getUniverseDomain(), transportFactory.create(), toSign, ImmutableMap.of("delegates", this.delegates)); } catch (IOException ex) { // Throwing an IOException would be a breaking change, so wrap it here. - // This should not happen for this credential type. - throw new SigningException("Failed to sign: Error obtaining universe domain", ex); + throw new SigningException("Failed to sign: Error obtaining IAM endpoint", ex); } } + private String getIamEndpoint(String endpointFormat, String action) throws IOException { + String endpointOverride = this.iamEndpointOverride; + if (endpointOverride == null) { + return String.format(endpointFormat, getUniverseDomain(), getAccount()); + } + // Falling back to the universe-domain endpoint could send source credentials to the wrong host. + if (!endpointOverride.endsWith(GENERATE_ACCESS_TOKEN_ACTION)) { + throw new IOException( + String.format( + "Invalid IAM endpoint override: %s. Expected a URL ending in %s.", + endpointOverride, GENERATE_ACCESS_TOKEN_ACTION)); + } + return endpointOverride.substring( + 0, endpointOverride.length() - GENERATE_ACCESS_TOKEN_ACTION.length()) + + action; + } + /** * Returns credentials defined by a ImpersonatedCredential key file in JSON format from the Google * Developers Console. @@ -462,6 +480,7 @@ static ImpersonatedCredentials fromJson( String quotaProjectId; String targetPrincipal; String serviceAccountImpersonationUrl; + String universeDomain; // This applies to the scopes applied for the impersonated token and not the // underlying source credential. Default to empty list to keep the existing // behavior (when json file did not populate a scopes field). @@ -474,6 +493,7 @@ static ImpersonatedCredentials fromJson( sourceCredentialsJson = (Map) json.get("source_credentials"); sourceCredentialsType = (String) sourceCredentialsJson.get("type"); quotaProjectId = (String) json.get("quota_project_id"); + universeDomain = (String) json.get("universe_domain"); targetPrincipal = extractTargetPrincipal(serviceAccountImpersonationUrl); if (json.containsKey("scopes")) { scopes = ImmutableList.copyOf((List) json.get("scopes")); @@ -496,7 +516,19 @@ static ImpersonatedCredentials fromJson( "A credential of type %s is not supported as source credential for impersonation.", sourceCredentialsType)); } - return ImpersonatedCredentials.newBuilder() + ImpersonatedCredentials.Builder builder = ImpersonatedCredentials.newBuilder(); + if (universeDomain != null && !universeDomain.trim().isEmpty()) { + String sourceUniverseDomain = sourceCredentials.getUniverseDomain(); + if (!universeDomain.equals(sourceUniverseDomain)) { + throw new IOException( + String.format( + "Universe domain %s in source credentials does not match %s universe domain" + + " set for impersonated credentials.", + sourceUniverseDomain, universeDomain)); + } + builder.setUniverseDomain(universeDomain); + } + return builder .setSourceCredentials(sourceCredentials) .setTargetPrincipal(targetPrincipal) .setDelegates(delegates) @@ -900,14 +932,13 @@ public IdToken idTokenWithAudience( boolean includeEmail = options != null && options.contains(IdTokenProvider.Option.INCLUDE_EMAIL); return IamUtils.getIdToken( - getAccount(), + getIamEndpoint(IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, GENERATE_ID_TOKEN_ACTION), sourceCredentials, transportFactory.create(), targetAudience, includeEmail, ImmutableMap.of("delegates", this.delegates), - getMetricsCredentialType(), - getUniverseDomain()); + getMetricsCredentialType()); } @Override diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java index 6966ee3fc82f..7997d5fa6b32 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java @@ -40,6 +40,7 @@ import com.google.common.base.Preconditions; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; +import java.io.ObjectInputStream; import java.net.URI; import java.security.GeneralSecurityException; import java.security.PrivateKey; @@ -71,6 +72,9 @@ */ @NullMarked public class JwtCredentials extends Credentials implements JwtProvider { + // Matches the default computed serialVersionUID from released versions before universeDomain was + // added, so previously serialized JwtCredentials instances still deserialize. + private static final long serialVersionUID = 287345113251030847L; private static final String JWT_ACCESS_PREFIX = OAuth2Utils.BEARER_PREFIX; private static final String JWT_INCOMPLETE_ERROR_MESSAGE = "JWT claims must contain audience, " + "issuer, and subject."; @@ -82,7 +86,7 @@ public class JwtCredentials extends Credentials implements JwtProvider { private final String privateKeyId; private final JwtClaims jwtClaims; private final Long lifeSpanSeconds; - private final String universeDomain; + @VisibleForTesting String universeDomain; @VisibleForTesting transient Clock clock; private transient String jwt; @@ -230,6 +234,17 @@ Clock getClock() { return clock; } + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + clock = Clock.SYSTEM; + // Java deserialization bypasses the constructor and leaves fields absent from older serialized + // streams as null. Normalize universeDomain here so getUniverseDomain(), equals(), and + // hashCode() stay consistent with newly constructed default instances. + if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) { + this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + } + } + public static class Builder { private PrivateKey privateKey; private String privateKeyId; diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java index 9816a4c87bf2..180c76db206b 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java @@ -93,6 +93,10 @@ public class OAuth2Credentials extends Credentials { /** * Returns the credentials instance from the given access token. * + *

The returned credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. To create + * access-token credentials for a custom universe domain, use {@link + * GoogleCredentials#create(String, AccessToken)}. + * * @param accessToken the access token * @return the credentials instance */ @@ -559,6 +563,13 @@ public static T getFromServiceLoader(Class clazz, T defaultInst return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance); } + /** + * Returns a new builder for {@link OAuth2Credentials}. + * + *

Built credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. To create + * access-token credentials for a custom universe domain, use {@link + * GoogleCredentials#create(String, AccessToken)} or {@link GoogleCredentials#newBuilder()}. + */ public static Builder newBuilder() { return new Builder(); } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java index 91b374da5e96..d8ab23c92aec 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java @@ -33,46 +33,58 @@ import static com.google.common.base.Preconditions.checkNotNull; +import com.google.auth.Credentials; +import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.Objects; import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** * A refreshable alternative to {@link OAuth2Credentials}. * *

To enable automatic token refreshes, you must provide an {@link OAuth2RefreshHandler}. + * + *

Because {@link OAuth2RefreshHandler} returns {@link AccessToken} values without universe + * domain metadata, credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Callers + * refreshing tokens for a custom universe domain should configure it explicitly via {@link + * Builder#setUniverseDomain(String)}. If lazy or delegated universe domain resolution is needed, + * subclass this class and override {@link #getUniverseDomain()}. */ @NullMarked public class OAuth2CredentialsWithRefresh extends OAuth2Credentials { + // Matches the computed serialVersionUID prior to adding universeDomain. + private static final long serialVersionUID = -5362111100740719676L; + /** Interface for the refresh handler. */ public interface OAuth2RefreshHandler { AccessToken refreshAccessToken() throws IOException; } private final OAuth2RefreshHandler refreshHandler; + @VisibleForTesting String universeDomain; protected OAuth2CredentialsWithRefresh(Builder builder) { super(builder.getAccessToken(), builder.getRefreshMargin(), builder.getExpirationMargin()); - // An expiration time must be provided. + // If no expirationTime is provided, the token will never be refreshed. if (builder.getAccessToken() != null && builder.getAccessToken().getExpirationTime() == null) { throw new IllegalArgumentException( "The provided access token must contain the expiration time."); } this.refreshHandler = checkNotNull(builder.refreshHandler); + if (builder.universeDomain == null || builder.universeDomain.trim().isEmpty()) { + this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + } else { + this.universeDomain = builder.universeDomain; + } } protected OAuth2CredentialsWithRefresh( AccessToken accessToken, OAuth2RefreshHandler refreshHandler) { - super(accessToken); - - // If no expirationTime is provided, the token will never be refreshed. - if (accessToken != null && accessToken.getExpirationTime() == null) { - throw new IllegalArgumentException( - "The provided access token must contain the expiration time."); - } - - this.refreshHandler = checkNotNull(refreshHandler); + this(newBuilder().setAccessToken(accessToken).setRefreshHandler(refreshHandler)); } /** Refreshes the access token using the provided {@link OAuth2RefreshHandler}. */ @@ -87,6 +99,46 @@ public OAuth2RefreshHandler getRefreshHandler() { return refreshHandler; } + /** + * Returns the universe domain for this credential. + * + *

Returns the fixed universe domain configured via {@link Builder#setUniverseDomain(String)}, + * or {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} if none was configured. Subclasses may override + * this method if lazy or delegated resolution is required. + * + * @return the configured universe domain, or {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} if none + * was explicitly configured + * @throws IOException if a subclass fails while resolving the universe domain + */ + @Override + public String getUniverseDomain() throws IOException { + return this.universeDomain; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (!(obj instanceof OAuth2CredentialsWithRefresh)) { + return false; + } + OAuth2CredentialsWithRefresh other = (OAuth2CredentialsWithRefresh) obj; + return super.equals(other) + && Objects.equals(this.refreshHandler, other.refreshHandler) + && Objects.equals(this.universeDomain, other.universeDomain); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), this.refreshHandler, this.universeDomain); + } + + private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { + input.defaultReadObject(); + // Default absent or blank universeDomain from older serialized streams. + if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) { + this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + } + } + public static Builder newBuilder() { return new Builder(); } @@ -94,6 +146,7 @@ public static Builder newBuilder() { public static class Builder extends OAuth2Credentials.Builder { private OAuth2RefreshHandler refreshHandler; + private @Nullable String universeDomain; private Builder() {} @@ -115,6 +168,28 @@ public Builder setRefreshHandler(OAuth2RefreshHandler handler) { return this; } + /** + * Sets the fixed universe domain for this credential. If null or blank, defaults to {@link + * Credentials#GOOGLE_DEFAULT_UNIVERSE}. + * + *

Because {@link OAuth2RefreshHandler} returns {@link AccessToken} values without universe + * domain metadata, callers refreshing tokens for a custom universe domain must set this + * explicitly. + * + * @param universeDomain the universe domain (for example, {@code googleapis.com}) + * @return this builder + */ + @CanIgnoreReturnValue + public Builder setUniverseDomain(@Nullable String universeDomain) { + this.universeDomain = universeDomain; + return this; + } + + /** Returns the configured universe domain, or {@code null} if not explicitly set. */ + public @Nullable String getUniverseDomain() { + return universeDomain; + } + @Override public OAuth2CredentialsWithRefresh build() { return new OAuth2CredentialsWithRefresh(this); diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java index 3c09e1c20dfa..76a66d05b46d 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java @@ -119,6 +119,9 @@ public class ServiceAccountCredentials extends GoogleCredentials private transient HttpTransportFactory transportFactory; + // Lazily cached self-signed JWT credentials for scope-based requests, where the claims are + // identical across requests. Reused across calls so the RSA key only signs once per expiry + // window (JwtCredentials handles re-signing near expiration). private transient @Nullable JwtCredentials selfSignedJwtCredentialsWithScope = null; /** @@ -522,10 +525,30 @@ private GenericData parseResponseAs(HttpResponse response) throws IOException { } /** - * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT). + * Refreshes the OAuth2 access token by exchanging a signed JWT assertion at {@code + * tokenServerUri}. + * + *

This method is only used for the OAuth2 access token flow (not self-signed JWT + * authentication, which is handled directly by {@link #getRequestMetadata(URI)} without calling + * this method). + * + *

OAuth2 token exchange is only supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. In + * non-default universe domains, this method throws {@link IOException}. Use {@link + * #getRequestMetadata(URI)} for self-signed JWT authentication, or wrap this credential in {@link + * ImpersonatedCredentials} if an OAuth2 access token is required. */ @Override public AccessToken refreshAccessToken() throws IOException { + String universeDomain = getUniverseDomain(); + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) { + throw new IOException( + String.format( + "OAuth2 access token refresh is not supported for ServiceAccountCredentials in" + + " universe domain %s. Use self-signed JWT authentication via" + + " getRequestMetadata() or wrap this credential in ImpersonatedCredentials to" + + " obtain short-lived OAuth2 access tokens.", + universeDomain)); + } JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY; long currentTime = clock.currentTimeMillis(); String assertion = createAssertion(jsonFactory, currentTime); @@ -862,6 +885,8 @@ public byte[] sign(byte[] toSign) { /** * Returns a new JwtCredentials instance with modified claims. * + *

The returned credentials use the same universe domain as these credentials. + * * @param newClaims new claims. Any unspecified claim fields will default to the current values. * @return new credentials */ @@ -874,6 +899,7 @@ public JwtCredentials jwtWithClaims(JwtClaims newClaims) { .setPrivateKeyId(privateKeyId) .setJwtClaims(claimsBuilder.build().merge(newClaims)) .setClock(clock) + .setUniverseDomain(getUniverseDomainOrThrow()) .build(); } @@ -1035,9 +1061,21 @@ JwtCredentials createSelfSignedJwtCredentials( .setPrivateKeyId(privateKeyId) .setJwtClaims(claimsBuilder.build()) .setClock(clock) + .setUniverseDomain(getUniverseDomainOrThrow()) .build(); } + // Helper only to catch the checked IOException from getUniverseDomain(). + // ServiceAccountCredentials reads universeDomain from the key file or builder, so it should not + // throw IOException. + private String getUniverseDomainOrThrow() { + try { + return getUniverseDomain(); + } catch (IOException e) { + throw new IllegalStateException("Failed to retrieve universe domain.", e); + } + } + @Override public void getRequestMetadata( final URI uri, Executor executor, final RequestMetadataCallback callback) { diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java index f4f2145c4cc2..f4958c9ef107 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java @@ -91,9 +91,11 @@ public class ServiceAccountJwtAccessCredentials extends Credentials private final String privateKeyId; private final URI defaultAudience; private final String quotaProjectId; - private final String universeDomain; + @VisibleForTesting String universeDomain; - private transient LoadingCache credentialsCache; + // Caches one JwtCredentials per audience (JwtClaims) so each target URI signs a JWT once per + // token lifetime instead of re-signing with the RSA private key on every request. + @VisibleForTesting transient LoadingCache credentialsCache; // Until we expose this to the users it can remain transient and non-serializable @VisibleForTesting transient Clock clock = Clock.SYSTEM; @@ -142,13 +144,13 @@ private ServiceAccountJwtAccessCredentials( this.privateKey = Preconditions.checkNotNull(privateKey); this.privateKeyId = privateKeyId; this.defaultAudience = defaultAudience; - this.credentialsCache = createCache(); this.quotaProjectId = quotaProjectId; if (universeDomain == null || universeDomain.trim().isEmpty()) { this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; } else { this.universeDomain = universeDomain; } + this.credentialsCache = createCache(); } /** @@ -311,6 +313,10 @@ public static ServiceAccountJwtAccessCredentials fromStream( } private LoadingCache createCache() { + // Bound entries to 100 audiences and expire them after LIFE_SPAN_SECS - CLOCK_SKEW (55 minutes) + // so idle audiences are evicted around the same time JwtCredentials would re-sign. The custom + // ticker reads clock (and the loader reads fields from the enclosing instance lazily on each + // cache miss) so tests can advance time with a fake clock. return CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(LIFE_SPAN_SECS - CLOCK_SKEW, TimeUnit.SECONDS) @@ -331,6 +337,7 @@ public JwtCredentials load(JwtClaims claims) throws Exception { .setJwtClaims(claims) .setLifeSpanSeconds(LIFE_SPAN_SECS) .setClock(clock) + .setUniverseDomain(universeDomain) .build(); } }); @@ -339,6 +346,8 @@ public JwtCredentials load(JwtClaims claims) throws Exception { /** * Returns a new JwtCredentials instance with modified claims. * + *

The returned credentials use the same universe domain as these credentials. + * * @param newClaims new claims. Any unspecified claim fields will default to the current values. * @return new credentials */ @@ -355,6 +364,7 @@ public JwtCredentials jwtWithClaims(JwtClaims newClaims) { .setJwtClaims(claimsBuilder.build().merge(newClaims)) .setLifeSpanSeconds(LIFE_SPAN_SECS) .setClock(clock) + .setUniverseDomain(universeDomain) .build(); } @@ -465,7 +475,13 @@ public byte[] sign(byte[] toSign) { @Override public int hashCode() { return Objects.hash( - clientId, clientEmail, privateKey, privateKeyId, defaultAudience, quotaProjectId); + clientId, + clientEmail, + privateKey, + privateKeyId, + defaultAudience, + quotaProjectId, + universeDomain); } @Override @@ -476,6 +492,7 @@ public String toString() { .add("privateKeyId", privateKeyId) .add("defaultAudience", defaultAudience) .add("quotaProjectId", quotaProjectId) + .add("universeDomain", universeDomain) .toString(); } @@ -490,12 +507,20 @@ public boolean equals(@Nullable Object obj) { && Objects.equals(this.privateKey, other.privateKey) && Objects.equals(this.privateKeyId, other.privateKeyId) && Objects.equals(this.defaultAudience, other.defaultAudience) - && Objects.equals(this.quotaProjectId, other.quotaProjectId); + && Objects.equals(this.quotaProjectId, other.quotaProjectId) + && Objects.equals(this.universeDomain, other.universeDomain); } private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); clock = Clock.SYSTEM; + // Java deserialization bypasses the constructor and leaves fields absent from older serialized + // streams as null. Normalize universeDomain here so getUniverseDomain(), equals(), and + // hashCode() stay consistent with newly constructed default instances. + if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) { + this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; + } + // LoadingCache is transient (not serializable), so recreate an empty cache. credentialsCache = createCache(); } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java index 510e54ba174b..94bcb619397e 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java @@ -72,6 +72,7 @@ class Slf4jLoggingHelpers { "authorization", "subject_token", "actor_token", + "access_boundary_session_key", "id_token")); } diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java index c2eb38aa490c..35d37f3d727c 100644 --- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java +++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java @@ -44,6 +44,7 @@ import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.GenericData; import com.google.auth.CredentialTypeForMetrics; +import com.google.auth.Credentials; import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.MetricsUtils.RequestType; import com.google.common.base.MoreObjects; @@ -137,20 +138,34 @@ static UserCredentials fromJson(Map json, HttpTransportFactory t // currently "token_uri" is not a default field and needs to be added to json file manually String tokenUrl = (String) json.get("token_uri"); URI tokenUri = (tokenUrl == null || tokenUrl.isEmpty()) ? null : URI.create(tokenUrl); + String universeDomain = (String) json.get("universe_domain"); + if (universeDomain != null + && !universeDomain.trim().isEmpty() + && !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) { + throw new IOException( + String.format( + "UserCredentials are not supported in universes other than %s (configured" + + " universe_domain: %s).", + Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain)); + } String account = null; if (json.containsKey("account")) { account = (String) json.get("account"); } - return UserCredentials.newBuilder() - .setClientId(clientId) - .setClientSecret(clientSecret) - .setRefreshToken(refreshToken) - .setAccessToken(null) - .setHttpTransportFactory(transportFactory) - .setTokenServerUri(tokenUri) - .setQuotaProjectId(quotaProjectId) - .setAccount(account) - .build(); + UserCredentials.Builder builder = + UserCredentials.newBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRefreshToken(refreshToken) + .setAccessToken(null) + .setHttpTransportFactory(transportFactory) + .setTokenServerUri(tokenUri) + .setQuotaProjectId(quotaProjectId) + .setAccount(account); + if (universeDomain != null && !universeDomain.trim().isEmpty()) { + builder.setUniverseDomain(universeDomain); + } + return builder.build(); } /** @@ -271,6 +286,13 @@ private GenericData doRefreshAccessToken() throws IOException { throw new IllegalStateException( "UserCredentials instance cannot refresh because there is no refresh token."); } + String universeDomain = getUniverseDomain(); + if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) { + throw new IOException( + String.format( + "UserCredentials refresh is only supported in %s (configured universe domain: %s).", + Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain)); + } GenericData tokenRequest = new GenericData(); tokenRequest.set("client_id", clientId); tokenRequest.set("client_secret", clientSecret); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java index e2759a292439..258e362ea0c5 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java @@ -165,10 +165,7 @@ void refreshAccessToken() throws IOException { void refreshAccessToken_withCustomUniverseDomain() throws IOException { MockStsTransportFactory transportFactory = new MockStsTransportFactory(); String universeDomain = "foobar"; - GoogleCredentials sourceCredentials = - getServiceAccountSourceCredentials(/* canRefresh= */ true).toBuilder() - .setUniverseDomain(universeDomain) - .build(); + GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain); DownscopedCredentials downscopedCredentials = DownscopedCredentials.newBuilder() @@ -192,7 +189,7 @@ void refreshAccessToken_withCustomUniverseDomain() throws IOException { // Verify domain. String url = transportFactory.transport.getRequest().getUrl(); - assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain)); + assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url); } @Test @@ -350,6 +347,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials(boolean canR return sourceCredentials.createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE); } + private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) { + return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) { + @Override + public AccessToken refreshAccessToken() { + return new AccessToken( + "customUniverseAccessToken", + new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1))); + } + }; + } + private static GoogleCredentials getUserSourceCredentials() { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addClient("clientId", "clientSecret"); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java index 343eca7fbcd2..53544ded1a74 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java @@ -98,7 +98,7 @@ class GoogleCredentialsTest extends BaseSerializationTest { private static final Collection DEFAULT_SCOPES = Collections.unmodifiableCollection(Arrays.asList("scope3")); private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com"; - private static final String TPC_UNIVERSE = "foo.bar"; + private static final String CUSTOM_UNIVERSE = "foo.bar"; @Test void getApplicationDefault_nullTransport_throws() { @@ -190,13 +190,17 @@ void fromStream_serviceAccount_Universe_noToken() throws IOException { transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = ServiceAccountCredentialsTest.writeServiceAccountStream( - SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, TPC_UNIVERSE); + SA_CLIENT_ID, + SA_CLIENT_EMAIL, + SA_PRIVATE_KEY_PKCS8, + SA_PRIVATE_KEY_ID, + CUSTOM_UNIVERSE); GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccountStream, transportFactory); assertNotNull(credentials); - assertEquals(TPC_UNIVERSE, credentials.getUniverseDomain()); + assertEquals(CUSTOM_UNIVERSE, credentials.getUniverseDomain()); assertTrue(credentials.isExplicitUniverseDomain()); credentials = credentials.createScoped(SCOPES); credentials.getRequestMetadata(CALL_URI); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java index b136f264f998..303d4f6720dc 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java @@ -51,6 +51,14 @@ class IamUtilsTest { private static final String CLIENT_EMAIL = "36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com"; + private static final String SIGN_BLOB_URL = + String.format( + IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + CLIENT_EMAIL); + private static final String ID_TOKEN_URL = + String.format( + IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, Credentials.GOOGLE_DEFAULT_UNIVERSE, CLIENT_EMAIL); private ServiceAccountCredentials credentials; @@ -77,9 +85,8 @@ void sign_success_noRetry() { byte[] signature = IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transportFactory.getTransport(), expectedSignature, ImmutableMap.of()); @@ -109,9 +116,8 @@ void sign_retryTwoTimes_success() { byte[] signature = IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transportFactory.getTransport(), expectedSignature, ImmutableMap.of()); @@ -146,9 +152,8 @@ void sign_retryThreeTimes_success() { byte[] signature = IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transportFactory.getTransport(), expectedSignature, ImmutableMap.of()); @@ -189,9 +194,8 @@ void sign_retryThreeTimes_exception() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transportFactory.getTransport(), expectedSignature, ImmutableMap.of())); @@ -225,9 +229,8 @@ void sign_4xxError_noRetry_exception() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transportFactory.getTransport(), expectedSignature, ImmutableMap.of())); @@ -262,9 +265,8 @@ void sign_4xxErrorWithEmptyBody_throwsSigningExceptionWithStatusCode() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -292,14 +294,13 @@ void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() throws I IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 401 trying to getIDToken: Unauthorized", exception.getMessage()); Mockito.verify(credentials, Mockito.never()).refresh(); } @@ -320,14 +321,13 @@ void getIdToken_4xxErrorWithJsonBody_includesServerMessage() { IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 403 trying to getIDToken: Permission denied", exception.getMessage()); } @@ -347,9 +347,8 @@ void sign_4xxErrorWithEmptyStringBody_usesStatusMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -372,9 +371,8 @@ void sign_4xxErrorWithEmptyBodyAndNoReasonPhrase_usesFallbackMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -398,14 +396,13 @@ void getIdToken_4xxErrorWithEmptyBodyAndEmptyReasonPhrase_usesFallbackMessage() IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals( "Error code 403 trying to getIDToken: (no error details in the response)", exception.getMessage()); @@ -427,9 +424,8 @@ void sign_4xxErrorWithJsonBody_includesServerMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -457,9 +453,8 @@ void sign_4xxErrorWithJsonNullBody_usesStatusMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -486,9 +481,8 @@ void sign_4xxErrorWithHtmlBody_usesStatusMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -515,9 +509,8 @@ void sign_4xxErrorWithEmptyJsonObject_usesStatusMessage() { ServiceAccountSigner.SigningException.class, () -> IamUtils.sign( - CLIENT_EMAIL, + SIGN_BLOB_URL, credentials, - Credentials.GOOGLE_DEFAULT_UNIVERSE, transport, new byte[] {0xD, 0xE, 0xA, 0xD}, ImmutableMap.of())); @@ -544,14 +537,13 @@ void getIdToken_4xxErrorWithHtmlBody_usesStatusMessage() { IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); } @@ -572,14 +564,13 @@ void getIdToken_4xxErrorWithJsonMissingMessage_usesStatusMessage() { IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); } @@ -600,14 +591,13 @@ void getIdToken_4xxErrorWithJsonEmptyMessage_usesStatusMessage() { IOException.class, () -> IamUtils.getIdToken( - CLIENT_EMAIL, + ID_TOKEN_URL, credentials, transport, "https://example.com", false, ImmutableMap.of(), - CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT, - Credentials.GOOGLE_DEFAULT_UNIVERSE)); + CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT)); assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage()); } } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java index cd33872d146c..3bdf64190dbb 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java @@ -46,13 +46,17 @@ import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonGenerator; import com.google.api.client.json.JsonParser; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebToken.Payload; +import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; import com.google.auth.Credentials; import com.google.auth.ServiceAccountSigner.SigningException; @@ -874,7 +878,7 @@ void sign_universeDomainException() throws IOException { SigningException exception = assertThrows(SigningException.class, () -> targetCredentials.sign(expectedSignature)); - assertEquals("Failed to sign: Error obtaining universe domain", exception.getMessage()); + assertEquals("Failed to sign: Error obtaining IAM endpoint", exception.getMessage()); } @Test @@ -1596,4 +1600,153 @@ public AccessToken refreshAccessToken() { .getRequest() .getFirstHeaderValue("Authorization")); } + + @Test + void fromStream_matchingTopLevelUniverseDomain_loads() throws IOException { + GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL); + setSourceUniverseDomain(json, TEST_UNIVERSE_DOMAIN); + json.put("universe_domain", TEST_UNIVERSE_DOMAIN); + + ImpersonatedCredentials credentials = + ImpersonatedCredentials.fromStream(TestUtils.jsonToInputStream(json)); + + assertEquals(TEST_UNIVERSE_DOMAIN, credentials.getUniverseDomain()); + assertTrue(credentials.isExplicitUniverseDomain()); + } + + @Test + void fromStream_topLevelUniverseDomainMismatchesUserSource_throwsIOException() + throws IOException { + // authorized_user sources always report the default universe. + GenericJson json = + buildImpersonationCredentialsJson( + NONGDU_IMPERSONATION_URL, + null, + null, + USER_ACCOUNT_CLIENT_ID, + USER_ACCOUNT_CLIENT_SECRET, + REFRESH_TOKEN, + IMMUTABLE_SCOPES_LIST); + json.put("universe_domain", TEST_UNIVERSE_DOMAIN); + InputStream stream = TestUtils.jsonToInputStream(json); + + assertThrows(IOException.class, () -> ImpersonatedCredentials.fromStream(stream)); + } + + @Test + void sign_withImpersonationUrlFromStream_usesOverrideSignBlobEndpoint() throws IOException { + List requestedUrls = new ArrayList<>(); + GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL); + ImpersonatedCredentials credentials = + ImpersonatedCredentials.fromStream( + TestUtils.jsonToInputStream(json), recordingSignBlobTransportFactory(requestedUrls)); + + credentials.sign(new byte[] {0x1}); + + assertEquals( + Collections.singletonList( + String.format( + IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, + TEST_UNIVERSE_DOMAIN, + IMPERSONATED_CLIENT_EMAIL)), + requestedUrls); + } + + @Test + void sign_withPscImpersonationUrl_usesPscSignBlobEndpoint() throws IOException { + String pscUrl = + "https://iamcredentials-myendpoint.p.googleapis.com/v1/projects/-/serviceAccounts/" + + IMPERSONATED_CLIENT_EMAIL; + List requestedUrls = new ArrayList<>(); + GenericJson json = serviceAccountImpersonationJson(pscUrl + ":generateAccessToken"); + ImpersonatedCredentials credentials = + ImpersonatedCredentials.fromStream( + TestUtils.jsonToInputStream(json), recordingSignBlobTransportFactory(requestedUrls)); + + credentials.sign(new byte[] {0x1}); + + assertEquals(Collections.singletonList(pscUrl + ":signBlob"), requestedUrls); + } + + @Test + void idTokenWithAudience_withImpersonationUrlFromStream_usesOverrideGenerateIdTokenEndpoint() + throws IOException { + List requestedUrls = new ArrayList<>(); + GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL); + ImpersonatedCredentials credentials = + ImpersonatedCredentials.fromStream( + TestUtils.jsonToInputStream(json), recordingIdTokenTransportFactory(requestedUrls)); + + credentials.idTokenWithAudience("https://foo.bar", null); + + assertEquals( + Collections.singletonList( + String.format( + IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, + TEST_UNIVERSE_DOMAIN, + IMPERSONATED_CLIENT_EMAIL)), + requestedUrls); + } + + @Test + void idTokenWithAudience_withBaseHostOverride_throwsIOExceptionWithoutNetworkCall() + throws IOException { + List requestedUrls = new ArrayList<>(); + ImpersonatedCredentials credentials = + credentialsWithOverride( + "https://iamcredentials." + TEST_UNIVERSE_DOMAIN, + recordingIdTokenTransportFactory(requestedUrls)); + + assertThrows(IOException.class, () -> credentials.idTokenWithAudience("https://foo.bar", null)); + assertEquals(Collections.emptyList(), requestedUrls); + } + + private static GenericJson serviceAccountImpersonationJson(String impersonationUrl) { + return buildImpersonationCredentialsJson(impersonationUrl, null, null, Collections.emptyList()); + } + + @SuppressWarnings("unchecked") + private static void setSourceUniverseDomain(GenericJson json, String universeDomain) { + ((Map) json.get("source_credentials")).put("universe_domain", universeDomain); + } + + private static ImpersonatedCredentials credentialsWithOverride( + String iamEndpointOverride, HttpTransportFactory transportFactory) throws IOException { + return ImpersonatedCredentials.newBuilder() + .setSourceCredentials(getSourceCredentials()) + .setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL) + .setScopes(Collections.emptyList()) + .setIamEndpointOverride(iamEndpointOverride) + .setHttpTransportFactory(transportFactory) + .build(); + } + + private static HttpTransportFactory recordingSignBlobTransportFactory( + List requestedUrls) { + return recordingIamTransportFactory(requestedUrls, "{\"signedBlob\":\"3q2+\"}"); + } + + private static HttpTransportFactory recordingIdTokenTransportFactory(List requestedUrls) { + return recordingIamTransportFactory(requestedUrls, "{\"token\":\"" + STANDARD_ID_TOKEN + "\"}"); + } + + private static HttpTransportFactory recordingIamTransportFactory( + List requestedUrls, String responseJson) { + return () -> + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + requestedUrls.add(url); + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() { + return new MockLowLevelHttpResponse() + .setStatusCode(HttpStatusCodes.STATUS_CODE_OK) + .setContentType("application/json") + .setContent(responseJson); + } + }; + } + }; + } } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java index 96afc0dce6e8..8a00bd8b0adf 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java @@ -93,10 +93,34 @@ void serialize() throws IOException, ClassNotFoundException { assertEquals(credentials.hashCode(), deserializedCredentials.hashCode()); assertEquals(credentials.toString(), deserializedCredentials.toString()); assertEquals(credentials.getUniverseDomain(), deserializedCredentials.getUniverseDomain()); + verifyJwtAccess( + deserializedCredentials.getRequestMetadata(), + "some-audience", + "some-issuer", + "some-subject", + PRIVATE_KEY_ID); assertSame(Clock.SYSTEM, deserializedCredentials.getClock()); } } + @Test + void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse() + throws IOException, ClassNotFoundException { + JwtCredentials expected = createTestBuilder().build(); + + for (String serializedUniverseDomain : Arrays.asList(null, "", " ")) { + JwtCredentials credentials = createTestBuilder().build(); + credentials.universeDomain = serializedUniverseDomain; + + JwtCredentials deserialized = serializeAndDeserialize(credentials); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain()); + assertEquals(expected, deserialized); + assertEquals(deserialized, expected); + assertEquals(expected.hashCode(), deserialized.hashCode()); + assertEquals(expected.toString(), deserialized.toString()); + } + } + @Test void builder_requiresPrivateKey() { JwtClaims claims = diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java index 34e66daace9c..abe21cf3ada0 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java @@ -604,6 +604,7 @@ void serviceAccountCredentials_exchangeToken_masksSensitiveTokens() throws IOExc void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException { TestAppender testAppender = setupTestLogger(StsRequestHandler.class); MockStsTransport transport = new MockStsTransport(); + transport.setReturnAccessBoundarySessionKey(true); StsTokenExchangeRequest tokenRequest = StsTokenExchangeRequest.newBuilder( @@ -643,6 +644,7 @@ void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException { assertEquals("Response payload for token exchange", payloadLog.getMessage()); boolean foundAccessToken = false; + boolean foundSessionKey = false; for (KeyValuePair kvp : payloadLog.getKeyValuePairs()) { if ("access_token".equals(kvp.key)) { foundAccessToken = true; @@ -657,9 +659,21 @@ void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException { 64, ((String) kvp.value).length(), "access_token should be masked as a SHA-256 hash (64 hex chars)"); + } else if ("access_boundary_session_key".equals(kvp.key)) { + foundSessionKey = true; + assertNotNull(kvp.value); + assertNotEquals( + transport.getAccessBoundarySessionKey(), + kvp.value, + "access_boundary_session_key value should be masked, not logged as raw key"); + assertEquals( + 64, + ((String) kvp.value).length(), + "access_boundary_session_key should be masked as a SHA-256 hash (64 hex chars)"); } } assertTrue(foundAccessToken); + assertTrue(foundSessionKey); testAppender.stop(); } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java index a6b437eabc3b..3f716dcb007a 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java @@ -35,20 +35,25 @@ import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_REFRESH_MARGIN; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import com.google.auth.Credentials; import com.google.auth.TestUtils; import java.io.IOException; +import java.io.Serializable; import java.net.URI; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Objects; import org.junit.jupiter.api.Test; /** Tests for {@link OAuth2CredentialsWithRefresh}. */ -class OAuth2CredentialsWithRefreshTest { +class OAuth2CredentialsWithRefreshTest extends BaseSerializationTest { private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date()); @Test @@ -199,4 +204,205 @@ void getRequestMetadata() throws IOException { TestUtils.assertContainsBearerToken(metadata, refreshedToken.getTokenValue()); } + + private static final AccessToken REFRESHED_TOKEN = + new AccessToken("refreshedAccessToken", new Date()); + + private static final class SerializableRefreshHandler + implements OAuth2CredentialsWithRefresh.OAuth2RefreshHandler, Serializable { + private static final long serialVersionUID = 1L; + private final AccessToken refreshedToken; + + private SerializableRefreshHandler(AccessToken refreshedToken) { + this.refreshedToken = refreshedToken; + } + + @Override + public AccessToken refreshAccessToken() { + return refreshedToken; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SerializableRefreshHandler)) { + return false; + } + SerializableRefreshHandler other = (SerializableRefreshHandler) obj; + return Objects.equals(this.refreshedToken, other.refreshedToken); + } + + @Override + public int hashCode() { + return Objects.hashCode(refreshedToken); + } + } + + private static OAuth2CredentialsWithRefresh.Builder createTestBuilder( + OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler) { + return OAuth2CredentialsWithRefresh.newBuilder() + .setAccessToken(ACCESS_TOKEN) + .setRefreshHandler(handler); + } + + @Test + void protectedConstructor() throws IOException { + OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN; + OAuth2CredentialsWithRefresh credentials = + new OAuth2CredentialsWithRefresh(ACCESS_TOKEN, handler); + + assertEquals(ACCESS_TOKEN, credentials.getAccessToken()); + assertEquals(handler, credentials.getRefreshHandler()); + assertEquals(DEFAULT_REFRESH_MARGIN, credentials.getRefreshMargin()); + assertEquals(DEFAULT_EXPIRATION_MARGIN, credentials.getExpirationMargin()); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain()); + + assertThrows( + NullPointerException.class, () -> new OAuth2CredentialsWithRefresh(ACCESS_TOKEN, null)); + assertThrows( + IllegalArgumentException.class, + () -> new OAuth2CredentialsWithRefresh(new AccessToken("accessToken", null), handler)); + } + + @Test + void builder_universeDomain() throws IOException { + OAuth2CredentialsWithRefresh.Builder builder = createTestBuilder(() -> ACCESS_TOKEN); + assertNull(builder.getUniverseDomain()); + + builder.setUniverseDomain("example.com"); + assertEquals("example.com", builder.getUniverseDomain()); + assertEquals("example.com", builder.build().getUniverseDomain()); + } + + @Test + void getUniverseDomain_defaultsToGoogleDefaultUniverse() throws IOException { + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + createTestBuilder(() -> ACCESS_TOKEN).build().getUniverseDomain()); + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain(null).build().getUniverseDomain()); + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain("").build().getUniverseDomain()); + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain(" ").build().getUniverseDomain()); + } + + @Test + void serialize() throws IOException, ClassNotFoundException { + SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN); + OAuth2CredentialsWithRefresh credentials = createTestBuilder(handler).build(); + + OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials); + assertEquals(credentials, deserialized); + assertEquals(credentials.hashCode(), deserialized.hashCode()); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain()); + assertEquals(REFRESHED_TOKEN, deserialized.refreshAccessToken()); + TestUtils.assertContainsBearerToken( + deserialized.getRequestMetadata(URI.create("http://googleapis.com/testapi/v1/foo")), + REFRESHED_TOKEN.getTokenValue()); + } + + @Test + void serialize_preservesCustomUniverseDomain() throws IOException, ClassNotFoundException { + SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN); + OAuth2CredentialsWithRefresh credentials = + createTestBuilder(handler).setUniverseDomain("example.com").build(); + + OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials); + assertEquals("example.com", deserialized.getUniverseDomain()); + } + + @Test + void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse() + throws IOException, ClassNotFoundException { + SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN); + OAuth2CredentialsWithRefresh expected = createTestBuilder(handler).build(); + + // Simulate deserializing streams written before universeDomain existed or with blank values. + for (String rawUniverseDomain : new String[] {null, "", " "}) { + OAuth2CredentialsWithRefresh credentials = createTestBuilder(handler).build(); + credentials.universeDomain = rawUniverseDomain; + + OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials); + assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain()); + assertEquals(expected, deserialized); + } + } + + @Test + void equals_true() { + OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN; + OAuth2CredentialsWithRefresh custom = + createTestBuilder(handler).setUniverseDomain("example.com").build(); + OAuth2CredentialsWithRefresh sameCustom = + createTestBuilder(handler).setUniverseDomain("example.com").build(); + + assertEquals(custom, custom); + assertEquals(custom, sameCustom); + assertEquals(sameCustom, custom); + assertEquals(custom.hashCode(), sameCustom.hashCode()); + + OAuth2CredentialsWithRefresh noToken = + OAuth2CredentialsWithRefresh.newBuilder() + .setRefreshHandler(handler) + .setUniverseDomain("example.com") + .build(); + OAuth2CredentialsWithRefresh sameNoToken = + OAuth2CredentialsWithRefresh.newBuilder() + .setRefreshHandler(handler) + .setUniverseDomain("example.com") + .build(); + assertEquals(noToken, sameNoToken); + assertEquals(noToken.hashCode(), sameNoToken.hashCode()); + + // Explicit default universe domain equals unset, null, empty, and blank values. + OAuth2CredentialsWithRefresh explicitDefault = + createTestBuilder(handler).setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE).build(); + assertEquals(explicitDefault, createTestBuilder(handler).build()); + assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain(null).build()); + assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain("").build()); + assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain(" ").build()); + } + + @Test + void equals_false() { + OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN; + OAuth2CredentialsWithRefresh.OAuth2RefreshHandler otherHandler = () -> ACCESS_TOKEN; + AccessToken otherToken = + new AccessToken("otherAccessToken", new Date(ACCESS_TOKEN.getExpirationTime().getTime())); + + OAuth2CredentialsWithRefresh baseline = + createTestBuilder(handler).setUniverseDomain("example.com").build(); + OAuth2CredentialsWithRefresh differentToken = + OAuth2CredentialsWithRefresh.newBuilder() + .setAccessToken(otherToken) + .setRefreshHandler(handler) + .setUniverseDomain("example.com") + .build(); + OAuth2CredentialsWithRefresh differentHandler = + createTestBuilder(otherHandler).setUniverseDomain("example.com").build(); + OAuth2CredentialsWithRefresh differentUniverse = + createTestBuilder(handler).setUniverseDomain("other.example.com").build(); + + assertNotEquals(baseline, null); + assertNotEquals(baseline, "not-a-credential"); + assertNotEquals(baseline, differentToken); + assertNotEquals(baseline, differentHandler); + assertNotEquals(baseline, differentUniverse); + + // Without an initial access token, distinct refresh handlers must still compare unequal. + OAuth2CredentialsWithRefresh noToken = + OAuth2CredentialsWithRefresh.newBuilder() + .setRefreshHandler(handler) + .setUniverseDomain("example.com") + .build(); + OAuth2CredentialsWithRefresh noTokenOtherHandler = + OAuth2CredentialsWithRefresh.newBuilder() + .setRefreshHandler(otherHandler) + .setUniverseDomain("example.com") + .build(); + assertNotEquals(noToken, noTokenOtherHandler); + } } diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 34592a6ce5ea..07f2287dcf81 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java @@ -43,14 +43,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import com.google.api.client.http.GenericUrl; +import com.google.api.client.http.HttpRequest; +import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.json.webtoken.JsonWebToken; import com.google.api.client.testing.http.FixedClock; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.client.util.Clock; import com.google.api.client.util.Joiner; @@ -59,6 +66,7 @@ import com.google.auth.RequestMetadataCallback; import com.google.auth.TestUtils; import com.google.auth.http.AuthHttpConstants; +import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.GoogleCredentials.GoogleCredentialsInfo; import com.google.common.collect.ImmutableSet; @@ -81,6 +89,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; /** Test case for {@link ServiceAccountCredentials}. */ @@ -644,6 +654,108 @@ void refreshAccessToken_tokenExpiry() throws IOException { assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue()); } + @Test + void refreshAccessToken_nonDefaultUniverse_throwsIOExceptionWithoutNetworkCall() + throws IOException { + URI customTokenUri = URI.create("https://oauth2.example.com/token"); + MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); + + GoogleCredentials[] cases = { + createDefaultBuilder() + .setScopes(SCOPES) + .setHttpTransportFactory(transportFactory) + .setUniverseDomain("example.com") + .build(), + createDefaultBuilder() + .setScopes(SCOPES) + .setHttpTransportFactory(transportFactory) + .setTokenServerUri(customTokenUri) + .setUniverseDomain("example.com") + .build(), + createDefaultBuilder() + .setScopes(SCOPES) + .setHttpTransportFactory(transportFactory) + .setUniverseDomain("example.com") + .build() + .createDelegated("user@example.com") + }; + + for (GoogleCredentials credentials : cases) { + IOException error = assertThrows(IOException.class, credentials::refreshAccessToken); + assertTrue(error.getMessage().contains("example.com")); + } + assertThrows(IOException.class, cases[0]::refresh); + assertThrows(IOException.class, cases[0]::refreshIfExpired); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void refreshAccessToken_nonDefaultUniverseFromJson_throwsIOException() throws IOException { + MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); + GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "example.com"); + json.put("token_uri", OAuth2Utils.TOKEN_SERVER_URI.toString()); + + GoogleCredentials credentials = + ServiceAccountCredentials.fromJson(json, transportFactory).createScoped(SCOPES); + + IOException error = assertThrows(IOException.class, credentials::refreshAccessToken); + assertTrue(error.getMessage().contains("example.com")); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void httpCredentialsAdapter_401WithNonDefaultUniverseServiceAccount_doesNotCallTokenServer() + throws IOException { + MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory(); + tokenTransportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN); + ServiceAccountCredentials credentials = + createDefaultBuilder() + .setScopes(SCOPES) + .setHttpTransportFactory(tokenTransportFactory) + .setUniverseDomain("example.com") + .build(); + + AtomicInteger apiRequestCount = new AtomicInteger(); + AtomicReference authorizationHeader = new AtomicReference<>(); + MockHttpTransport apiTransport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() { + apiRequestCount.incrementAndGet(); + authorizationHeader.set(getFirstHeaderValue(AuthHttpConstants.AUTHORIZATION)); + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED); + response.addHeader("WWW-Authenticate", "Bearer error=\"invalid_token\""); + return response; + } + }; + } + }; + + HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials); + HttpRequest request = + apiTransport + .createRequestFactory(adapter) + .buildGetRequest(new GenericUrl("https://storage.example.com/test")); + request.setThrowExceptionOnExecuteError(false); + + HttpResponse response = request.execute(); + + assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatusCode()); + assertEquals(1, apiRequestCount.get()); + assertNotNull(authorizationHeader.get()); + assertTrue(authorizationHeader.get().startsWith("Bearer ")); + assertEquals(0, tokenTransportFactory.transport.buildRequestCount); + assertNull(tokenTransportFactory.transport.getRequest()); + } + @Test void refreshAccessToken_IOException_Retry() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; @@ -1773,6 +1885,74 @@ void getRequestMetadata_withMultipleScopes_selfSignedJWT() throws IOException { verifyJwtAccess(credentials.getRequestMetadata(CALL_URI), "scope1 scope2"); } + @Test + void jwtWithClaims_propagatesUniverseDomain() throws IOException { + JwtClaims newClaims = + JwtClaims.newBuilder().setAudience("https://service.example.com/").build(); + + ServiceAccountCredentials defaultCredentials = createDefaultBuilder().build(); + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + defaultCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + + ServiceAccountCredentials customCredentials = + createDefaultBuilder().setUniverseDomain("example.com").build(); + assertEquals("example.com", customCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + + InputStream stream = + writeServiceAccountStream( + CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, "example.com"); + ServiceAccountCredentials jsonCredentials = ServiceAccountCredentials.fromStream(stream); + assertEquals("example.com", jsonCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + } + + @Test + void jwtWithClaims_getUniverseDomainIOException_throwsIllegalStateException() throws IOException { + IOException expectedCause = new IOException("universe lookup failed"); + ServiceAccountCredentials credentials = + new ServiceAccountCredentials(createDefaultBuilder()) { + @Override + public String getUniverseDomain() throws IOException { + throw expectedCause; + } + }; + JwtClaims newClaims = + JwtClaims.newBuilder().setAudience("https://service.example.com/").build(); + + IllegalStateException exception = + assertThrows(IllegalStateException.class, () -> credentials.jwtWithClaims(newClaims)); + assertSame(expectedCause, exception.getCause()); + } + + @Test + void createSelfSignedJwtCredentials_propagatesUniverseDomain() throws IOException { + URI audienceUri = URI.create("https://service.example.com/v1/resource"); + + ServiceAccountCredentials defaultCredentials = createDefaultBuilder().build(); + assertEquals( + Credentials.GOOGLE_DEFAULT_UNIVERSE, + defaultCredentials.createSelfSignedJwtCredentials(audienceUri).getUniverseDomain()); + + ServiceAccountCredentials customCredentials = + createDefaultBuilder().setUniverseDomain("example.com").build(); + assertEquals( + "example.com", + customCredentials.createSelfSignedJwtCredentials(audienceUri).getUniverseDomain()); + } + + @Test + void getRequestMetadata_withScopesAndCustomUniverseDomain_propagatesUniverseDomainToCachedJwt() + throws IOException { + ServiceAccountCredentials credentials = + createDefaultBuilder().setScopes(SCOPES).setUniverseDomain("example.com").build(); + + credentials.getRequestMetadata(null); + + JwtCredentials cachedJwt = credentials.getSelfSignedJwtCredentialsWithScope(); + assertNotNull(cachedJwt); + assertEquals("example.com", cachedJwt.getUniverseDomain()); + } + private void verifyJwtAccess(Map> metadata, String expectedScopeClaim) throws IOException { assertNotNull(metadata); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java index 4a12b7483a33..43b720a02908 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java @@ -62,6 +62,7 @@ import java.security.PrivateKey; import java.security.Signature; import java.security.SignatureException; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -561,6 +562,30 @@ void equals_false_callUri() throws IOException { assertNotEquals(otherCredentials, credentials); } + @Test + void equals_false_universeDomain() throws IOException { + PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); + ServiceAccountJwtAccessCredentials credentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(CALL_URI) + .build(); + ServiceAccountJwtAccessCredentials otherCredentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(CALL_URI) + .setUniverseDomain("example.com") + .build(); + assertNotEquals(credentials, otherCredentials); + assertNotEquals(otherCredentials, credentials); + } + @Test void toString_containsFields() throws IOException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); @@ -576,8 +601,13 @@ void toString_containsFields() throws IOException { String expectedToString = String.format( "ServiceAccountJwtAccessCredentials{clientId=%s, clientEmail=%s, privateKeyId=%s, " - + "defaultAudience=%s, quotaProjectId=%s}", - SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_ID, CALL_URI, QUOTA_PROJECT); + + "defaultAudience=%s, quotaProjectId=%s, universeDomain=%s}", + SA_CLIENT_ID, + SA_CLIENT_EMAIL, + SA_PRIVATE_KEY_ID, + CALL_URI, + QUOTA_PROJECT, + GOOGLE_DEFAULT_UNIVERSE); assertEquals(expectedToString, credentials.toString()); } @@ -591,6 +621,7 @@ void hashCode_equals() throws IOException { .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setDefaultAudience(CALL_URI) + .setUniverseDomain("example.com") .build(); ServiceAccountJwtAccessCredentials otherCredentials = ServiceAccountJwtAccessCredentials.newBuilder() @@ -599,14 +630,51 @@ void hashCode_equals() throws IOException { .setPrivateKey(privateKey) .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setDefaultAudience(CALL_URI) + .setUniverseDomain("example.com") .build(); + assertEquals(credentials, otherCredentials); assertEquals(credentials.hashCode(), otherCredentials.hashCode()); } @Test void serialize() throws IOException, ClassNotFoundException { PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); - ServiceAccountJwtAccessCredentials credentials = + JwtClaims expectedClaims = + JwtClaims.newBuilder() + .setAudience(CALL_URI.toString()) + .setIssuer(SA_CLIENT_EMAIL) + .setSubject(SA_CLIENT_EMAIL) + .build(); + + for (String universeDomain : Arrays.asList(GOOGLE_DEFAULT_UNIVERSE, "example.com")) { + ServiceAccountJwtAccessCredentials credentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(CALL_URI) + .setUniverseDomain(universeDomain) + .build(); + ServiceAccountJwtAccessCredentials deserializedCredentials = + serializeAndDeserialize(credentials); + verifyJwtAccess(deserializedCredentials.getRequestMetadata(), CALL_URI); + assertEquals(credentials, deserializedCredentials); + assertEquals(credentials.hashCode(), deserializedCredentials.hashCode()); + assertEquals(credentials.toString(), deserializedCredentials.toString()); + assertEquals(universeDomain, deserializedCredentials.getUniverseDomain()); + assertSame(Clock.SYSTEM, deserializedCredentials.clock); + JwtCredentials cached = deserializedCredentials.credentialsCache.getIfPresent(expectedClaims); + assertNotNull(cached); + assertEquals(universeDomain, cached.getUniverseDomain()); + } + } + + @Test + void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse() + throws IOException, ClassNotFoundException { + PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); + ServiceAccountJwtAccessCredentials expected = ServiceAccountJwtAccessCredentials.newBuilder() .setClientId(SA_CLIENT_ID) .setClientEmail(SA_CLIENT_EMAIL) @@ -614,13 +682,35 @@ void serialize() throws IOException, ClassNotFoundException { .setPrivateKeyId(SA_PRIVATE_KEY_ID) .setDefaultAudience(CALL_URI) .build(); - ServiceAccountJwtAccessCredentials deserializedCredentials = - serializeAndDeserialize(credentials); - verifyJwtAccess(deserializedCredentials.getRequestMetadata(), CALL_URI); - assertEquals(credentials, deserializedCredentials); - assertEquals(credentials.hashCode(), deserializedCredentials.hashCode()); - assertEquals(credentials.toString(), deserializedCredentials.toString()); - assertSame(Clock.SYSTEM, deserializedCredentials.clock); + JwtClaims expectedClaims = + JwtClaims.newBuilder() + .setAudience(CALL_URI.toString()) + .setIssuer(SA_CLIENT_EMAIL) + .setSubject(SA_CLIENT_EMAIL) + .build(); + + for (String serializedUniverseDomain : Arrays.asList(null, "", " ")) { + ServiceAccountJwtAccessCredentials credentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(CALL_URI) + .build(); + credentials.universeDomain = serializedUniverseDomain; + + ServiceAccountJwtAccessCredentials deserialized = serializeAndDeserialize(credentials); + assertEquals(GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain()); + assertEquals(expected, deserialized); + assertEquals(deserialized, expected); + assertEquals(expected.hashCode(), deserialized.hashCode()); + assertEquals(expected.toString(), deserialized.toString()); + verifyJwtAccess(deserialized.getRequestMetadata(), CALL_URI); + JwtCredentials cached = deserialized.credentialsCache.getIfPresent(expectedClaims); + assertNotNull(cached); + assertEquals(GOOGLE_DEFAULT_UNIVERSE, cached.getUniverseDomain()); + } } @Test @@ -900,6 +990,75 @@ void builder_customUniverseDomain() throws IOException { assertEquals("example.com", credentials.getUniverseDomain()); } + @Test + void jwtWithClaims_propagatesUniverseDomain() throws IOException { + PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); + JwtClaims newClaims = JwtClaims.newBuilder().setAudience("new-audience").build(); + + ServiceAccountJwtAccessCredentials defaultCredentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(URI.create("default-audience")) + .build(); + assertEquals( + GOOGLE_DEFAULT_UNIVERSE, defaultCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + + ServiceAccountJwtAccessCredentials customCredentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setDefaultAudience(URI.create("default-audience")) + .setUniverseDomain("example.com") + .build(); + assertEquals("example.com", customCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + + ServiceAccountJwtAccessCredentials jsonCredentials = + ServiceAccountJwtAccessCredentials.fromJson( + writeServiceAccountJson("example.com"), CALL_URI); + assertEquals("example.com", jsonCredentials.jwtWithClaims(newClaims).getUniverseDomain()); + } + + @Test + void getRequestMetadata_propagatesUniverseDomainToCachedJwtCredentials() throws IOException { + PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8); + JwtClaims expectedClaims = + JwtClaims.newBuilder() + .setAudience(CALL_URI.toString()) + .setIssuer(SA_CLIENT_EMAIL) + .setSubject(SA_CLIENT_EMAIL) + .build(); + + ServiceAccountJwtAccessCredentials defaultCredentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .build(); + defaultCredentials.getRequestMetadata(CALL_URI); + JwtCredentials defaultCached = defaultCredentials.credentialsCache.getIfPresent(expectedClaims); + assertNotNull(defaultCached); + assertEquals(GOOGLE_DEFAULT_UNIVERSE, defaultCached.getUniverseDomain()); + + ServiceAccountJwtAccessCredentials customCredentials = + ServiceAccountJwtAccessCredentials.newBuilder() + .setClientId(SA_CLIENT_ID) + .setClientEmail(SA_CLIENT_EMAIL) + .setPrivateKey(privateKey) + .setPrivateKeyId(SA_PRIVATE_KEY_ID) + .setUniverseDomain("example.com") + .build(); + customCredentials.getRequestMetadata(CALL_URI); + JwtCredentials customCached = customCredentials.credentialsCache.getIfPresent(expectedClaims); + assertNotNull(customCached); + assertEquals("example.com", customCached.getUniverseDomain()); + } + private void verifyJwtAccess(Map> metadata, URI expectedAudience) throws IOException { assertNotNull(metadata); diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java index b4b06743ee24..0fd2e9a2273f 100644 --- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java +++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java @@ -71,8 +71,8 @@ class UserCredentialsTest extends BaseSerializationTest { static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu"; - static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws"; - static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY"; + static final String CLIENT_ID = "test-client-id"; + static final String REFRESH_TOKEN = "test-refresh-token"; private static final String ACCESS_TOKEN = "1/MkSJoj1xsli0AccessToken_NKPY2"; private static final String QUOTA_PROJECT = "sample-quota-project-id"; private static final Collection SCOPES = Collections.singletonList("dummy.scope"); @@ -883,6 +883,134 @@ void userCredentials_toBuilder_copyEveryAttribute() { assertEquals(credentials, otherCredentials); } + @Test + void refreshAccessToken_nonDefaultUniverse_throwsIOException() { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + URI[] tokenUris = { + null, + URI.create("https://oauth2.example.com/token"), + URI.create("https://accounts.google.com/o/oauth2/token"), + URI.create("/token"), + URI.create("mailto:user@example.com") + }; + + for (URI tokenUri : tokenUris) { + UserCredentials credentials = + createUniverseUserCredentials(transportFactory, tokenUri, "example.com"); + IOException error = assertThrows(IOException.class, credentials::refreshAccessToken); + assertTrue(error.getMessage().contains("example.com")); + } + + UserCredentials defaultUriCredentials = + createUniverseUserCredentials(transportFactory, null, "example.com"); + assertThrows(IOException.class, defaultUriCredentials::refresh); + assertThrows(IOException.class, defaultUriCredentials::refreshIfExpired); + + GoogleCredentials fromToBuilder = + createUniverseUserCredentials(transportFactory, null, null).toBuilder() + .setUniverseDomain("example.com") + .build(); + assertThrows(IOException.class, fromToBuilder::refreshAccessToken); + + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void idTokenWithAudience_nonDefaultUniverse_throwsIOException() { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + UserCredentials credentials = + createUniverseUserCredentials(transportFactory, null, "example.com"); + + assertThrows( + IOException.class, + () -> credentials.idTokenWithAudience("https://target.example.com", null)); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + + @Test + void refreshAccessToken_defaultUniverseWithDefaultOrCustomTokenUri_succeeds() throws IOException { + URI[] tokenUris = {null, URI.create("https://oauth2.example.com/token")}; + + for (URI tokenUri : tokenUris) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(tokenUri); + UserCredentials credentials = createUniverseUserCredentials(transportFactory, tokenUri, null); + + AccessToken token = credentials.refreshAccessToken(); + + URI expectedUri = tokenUri != null ? tokenUri : OAuth2Utils.TOKEN_SERVER_URI; + assertEquals(ACCESS_TOKEN, token.getTokenValue()); + assertEquals(expectedUri.toString(), transportFactory.transport.getRequest().getUrl()); + } + } + + @Test + void fromJson_nonDefaultUniverse_throwsIOException() { + String[] tokenUrls = { + null, OAuth2Utils.TOKEN_SERVER_URI.toString(), "https://oauth2.example.com/token" + }; + + for (String tokenUrl : tokenUrls) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, tokenUrl); + json.put("universe_domain", "example.com"); + + IOException error = + assertThrows(IOException.class, () -> UserCredentials.fromJson(json, transportFactory)); + assertTrue(error.getMessage().contains("example.com")); + assertEquals(0, transportFactory.transport.buildRequestCount); + assertNull(transportFactory.transport.getRequest()); + } + } + + @Test + void fromJson_defaultOrBlankUniverse_succeeds() throws IOException { + String[] universeDomains = {null, "", " ", "googleapis.com"}; + + for (String universeDomain : universeDomains) { + MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null); + GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, null); + if (universeDomain != null) { + json.put("universe_domain", universeDomain); + } + + UserCredentials credentials = UserCredentials.fromJson(json, transportFactory); + assertEquals("googleapis.com", credentials.getUniverseDomain()); + assertEquals(ACCESS_TOKEN, credentials.refreshAccessToken().getTokenValue()); + assertEquals( + OAuth2Utils.TOKEN_SERVER_URI.toString(), + transportFactory.transport.getRequest().getUrl()); + } + } + + private static MockTokenServerTransportFactory createMockTokenTransportFactory(URI tokenUri) { + MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); + if (tokenUri != null) { + transportFactory.transport.setTokenServerUri(tokenUri); + } + transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET); + transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN); + return transportFactory; + } + + private static UserCredentials createUniverseUserCredentials( + MockTokenServerTransportFactory transportFactory, URI tokenUri, String universeDomain) { + UserCredentials.Builder builder = + UserCredentials.newBuilder() + .setClientId(CLIENT_ID) + .setClientSecret(CLIENT_SECRET) + .setRefreshToken(REFRESH_TOKEN) + .setHttpTransportFactory(transportFactory); + if (tokenUri != null) { + builder.setTokenServerUri(tokenUri); + } + if (universeDomain != null) { + builder.setUniverseDomain(universeDomain); + } + return builder.build(); + } + static GenericJson writeUserJson( String clientId, String clientSecret, diff --git a/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md b/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md index fb89b3c46cf7..61c738de7c7b 100644 --- a/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md +++ b/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md @@ -1,6 +1,6 @@ --- name: bigquery-jdbc-testing -description: Conventions for writing and refactoring unit and integration tests in the BigQuery JDBC driver (java-bigquery-jdbc). Use this skill when adding, reviewing, or cleaning up tests under java-bigquery-jdbc/src/test, including tests for connection/credential setup, Storage Read/Write API clients, TPC/universe-domain behavior, and ITBase-derived integration tests. +description: Conventions for writing and refactoring unit and integration tests in the BigQuery JDBC driver (java-bigquery-jdbc). Use this skill when adding, reviewing, or cleaning up tests under java-bigquery-jdbc/src/test, including tests for connection/credential setup, Storage Read/Write API clients, universe-domain behavior, and ITBase-derived integration tests. --- # BigQuery JDBC Driver: Writing Tests @@ -39,7 +39,7 @@ Example: String url = getUriOAuthServiceAccount() .append("ProjectId", "project") - .append("universeDomain", "apis-tpczero.goog") + .append("universeDomain", "example.com") .toString(); ``` @@ -54,20 +54,20 @@ the assertions into one `private static` helper that takes the varying parts (credentials, endpoint URI, expected scopes, expected universe) as parameters. Each test then makes one call per object. -This is how `BigQueryConnectionTest` does it. `TPC_UNIVERSE`, `storageUri` and -`assertStorageCredentialsScoped` are private members of that class, not shared -fixtures: +This is how `BigQueryConnectionTest` does it. `CUSTOM_UNIVERSE`, `storageUri` +and `assertStorageCredentialsScoped` are private members of that class, not +shared fixtures: ```java assertStorageCredentialsScoped( readClient.getSettings().getCredentialsProvider().getCredentials(), - TPC_UNIVERSE, - storageUri(TPC_UNIVERSE, "BigQueryRead"), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryRead"), BigQueryReadSettings.getDefaultServiceScopes()); assertStorageCredentialsScoped( writeClient.getSettings().getCredentialsProvider().getCredentials(), - TPC_UNIVERSE, - storageUri(TPC_UNIVERSE, "BigQueryWrite"), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryWrite"), BigQueryWriteSettings.getDefaultServiceScopes()); ``` @@ -83,8 +83,8 @@ takes each side. In particular: `GoogleCredentials`, also test a credential that is *not* a service account, such as `getUriOAuthToken()` / `GoogleCredentials.create(AccessToken)`. Check that it passes through unchanged (`assertSame` where possible). -- **Universe domain.** If the code behaves differently for TPC - (`universeDomain=apis-tpczero.goog`), also test the **default** universe (no +- **Universe domain.** If the code behaves differently for a custom universe + domain (`universeDomain=example.com`), also test the **default** universe (no `universeDomain` property, so `googleapis.com`). - **Already configured input.** For example, credentials that already have explicit scopes must keep them. @@ -111,9 +111,10 @@ cases or weaken assertions (for example, changing `assertEquals` to misleads the reader. - Use try-with-resources for `Connection`, `Statement`, and `ResultSet`, or close them explicitly. IT suites share quotas. -- `@Tag("disable_tpc")` excludes a test from TPC runs. Remove it only when the - feature is known to work against TPC, and in that case add an assertion that - proves the intended path was used (for example `assertArrowResultSet`). +- `@Tag("disable_universe_domain")` excludes a test from custom universe domain + runs. Remove it only when the feature is known to work against a custom + universe domain, and in that case add an assertion that proves the intended + path was used (for example `assertArrowResultSet`). ## 5. Style and verification diff --git a/java-bigquery-jdbc/README.MD b/java-bigquery-jdbc/README.MD index 34bbb7b38c54..fbbeb7681295 100644 --- a/java-bigquery-jdbc/README.MD +++ b/java-bigquery-jdbc/README.MD @@ -40,6 +40,8 @@ libraryDependencies += "com.google.cloud" % "google-cloud-bigquery-jdbc" % "LATE See the [Authentication][authentication] section in the base directory's README. +For custom universe domain deployments, configure the target universe domain via the `universeDomain=` JDBC connection URL property, `DataSource.setUniverseDomain("")`, or the `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable (`GOOGLE_CLOUD_UNIVERSE_DOMAIN` configures client endpoints only and does not override credentials). Self-describing JSON credentials (Service Account JSON keys, External Account JSON files, and Application Default Credentials) always retain their own embedded `universe_domain`. When inline External Account / Workload Identity Federation (`OAuthType=4` with `BYOID_*` properties) is used without an explicit `BYOID_TokenUri`, the driver derives `https://sts./v1/token` when `universeDomain` is explicitly set (otherwise defaulting to `https://sts.googleapis.com/v1/token`). + ## Authorization The client application making API calls must be granted [authorization scopes][auth-scopes] required for the desired BigQuery JDBC APIs, and the authenticated principal must have the [IAM role(s)][predefined-iam-roles] required to access GCP resources using the BigQuery JDBC API calls. diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 1549d1b5fb4a..cb2f7cc28e92 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -109,7 +109,7 @@ The driver supports multiple OAuth 2.0 and identity workflows specified via the | **`0`** | **Service Account Key File (P12)** | `OAuthPvtKeyPath`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Path to `.p12` key file. Requires explicit `OAuthServiceAcctEmail` as `.p12` files do not contain email metadata. `OAuthP12Password` defaults to `notasecret`. | | **`0`** | **Service Account Key String (JSON)** | `OAuthPvtKey` | `OAuthServiceAcctEmail` | Raw JSON key file string content in URL. Service account email and private key are automatically extracted from the JSON string. | | **`0`** | **Service Account Key String (PKCS#8 / P12 Bytes)** | `OAuthPvtKey`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Raw PKCS#8 or P12 bytes key string content in URL. Requires explicit `OAuthServiceAcctEmail`. | -| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. | +| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. Custom `OAuthClientId` values must be configured as a **Desktop app** OAuth 2.0 client. | | **`2`** | **Pre-generated Access Token** | `OAuthAccessToken` | `OAuthAccessTokenReadonly` | Uses short-lived bearer token directly. `OAuthAccessTokenReadonly` defaults to `false`. | | **`2`** | **Pre-generated Refresh Token** | `OAuthRefreshToken`, `OAuthClientId`, `OAuthClientSecret` | None | Uses refresh token with client credentials to automatically mint access tokens. | | **`3`** | **Application Default Credentials (ADC)** | None | None | Uses GCP standard credential resolution (`GOOGLE_APPLICATION_CREDENTIALS` env var or `gcloud` CLI context). | @@ -160,7 +160,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `OAuthAccessToken` | `null` | Pre-generated OAuth 2.0 access token string. | | `OAuthAccessTokenReadonly` | `false` | Indicates whether the pre-generated access token has read-only scope. | | `OAuthRefreshToken` | `null` | Pre-generated refresh token to automatically mint access tokens. | -| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. | +| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. For `OAuthType=1`, custom client IDs must be configured as a **Desktop app** OAuth 2.0 client so dynamic loopback redirect URIs (`http://127.0.0.1:` or `http://[::1]:`) are accepted. | | `OAuthClientSecret` | *Google Secret* | OAuth 2.0 Client Secret for user authentication or refresh token flows. | | `ServiceAccountImpersonationEmail` | `null` | Target Service Account email to impersonate for query job execution. | | `ServiceAccountImpersonationChain` | `null` | Comma-separated list of service account emails representing the impersonation chain. | @@ -177,7 +177,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `BYOID_PoolUserProject` | `null` | Google Cloud project number associated with the workforce pool. | | `BYOID_SA_Impersonation_Uri` | `null` | Service Account impersonation URL for Workload Identity Federation. | | `BYOID_SubjectTokenType` | `urn:ietf:params:oauth:tokentype:id_token` | Type of subject token provided (e.g., `urn:ietf:params:oauth:tokentype:jwt`). | -| `BYOID_TokenUri` | `https://sts.googleapis.com/v1/token` | Security Token Service (STS) token exchange endpoint URI. | +| `BYOID_TokenUri` | `https://sts./v1/token` (`https://sts.googleapis.com/v1/token`) | Security Token Service (STS) token exchange endpoint URI. Derived from explicit `universeDomain` when omitted (defaults to `https://sts.googleapis.com/v1/token`). | ### Core Query & Catalog Properties @@ -253,7 +253,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `ProxyPwd` | `null` | Password for proxy server authentication. | | `EndpointOverrides` | `null` | Semicolon or comma-separated list of custom service endpoint overrides. Supported keys: `BIGQUERY`, `READ_API`, `OAUTH2`, `STS`, `ACCOUNTS`. | | `PrivateServiceConnectUris` | `null` | Alias for `EndpointOverrides`. Accepts the same custom service endpoint override format and supported keys. | -| `universeDomain` | `googleapis.com` | Domain name for Google Cloud Dedicated (GCD) or custom Google universe instances. | +| `universeDomain` | `null` (falls back to `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, then `googleapis.com`) | Domain name for Google Cloud Dedicated (GCD) or custom universe domain instances. Configures BigQuery, Storage Read/Write, and Cloud Logging client endpoints. Explicit `universeDomain` also applies to non-JSON credentials (PKCS#8/P12 keys, pre-generated tokens, and inline `BYOID_*` properties), while `GOOGLE_CLOUD_UNIVERSE_DOMAIN` applies to client endpoints only and JSON credentials always preserve their own `universe_domain`. | | `SSLTrustStore` | `null` | Path to custom Java TrustStore file containing trusted server certificates for SSL. | | `SSLTrustStorePwd` | `null` | Password for accessing the custom Java TrustStore file. | | `SSLTrustStoreType` | *System Default* (`JKS`/`PKCS12`) | Type of the custom Java TrustStore file. | @@ -272,8 +272,8 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `RetryInitialDelay` | `0` | Initial delay (in seconds) before executing the first retry attempt. | | `RetryMaxDelay` | `0` | Maximum delay limit (in seconds) between retry attempts. | | `MetaDataFetchThreadCount` | `32` | Thread pool size used to parallelize `DatabaseMetaData` catalog RPC calls. | -| `ConnectionPoolSize` | `10` | Maximum size of the internal connection pool when connection pooling is enabled. | -| `ListenerPoolSize` | `10` | Maximum size of the listener thread pool when connection pooling is enabled. | +| `ConnectionPoolSize` | `10` | Maximum number of idle physical connections retained in `PooledConnectionDataSource`'s built-in pool (`0` = unbounded). Latched from the first physical connection checkout; changing it on the same `PooledConnectionDataSource` afterward has no effect. | +| `ListenerPoolSize` | `10` | Maximum number of `ConnectionEventListener` instances that can be registered on a single `PooledConnection` (`0` = unbounded). | | `RequestReason` | `null` | Reason string passed in the `x-goog-request-reason` HTTP header for auditing. | ### OpenTelemetry & Cloud Observability Exporters @@ -625,9 +625,9 @@ jdbc:bigquery://https://bigquery.googleapis.com:443 ;PrivateServiceConnectUris=BIGQUERY=https://bigquery-privateendpoint.p.googleapis.com ``` -#### 3. Custom Universe Domains (`universeDomain`) +#### 3. Custom Universe Domains (`universeDomain` / `GOOGLE_CLOUD_UNIVERSE_DOMAIN`) -To target Google Cloud Dedicated (GCD) or non-default Universe Domain instances, specify `universeDomain`: +To target Google Cloud Dedicated (GCD) or custom universe domain instances, specify `universeDomain` in the connection URL (or set the `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable): ``` jdbc:bigquery://https://www.my-universe.cloud:443 @@ -699,7 +699,12 @@ Logging can also be configured globally across all driver connections using envi #### Log File Naming & Format -Log files are generated inside the specified `LogPath` directory with per-connection log isolation. +Log files are generated inside the specified `LogPath` directory with per-connection log isolation: +- **Global log file**: `BQ-JDBC-GLOBAL.log` (or `BQ-JDBC-GLOBAL--.log` on lock/ownership contention), used for pre-connection driver events (such as URL parsing warnings and connection-setup failures before a connection ID exists) and fallback records when a per-connection file cannot be opened; all connection-scoped logs go to the per-connection file. +- **Per-connection log file**: `BQ-JDBC--.log` (with a numeric collision suffix if needed). +- **File permissions**: Created directories and log files enforce owner-only permissions (`0700` on directories, `0600` on files) on POSIX filesystems and reject symbolic links. +- **Size cap & rotation**: Each active log file is capped at `1 GiB` by default (configurable via `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=`) and rotates onto a single `.1.log` backup file (falling back to in-place truncation if rotation is blocked). +- **URL `LogPath` restriction**: Set `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=false` to ignore `LogPath` values supplied via JDBC URLs or connection `Properties` and restrict file logging to `BIGQUERY_JDBC_LOG_PATH`. **Standard Log Record Format**: ```text diff --git a/java-bigquery-jdbc/pom.xml b/java-bigquery-jdbc/pom.xml index ff5f6a1e8739..2eb1d6ecafda 100644 --- a/java-bigquery-jdbc/pom.xml +++ b/java-bigquery-jdbc/pom.xml @@ -33,6 +33,9 @@ github google-cloud-bigquery-jdbc false + + @@ -65,6 +68,15 @@ org.apache.maven.plugins maven-failsafe-plugin + 1 + + @{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1g true @@ -513,14 +525,15 @@ so BigQueryJdbcCustomLoggerTest can read the JDK-internal child-logger list and assert that driver objects do not leak logger registrations. --> - --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMED + @{argLine} --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMED org.apache.maven.plugins maven-failsafe-plugin - --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED + + @{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1g --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java index 97e04b6d9564..ce54b3dbeec4 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java @@ -71,6 +71,9 @@ public abstract class BigQueryBaseResultSet extends BigQueryNoOpsResultSet protected final boolean isNested; protected boolean isClosed = false; protected boolean wasNull = false; + // getMetaData() is commonly called inside row loops; cache the immutable wrapper and record + // the adoption signal once per result set. ResultSet is single-threaded by JDBC contract. + private ResultSetMetaData cachedMetaData; private int fetchSize = -1; private Job job; private SQLWarning warnings; @@ -258,21 +261,26 @@ public boolean wasNull() throws SQLException { @Override public ResultSetMetaData getMetaData() throws SQLException { checkClosed(); - String connectionId = this.statement != null ? this.statement.connectionId : null; - ResultSetMetaData metaData; - try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) { - if (this.isNested) { - metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement); - } else { - metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement); + if (this.cachedMetaData == null) { + String connectionId = this.statement != null ? this.statement.connectionId : null; + ResultSetMetaData metaData; + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) { + if (this.isNested) { + metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement); + } else { + metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement); + } } + this.cachedMetaData = + BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId); + // Always a user call: no driver code invokes ResultSet.getMetaData(), so this is recorded + // regardless of whether the owning statement is internal (e.g. the result set that + // DatabaseMetaData.getExportedKeys hands back to the user). + TelemetryManager.recordFeatureUsage( + DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, + "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"); } - - TelemetryManager.recordFeatureUsage( - DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, - "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"); - - return BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId); + return this.cachedMetaData; } @Override @@ -290,7 +298,11 @@ public int getConcurrency() throws SQLException { @Override public Statement getStatement() throws SQLException { checkClosed(); - return this.statement; + if (this.statement == null || this.statement.isInternal()) { + return null; + } + Statement proxy = this.statement.getLogicalStatementProxy(); + return proxy != null ? proxy : this.statement; } @Override diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index a10d03c1fcaa..8699c261a60a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -28,6 +28,7 @@ import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.cloud.RetryOption; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.BigQueryOptions; @@ -36,6 +37,7 @@ import com.google.cloud.bigquery.DatasetId; import com.google.cloud.bigquery.Job; import com.google.cloud.bigquery.JobInfo; +import com.google.cloud.bigquery.JobStatus; import com.google.cloud.bigquery.Project; import com.google.cloud.bigquery.QueryJobConfiguration; import com.google.cloud.bigquery.QueryJobConfiguration.JobCreationMode; @@ -74,15 +76,18 @@ import java.util.ArrayList; import java.util.Collections; import java.util.ConcurrentModificationException; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; @@ -155,7 +160,6 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME, BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME, BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME, - BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME, BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME, BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME, @@ -176,13 +180,13 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQuery bigQuery; String connectionUrl; Set openStatements; - boolean autoCommit; + volatile boolean autoCommit; int transactionIsolation; - List sqlWarnings; + final List sqlWarnings; String catalog; String gcpTelemetryCredentials; String gcpTelemetryProjectId; - int holdability; + int holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; long retryTimeoutInSeconds; Duration retryTimeoutDuration; long retryInitialDelayInSeconds; @@ -191,8 +195,11 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { Duration retryMaxDelayDuration; // transactionStarted is false by default. // when autocommit is false transaction starts and session is initialized. - boolean transactionStarted; - boolean isClosed; + volatile boolean transactionStarted; + volatile boolean isClosed; + private volatile boolean closeInitiated = false; + private final Object closeStateLock = new Object(); + private final Object lifecycleLock = new Object(); DatasetId defaultDataset; String location; boolean enableHighThroughputAPI; @@ -249,12 +256,19 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { private Context otelContext; Tracer tracer = OpenTelemetry.noop().getTracer(BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME); - DatabaseMetaData databaseMetaData; + + private volatile DatabaseMetaData databaseMetaData; + private final Object metaDataLock = new Object(); + + // A Connection may be used from several threads; compareAndSet keeps the adoption signal at + // exactly one record per connection without a lock. + private final AtomicBoolean metadataRetrievalRecorded = new AtomicBoolean(); Boolean reqGoogleDriveScope; private final Properties clientInfo = new Properties(); private boolean isReadOnlyTokenUsed = false; private final ExecutorService metadataExecutor; private final ExecutorService queryExecutor; + private final SessionState initialSessionState; /** * All session-scoped state, published as a single immutable snapshot. @@ -264,6 +278,35 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { private final AtomicReference sessionState = new AtomicReference<>(new SessionState(null, Collections.emptyList(), false)); + static String sanitizeForLog(String value) { + if (value == null) { + return null; + } + StringBuilder sb = null; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < 0x20 || c == 0x7F) { + if (sb == null) { + sb = new StringBuilder(value.length()).append(value, 0, i); + } + sb.append('?'); + } else if (sb != null) { + sb.append(c); + } + } + return sb == null ? value : sb.toString(); + } + + static String maskPropertyValue(String key, Object value) { + if (value == null) { + return null; + } + if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) { + return "*****"; + } + return sanitizeForLog(String.valueOf(value)); + } + BigQueryConnection(String url) throws SQLException { this(url, DataSource.fromUrl(url)); } @@ -275,23 +318,41 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { .put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, this.connectionId) .build(); this.otelContext = Context.current().with(baggage); + String rawLogLevel = ds.getLogLevel(); + if (rawLogLevel == null) { + rawLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); + } + String connLogPath = + BigQueryJdbcUrlUtility.resolveEffectiveLogPath( + ds.getLogPath(), + System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR), + rawLogLevel != null && !ds.getEnableGcpLogExporter()); + BigQueryJdbcRootLogger.registerConnection(this.connectionId, rawLogLevel, connLogPath); + boolean initialized = false; + ExecutorService createdQueryExecutor = null; + ExecutorService createdMetadataExecutor = null; try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { this.connectionUrl = url; if (LOG.isLoggable(Level.CONFIG)) { Properties connectionProps = ds.createProperties(); Properties maskedProps = new Properties(); for (String name : connectionProps.stringPropertyNames()) { - String value = connectionProps.getProperty(name); - if (!SAFE_TO_LOG_PROPERTIES.contains(name)) { - value = "*****"; - } - maskedProps.setProperty(name, value); + maskedProps.setProperty( + sanitizeForLog(name), maskPropertyValue(name, connectionProps.getProperty(name))); } LOG.config("Connection properties: %s", maskedProps.toString()); } this.openStatements = ConcurrentHashMap.newKeySet(); this.autoCommit = true; - this.sqlWarnings = new ArrayList<>(); + this.sqlWarnings = new CopyOnWriteArrayList<>(); + if (ds.getLogPath() != null && !BigQueryJdbcUrlUtility.isUrlLogPathAllowed()) { + this.sqlWarnings.add( + new SQLWarning( + String.format( + "Ignoring URL/Properties %s because system property %s is false.", + BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY))); + } this.transactionStarted = false; this.isClosed = false; @@ -310,12 +371,15 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcOAuthUtility.parseOAuthProperties(ds, this.connectionClassName); this.isReadOnlyTokenUsed = checkIsReadOnlyTokenUsed(this.authProperties); this.catalog = ds.getProjectId(); - this.universeDomain = ds.getUniverseDomain(); + this.universeDomain = ds.resolveUniverseDomain(); this.overrideProperties = ds.getOverrideProperties(); - if (this.universeDomain != null) { + // Only record an explicit URL/DataSource universeDomain in overrideProperties for non-JSON + // credentials; JSON credentials always keep their own parsed universe_domain. + String explicitUniverseDomain = ds.getUniverseDomain(); + if (explicitUniverseDomain != null) { this.overrideProperties.put( - BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, this.universeDomain); + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, explicitUniverseDomain); } this.reqGoogleDriveScope = @@ -383,11 +447,12 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { this.unsupportedHTAPIFallback = ds.getUnsupportedHTAPIFallback(); this.maxResults = ds.getMaxResults(); Map queryPropertiesMap = ds.getQueryProperties(); - this.sessionState.set( + this.initialSessionState = new SessionState( getSessionPropertyFromQueryProperties(queryPropertiesMap), convertMapToConnectionPropertiesList(queryPropertiesMap), - false)); + false); + this.sessionState.set(this.initialSessionState); this.enableWriteAPI = ds.getEnableWriteAPI(); this.writeAPIActivationRowCount = ds.getSwaActivationRowCount(); this.writeAPIAppendRowCount = ds.getSwaAppendRowCount(); @@ -413,11 +478,28 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { this.bigQuery = getBigQueryConnection(); // Cached pool executes queries immediately without queueing and reclaims all idle threads // when inactive, minimizing resources. - this.queryExecutor = + createdQueryExecutor = BigQueryJdbcMdc.newCachedThreadPool(String.format("BQ-Query-%s", connectionId)); - this.metadataExecutor = + this.queryExecutor = createdQueryExecutor; + createdMetadataExecutor = BigQueryJdbcMdc.newFixedThreadPool( String.format("BQ-Metadata-%s", connectionId), this.metadataFetchThreadCount); + this.metadataExecutor = createdMetadataExecutor; + BigQueryJdbcRootLogger.trackConnectionLifecycle(this, this.connectionId); + initialized = true; + } finally { + if (!initialized) { + if (createdQueryExecutor != null) { + createdQueryExecutor.shutdownNow(); + } + if (createdMetadataExecutor != null) { + createdMetadataExecutor.shutdownNow(); + } + BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); + BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); + BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); + this.openTelemetry = null; + } } } @@ -511,6 +593,38 @@ public Statement createStatement() throws SQLException { return currentStatement; } + /** + * Creates a {@code Statement} for the driver's own use (for example the {@code isValid} + * health-check query). Identical to {@link #createStatement()} except that neither the statement + * nor anything it executes is reported as user activity in usage telemetry. + */ + BigQueryStatement createStatementInternal() throws SQLException { + checkClosed(); + BigQueryStatement statement = new BigQueryStatement(this, false); + LOG.fine("Internal Statement %s created.", statement); + addOpenStatements(statement); + return statement; + } + + /** + * Creates a {@code PreparedStatement} for the driver's own metadata queries. Identical to {@link + * #prepareStatement(String)} except that neither the statement, its parameter bindings, nor + * anything it executes is reported as user activity in usage telemetry. + */ + BigQueryPreparedStatement prepareStatementInternal(String sql) throws SQLException { + return prepareStatementInternal(sql, false); + } + + BigQueryPreparedStatement prepareStatementInternal(String sql, boolean skipDryRun) + throws SQLException { + checkClosed(); + BigQueryPreparedStatement statement = + new BigQueryPreparedStatement(this, sql, skipDryRun, false); + LOG.fine("Internal Prepared Statement %s created.", statement); + addOpenStatements(statement); + return statement; + } + /** * Creates and returns a new {@code Statement} object for executing BigQuery SQL queries. This * method is similar to {@link BigQueryConnection#createStatement()}, but it overrides the type @@ -887,7 +1001,8 @@ public boolean isValid(int timeout) throws SQLException { throw new BigQueryJdbcException("timeout must be >= 0"); } if (!isClosed()) { - try (Statement statement = createStatement(); + // Internal statement: a pool health-check must not count as user statements or SELECTs. + try (Statement statement = createStatementInternal(); ResultSet rs = statement.executeQuery("SELECT 1")) { LOG.finer("Running validation query"); if (rs.next()) { @@ -904,7 +1019,40 @@ public boolean isValid(int timeout) throws SQLException { @Override public void abort(Executor executor) throws SQLException { - close(); + if (executor == null) { + throw new BigQueryJdbcException("Executor cannot be null."); + } + synchronized (this.closeStateLock) { + if (this.isClosed || this.closeInitiated) { + return; + } + this.closeInitiated = true; + try { + executor.execute( + () -> { + this.isClosed = true; + String previousConnectionId = BigQueryJdbcMdc.getConnectionId(); + try { + BigQueryJdbcMdc.registerInstance(this.connectionId); + LOG.fine("Aborting Connection %s", this); + closeImpl(); + } catch (SQLException ex) { + LOG.warning(ex, "Failed to release resources during connection abort"); + } finally { + if (previousConnectionId != null + && !previousConnectionId.equals(this.connectionId)) { + BigQueryJdbcMdc.registerInstance(previousConnectionId); + } + } + }); + this.isClosed = true; + } catch (RuntimeException | Error ex) { + if (!this.isClosed) { + this.closeInitiated = false; + } + throw ex; + } + } } @Override @@ -947,7 +1095,8 @@ public void setClientInfo(Properties properties) { @Override public SQLWarning getWarnings() { - return this.sqlWarnings.isEmpty() ? null : this.sqlWarnings.get(0); + Iterator iterator = this.sqlWarnings.iterator(); + return iterator.hasNext() ? iterator.next() : null; } @Override @@ -1009,10 +1158,10 @@ public void rollback() throws SQLException { "Cannot rollback without an active transaction. Please set setAutoCommit to false to" + " start a transaction."); } - rollbackImpl(); + rollbackImpl(!getAutoCommit()); } - private void rollbackImpl() throws SQLException { + private void rollbackImpl(boolean startNextTransaction) throws SQLException { try { QueryJobConfiguration transactionRollbackJobConfig = QueryJobConfiguration.newBuilder("ROLLBACK TRANSACTION;") @@ -1020,9 +1169,9 @@ private void rollbackImpl() throws SQLException { Collections.singletonList(this.sessionState.get().sessionInfo)) .build(); Job rollbackJob = this.bigQuery.create(JobInfo.of(transactionRollbackJobConfig)); - rollbackJob.waitFor(); + waitForTransactionJob(rollbackJob, "rollback"); this.transactionStarted = false; - if (!getAutoCommit()) { + if (startNextTransaction) { beginTransaction(); } } catch (BigQueryException ex) { @@ -1033,15 +1182,135 @@ private void rollbackImpl() throws SQLException { } } + private void waitForTransactionJob(Job job, String operationName) + throws BigQueryJdbcException, InterruptedException { + Job completedJob = + this.retryTimeoutInSeconds > 0L + ? job.waitFor(RetryOption.totalTimeoutDuration(this.retryTimeoutDuration)) + : job.waitFor(); + if (completedJob == null) { + throw new BigQueryJdbcException( + "Transaction " + operationName + " job no longer exists before completion."); + } + JobStatus status = completedJob.getStatus(); + if (status != null) { + if (status.getState() != null && status.getState() != JobStatus.State.DONE) { + throw new BigQueryJdbcException( + "Timed out waiting for transaction " + operationName + " job to complete."); + } + if (status.getError() != null) { + throw new BigQueryJdbcException( + "Transaction " + operationName + " job failed: " + status.getError().getMessage()); + } + } + } + + /** + * Resets mutable JDBC connection state, closes remaining open statements, rolls back any active + * transaction without starting a follow-up transaction, and aborts any driver-created BigQuery + * session before returning this physical connection for pooled reuse. + */ + void resetForReuse() throws SQLException { + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { + LOG.finer("++enter++"); + synchronized (this.lifecycleLock) { + checkClosed(); + boolean callerInterrupted = Thread.interrupted(); + try { + SQLException exceptionToThrow = closeOpenStatements(); + + this.autoCommit = true; + boolean rollbackFailed = false; + if (this.transactionStarted) { + try { + rollbackImpl(false); + } catch (SQLException e) { + rollbackFailed = true; + exceptionToThrow = accumulateException(exceptionToThrow, e); + } + } + + boolean sessionAbortFailed = false; + SessionState snapshot = this.sessionState.get(); + if (snapshot.sessionInfo != null && snapshot.createdByDriver) { + try { + abortSession(snapshot, true); + } catch (SQLException e) { + sessionAbortFailed = true; + exceptionToThrow = accumulateException(exceptionToThrow, e); + } + } + if (!rollbackFailed && !sessionAbortFailed) { + this.sessionState.set(this.initialSessionState); + } + + this.clientInfo.clear(); + this.sqlWarnings.clear(); + this.holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT; + + if (exceptionToThrow != null) { + throw exceptionToThrow; + } + } finally { + if (callerInterrupted) { + Thread.currentThread().interrupt(); + } + LOG.finer("++exit++"); + } + } + } + } + + private SQLException closeOpenStatements() { + SQLException exceptionToThrow = null; + for (Statement statement : new ArrayList<>(this.openStatements)) { + try { + statement.close(); + } catch (SQLException e) { + exceptionToThrow = accumulateException(exceptionToThrow, e); + } + } + this.openStatements.clear(); + return exceptionToThrow; + } + + private static SQLException accumulateException(SQLException current, SQLException next) { + if (current == null) { + return next; + } + if (current != next) { + current.addSuppressed(next); + } + return current; + } + @Override public DatabaseMetaData getMetaData() throws SQLException { - if (databaseMetaData == null) { - databaseMetaData = new BigQueryDatabaseMetaData(this); + checkClosed(); + DatabaseMetaData metaData = getMetaDataInternal(); + // Adoption signal, recorded once per connection on the first user call. Tied to this flag + // rather than to instance creation so the driver's own startup lookup does not consume it. + if (this.metadataRetrievalRecorded.compareAndSet(false, true)) { + TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL); } + return metaData; + } - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL); - - return databaseMetaData; + /** + * Same instance as {@link #getMetaData()} without the usage-telemetry record. Driver-internal. + */ + DatabaseMetaData getMetaDataInternal() { + DatabaseMetaData result = this.databaseMetaData; + if (result == null) { + synchronized (this.metaDataLock) { + result = this.databaseMetaData; + if (result == null) { + result = new BigQueryDatabaseMetaData(this); + this.databaseMetaData = result; + } + } + } + return result; } @Override @@ -1081,152 +1350,146 @@ public void setHoldability(int holdability) throws SQLException { */ @Override public void close() throws SQLException { - if (isClosed()) { - return; + synchronized (this.closeStateLock) { + if (this.isClosed || this.closeInitiated) { + return; + } + this.closeInitiated = true; } - LOG.fine("Closing Connection " + this); - closeImpl(); - } - - private void closeImpl() throws SQLException { - SQLException exceptionToThrow = null; + String previousConnectionId = BigQueryJdbcMdc.getConnectionId(); try { - if (this.bigQueryReadClient != null) { - this.bigQueryReadClient.shutdown(); - } - if (this.bigQueryWriteClient != null) { - this.bigQueryWriteClient.shutdown(); - } - if (this.metadataExecutor != null) { - this.metadataExecutor.shutdown(); - } - if (this.queryExecutor != null) { - this.queryExecutor.shutdown(); + BigQueryJdbcMdc.registerInstance(this.connectionId); + LOG.fine("Closing Connection %s", this); + closeImpl(); + } finally { + if (previousConnectionId != null && !previousConnectionId.equals(this.connectionId)) { + BigQueryJdbcMdc.registerInstance(previousConnectionId); } + } + } - for (Statement statement : this.openStatements) { - try { - statement.close(); - } catch (SQLException e) { - if (exceptionToThrow == null) { - exceptionToThrow = e; - } else { - exceptionToThrow.addSuppressed(e); - } + private void closeImpl() throws SQLException { + synchronized (this.lifecycleLock) { + SQLException exceptionToThrow = null; + boolean callerInterrupted = Thread.interrupted(); + try { + if (this.bigQueryReadClient != null) { + this.bigQueryReadClient.shutdown(); + } + if (this.bigQueryWriteClient != null) { + this.bigQueryWriteClient.shutdown(); + } + if (this.metadataExecutor != null) { + this.metadataExecutor.shutdown(); + } + if (this.queryExecutor != null) { + this.queryExecutor.shutdown(); } - } - this.openStatements.clear(); - if (isTransactionStarted()) { - try { - // It looks like there's no need to start a new transaction after a rollback, - // but the commit behavior is preserved since close() may still fail before isClosed is - // updated. - rollbackImpl(); - } catch (SQLException e) { - if (exceptionToThrow == null) { - exceptionToThrow = e; - } else { - exceptionToThrow.addSuppressed(e); + exceptionToThrow = closeOpenStatements(); + + if (isTransactionStarted()) { + try { + rollbackImpl(false); + } catch (SQLException e) { + exceptionToThrow = accumulateException(exceptionToThrow, e); } } - } - SessionState snapshot = this.sessionState.get(); - if (snapshot.sessionInfo != null && snapshot.createdByDriver) { - try { - abortSession(snapshot); - } catch (SQLException e) { - if (exceptionToThrow == null) { - exceptionToThrow = e; - } else { - exceptionToThrow.addSuppressed(e); + SessionState snapshot = this.sessionState.get(); + if (snapshot.sessionInfo != null && snapshot.createdByDriver) { + try { + abortSession(snapshot, false); + } catch (SQLException e) { + exceptionToThrow = accumulateException(exceptionToThrow, e); } } - } - boolean interrupted = Thread.currentThread().isInterrupted(); - InterruptedException terminationInterruptedException = null; + boolean interrupted = callerInterrupted || Thread.currentThread().isInterrupted(); + InterruptedException terminationInterruptedException = null; - try { - if (this.bigQueryReadClient != null) { - if (interrupted) { + try { + if (this.bigQueryReadClient != null) { + if (interrupted) { + this.bigQueryReadClient.shutdownNow(); + } else { + this.bigQueryReadClient.awaitTermination(1, TimeUnit.MINUTES); + } + } + if (this.bigQueryWriteClient != null) { + if (interrupted) { + this.bigQueryWriteClient.shutdownNow(); + } else { + this.bigQueryWriteClient.awaitTermination(1, TimeUnit.MINUTES); + } + } + if (this.metadataExecutor != null) { + if (interrupted || !this.metadataExecutor.awaitTermination(10, TimeUnit.SECONDS)) { + this.metadataExecutor.shutdownNow(); + } + } + if (this.queryExecutor != null) { + if (interrupted || !this.queryExecutor.awaitTermination(10, TimeUnit.SECONDS)) { + this.queryExecutor.shutdownNow(); + } + } + } catch (InterruptedException e) { + interrupted = true; + terminationInterruptedException = e; + if (this.bigQueryReadClient != null) { this.bigQueryReadClient.shutdownNow(); - } else { - this.bigQueryReadClient.awaitTermination(1, TimeUnit.MINUTES); } - } - if (this.bigQueryWriteClient != null) { - if (interrupted) { + if (this.bigQueryWriteClient != null) { this.bigQueryWriteClient.shutdownNow(); - } else { - this.bigQueryWriteClient.awaitTermination(1, TimeUnit.MINUTES); } - } - if (this.metadataExecutor != null) { - if (interrupted || !this.metadataExecutor.awaitTermination(10, TimeUnit.SECONDS)) { + if (this.metadataExecutor != null) { this.metadataExecutor.shutdownNow(); } - } - if (this.queryExecutor != null) { - if (interrupted || !this.queryExecutor.awaitTermination(10, TimeUnit.SECONDS)) { + if (this.queryExecutor != null) { this.queryExecutor.shutdownNow(); } + } finally { + try { + if (this.bigQueryReadClient != null) { + this.bigQueryReadClient.close(); + } + } finally { + if (this.bigQueryWriteClient != null) { + this.bigQueryWriteClient.close(); + } + } } - } catch (InterruptedException e) { - interrupted = true; - terminationInterruptedException = e; - if (this.bigQueryReadClient != null) { - this.bigQueryReadClient.shutdownNow(); - } - if (this.bigQueryWriteClient != null) { - this.bigQueryWriteClient.shutdownNow(); - } - if (this.metadataExecutor != null) { - this.metadataExecutor.shutdownNow(); + + if (interrupted) { + Thread.currentThread().interrupt(); } - if (this.queryExecutor != null) { - this.queryExecutor.shutdownNow(); + if (terminationInterruptedException != null) { + exceptionToThrow = + accumulateException( + exceptionToThrow, + new BigQueryJdbcException( + "Interrupted during close", terminationInterruptedException)); } + } catch (ConcurrentModificationException ex) { + throw new BigQueryJdbcException("Concurrent modification during close", ex); } finally { - try { - if (this.bigQueryReadClient != null) { - this.bigQueryReadClient.close(); - } - } finally { - if (this.bigQueryWriteClient != null) { - this.bigQueryWriteClient.close(); - } + this.isClosed = true; + if (callerInterrupted) { + Thread.currentThread().interrupt(); } - } - - if (interrupted) { - Thread.currentThread().interrupt(); - } - if (terminationInterruptedException != null) { - BigQueryJdbcException interruptedException = - new BigQueryJdbcException("Interrupted during close", terminationInterruptedException); - if (exceptionToThrow == null) { - exceptionToThrow = interruptedException; - } else { - exceptionToThrow.addSuppressed(interruptedException); + if (this.connectionId.equals(BigQueryJdbcMdc.getConnectionId())) { + BigQueryJdbcMdc.clear(); } + BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); + BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); + BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); + this.openTelemetry = null; } - } catch (ConcurrentModificationException ex) { - throw new BigQueryJdbcException("Concurrent modification during close", ex); - } finally { - BigQueryJdbcMdc.clear(); - BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); - BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); - BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); - this.openTelemetry = null; - } - this.isClosed = true; - - if (exceptionToThrow != null) { - throw exceptionToThrow; + if (exceptionToThrow != null) { + throw exceptionToThrow; + } } } @@ -1244,7 +1507,7 @@ public boolean isClosed() { } private void checkClosed() throws BigQueryJdbcException { - if (isClosed()) { + if (this.isClosed || this.closeInitiated) { throw new BigQueryJdbcException("This " + getClass().getName() + " has been closed"); } } @@ -1333,6 +1596,7 @@ private OpenTelemetry getOpenTelemetryInstance() { effectiveProjectId, this.credentials, this.proxyProperties); + this.openTelemetry = openTelemetry; boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry; Logging localLoggingClient = null; @@ -1344,7 +1608,8 @@ private OpenTelemetry getOpenTelemetryInstance() { this.gcpTelemetryCredentials, effectiveProjectId, this.credentials, - this.headerProvider); + this.headerProvider, + this.universeDomain); } if (this.enableGcpLogExporter || hasExternalOtel) { @@ -1589,32 +1854,44 @@ private void commitTransaction() throws BigQueryJdbcException { Collections.singletonList(this.sessionState.get().sessionInfo)) .build(); Job commitJob = this.bigQuery.create(JobInfo.of(transactionCommitJobConfig)); - commitJob.waitFor(); + waitForTransactionJob(commitJob, "commit"); this.transactionStarted = false; + } catch (BigQueryException ex) { + throw new BigQueryJdbcException("Failed to commit transaction", ex); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new BigQueryJdbcException("Interrupted during commitTransaction", ex); } } - private void abortSession(SessionState snapshot) throws BigQueryJdbcException { + private void abortSession(SessionState snapshot, boolean throwOnError) + throws BigQueryJdbcException { + boolean clearLocalSession = false; try { - LOG.fine("Aborting session on connection close: %s", snapshot.sessionInfo.getValue()); + LOG.fine("Aborting session: %s", snapshot.sessionInfo.getValue()); QueryJobConfiguration abortSessionJobConfig = QueryJobConfiguration.newBuilder("CALL BQ.ABORT_SESSION();") .setConnectionProperties(Collections.singletonList(snapshot.sessionInfo)) .build(); this.bigQuery.query(abortSessionJobConfig); + clearLocalSession = true; } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new BigQueryJdbcException("Interrupted during session abort", ex); } catch (BigQueryException ex) { + if (throwOnError) { + throw new BigQueryJdbcException("Failed to abort session", ex); + } LOG.warning( - "Failed to abort session during session abort (session may have already ended): " - + ex.getMessage()); + ex, + "Failed to abort session during session abort (session may have already ended): %s", + ex.getMessage()); + clearLocalSession = true; } finally { - this.sessionState.updateAndGet(SessionState::withoutSession); - this.transactionStarted = false; + if (clearLocalSession) { + this.sessionState.updateAndGet(SessionState::withoutSession); + this.transactionStarted = false; + } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java index c912fc1e6f7e..fcd6c4c5296f 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java @@ -1568,7 +1568,8 @@ void appendGraphTableRows( validateCatalogIdentifier(project); String formattedSql = replaceSqlParameters(getGraphTablesSqlContent(), project, scope); - try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) { + try (PreparedStatement statement = + this.connection.prepareStatementInternal(formattedSql, true)) { statement.setString(1, effectiveSchemaPattern == null ? "%" : effectiveSchemaPattern); statement.setString(2, effectiveTablePattern); @@ -1868,7 +1869,8 @@ void appendGraphColumnRows( } String formattedSql = replaceSqlParameters(getGraphColumnsSqlContent(), project, scope); - try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) { + try (PreparedStatement statement = + this.connection.prepareStatementInternal(formattedSql, true)) { statement.setString(1, effectiveSchemaLike); statement.setString(2, effectiveTableLike); statement.setString(3, effectiveColumnLike); @@ -2460,7 +2462,8 @@ private void appendGraphPrimaryKeys( validateCatalogIdentifier(project); String formattedSql = replaceSqlParameters(getGraphPrimaryKeysSqlContent(), project, scope); - try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) { + try (PreparedStatement statement = + this.connection.prepareStatementInternal(formattedSql, true)) { statement.setString(1, table); // exact "." try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { @@ -2623,7 +2626,7 @@ public ResultSet getExportedKeys(String catalog, String schema, String table) validateSchemaIdentifier(schema); String sql = getExportedKeysSqlContent(); String formattedSql = replaceSqlParameters(sql, catalog, schema); - PreparedStatement stmt = this.connection.prepareStatement(formattedSql, true); + PreparedStatement stmt = this.connection.prepareStatementInternal(formattedSql, true); if (stmt == null) { throw new BigQueryJdbcException("Failed to prepare statement for getExportedKeys"); } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 67e74d74c114..de14bdbfc1da 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -150,6 +150,7 @@ public Connection connect(String url, Properties info) throws SQLException { Level logLevel; String logPath; + boolean ignoredUrlLogPath; try { // LogLevel String logLevelStr = @@ -161,14 +162,11 @@ public Connection connect(String url, Properties info) throws SQLException { logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr); // LogPath - logPath = + String urlLogPath = BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME); - if (logPath == null) { - logPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); - } + String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); - // Fallback to default path only if not specified and not in Cloud-Only mode String enableGcpLogExporterStr = BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); @@ -179,9 +177,10 @@ public Connection connect(String url, Properties info) throws SQLException { enableGcpLogExporterStr, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); } - if (logPath == null && !enableGcpLogExporter) { - logPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH; - } + ignoredUrlLogPath = !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && urlLogPath != null; + logPath = + BigQueryJdbcUrlUtility.resolveEffectiveLogPath( + urlLogPath, envLogPath, !enableGcpLogExporter); BigQueryJdbcRootLogger.setLevel(logLevel, logPath); } catch (RuntimeException e) { @@ -190,34 +189,47 @@ public Connection connect(String url, Properties info) throws SQLException { } // Logging starts from here. - DataSource ds; - try { - ds = DataSource.fromUrl(connectionUri); - } catch (BigQueryJdbcRuntimeException e) { - LOG.log(Level.SEVERE, "Failed to parse connection URL", e); - throw new BigQueryJdbcException("Failed to parse connection URL", e); + BigQueryConnection connection; + try (BigQueryJdbcMdc.MdcCloseable preConnect = + BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) { + if (ignoredUrlLogPath) { + LOG.warning( + "Ignoring URL/Properties %s because system property %s is false.", + BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); + } + DataSource ds; + try { + ds = DataSource.fromUrl(connectionUri); + } catch (BigQueryJdbcRuntimeException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL", e); + throw new BigQueryJdbcException("Failed to parse connection URL", e); + } + authType = TelemetryManager.toAuthenticationType(ds.getOAuthType()); + if (customOpenTelemetryObj instanceof OpenTelemetry) { + ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj); + } + connection = new BigQueryConnection(connectionUri, ds); } - authType = TelemetryManager.toAuthenticationType(ds.getOAuthType()); - if (customOpenTelemetryObj instanceof OpenTelemetry) { - ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj); + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(connection.getConnectionId())) { + DatabaseMetaData metaData = connection.getMetaDataInternal(); + LOG.info( + "Driver info : { {Database Product Name : %s}, " + + "{Database Product Version : %s}, " + + "{Driver Name : %s}, " + + "{Driver Version : %s}, " + + "{LogLevel : %s}, " + + "{LogPath : %s}, " + + "{Driver Instance : %s} }", + metaData.getDatabaseProductName(), + metaData.getDatabaseProductVersion(), + metaData.getDriverName(), + metaData.getDriverVersion(), + logLevel, + logPath, + this.toString()); } - BigQueryConnection connection = new BigQueryConnection(connectionUri, ds); - DatabaseMetaData metaData = connection.getMetaData(); - LOG.info( - "Driver info : { {Database Product Name : %s}, " - + "{Database Product Version : %s}, " - + "{Driver Name : %s}, " - + "{Driver Version : %s}, " - + "{LogLevel : %s}, " - + "{LogPath : %s}, " - + "{Driver Instance : %s} }", - metaData.getDatabaseProductName(), - metaData.getDatabaseProductVersion(), - metaData.getDriverName(), - metaData.getDriverVersion(), - logLevel, - logPath, - this.toString()); Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java index fc724e53e543..a80774e90c31 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java @@ -35,11 +35,13 @@ class BigQueryJdbcContextProxy implements InvocationHandler { private final Object target; private final String connectionId; + private final ConnectionLogContext connectionContext; private final Class interfaceType; private BigQueryJdbcContextProxy(Object target, String connectionId, Class interfaceType) { this.target = target; this.connectionId = connectionId; + this.connectionContext = BigQueryJdbcRootLogger.resolveContext(connectionId); this.interfaceType = interfaceType; } @@ -132,7 +134,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl } // Wrap execution in the context of the active connection for all non-bypassed methods - try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) { + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) { boolean isFinerLoggable = LOG.isLoggable(Level.FINER); String targetClassName = null; if (isFinerLoggable) { @@ -173,7 +175,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl // Unified Context Logger: Captures and logs every exception exactly once with the Connection // context - try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) { + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) { String errMsg = cause.getMessage() != null ? cause.getMessage() : cause.toString(); LOG.severe("Exception occurred during " + methodName + ": " + errMsg, cause); } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java index 0acea77e5bf6..5d730143ddc4 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java @@ -17,11 +17,13 @@ package com.google.cloud.bigquery.jdbc; import java.util.function.Supplier; +import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class BigQueryJdbcCustomLogger extends Logger { + private volatile boolean hasOwnHandlers; protected BigQueryJdbcCustomLogger(String name, String resourceBundleName) { super(name, resourceBundleName); @@ -32,6 +34,42 @@ public BigQueryJdbcCustomLogger(String name) { this(name, null); } + @Override + public synchronized void addHandler(Handler handler) throws SecurityException { + super.addHandler(handler); + this.hasOwnHandlers = getHandlers().length > 0; + } + + @Override + public synchronized void removeHandler(Handler handler) throws SecurityException { + super.removeHandler(handler); + this.hasOwnHandlers = getHandlers().length > 0; + } + + @Override + public boolean isLoggable(Level level) { + if (!isSuperLoggable(level)) { + return false; + } + return isLoggableAfterSuper(level, BigQueryJdbcMdc.getConnectionContext()); + } + + boolean isSuperLoggable(Level level) { + return level != null && super.isLoggable(level); + } + + boolean isLoggableAfterSuper(Level level, ConnectionLogContext context) { + if (this.getLevel() != null + || this.hasOwnHandlers + || BigQueryJdbcRootLogger.hasExternalHandler()) { + return true; + } + if (context != null && context.hasExplicitLevel()) { + return context.isLoggable(level); + } + return true; + } + private void logWithCaller(Level level, Supplier msgSupplier) { logWithCaller(level, null, msgSupplier); } @@ -116,6 +154,7 @@ private static boolean isLoggerClass(String className) { || className.equals("com.google.cloud.bigquery.jdbc.BigQueryJdbcResultSetLogger") || className.startsWith("com.google.cloud.bigquery.jdbc.BigQueryJdbcRootLogger") || className.equals("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler") + || className.startsWith("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler$") || className.equals(BigQueryJdbcLogRecord.class.getName()); } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java index 254cdc5cc2fa..e9638cd8beeb 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java @@ -33,26 +33,54 @@ class BigQueryJdbcMdc { private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(BigQueryJdbcMdc.class.getName()); - private static final InheritableThreadLocal currentConnectionId = + private static final InheritableThreadLocal currentContext = new InheritableThreadLocal<>(); - /** Sets the current connection context on the executing thread. */ + /** + * Sets the current connection context on the executing thread and restores any prior connection + * context when closed. + */ static MdcCloseable registerInstance(String connectionId) { - if (connectionId != null) { - currentConnectionId.set(connectionId); + if (connectionId == null) { + return withContext(null); + } + ConnectionLogContext context = BigQueryJdbcRootLogger.getConnectionContext(connectionId); + if (context == null) { + context = ConnectionLogContext.unregistered(connectionId); + } + return withContext(context); + } + + static MdcCloseable withContext(ConnectionLogContext context) { + ConnectionLogContext previous = currentContext.get(); + if (context != null) { + currentContext.set(context); + } else { + currentContext.remove(); } - return () -> clear(); + return () -> { + if (previous != null) { + currentContext.set(previous); + } else { + currentContext.remove(); + } + }; + } + + static ConnectionLogContext getConnectionContext() { + return currentContext.get(); } /** * Returns the connection ID carried by any registered active connection on the current thread. */ static String getConnectionId() { - return currentConnectionId.get(); + ConnectionLogContext context = currentContext.get(); + return context != null ? context.connectionId() : null; } static void clear() { - currentConnectionId.remove(); + currentContext.remove(); } /** @@ -179,18 +207,18 @@ public void execute(Runnable command) { @Override protected RunnableFuture newTaskFor(Runnable runnable, T value) { - return new MdcFutureTask<>(runnable, value, getConnectionId()); + return new MdcFutureTask<>(runnable, value, getConnectionContext()); } @Override protected RunnableFuture newTaskFor(Callable callable) { - return new MdcFutureTask<>(callable, getConnectionId()); + return new MdcFutureTask<>(callable, getConnectionContext()); } private static Runnable wrap(Runnable runnable) { - String connectionId = getConnectionId(); + ConnectionLogContext context = getConnectionContext(); return () -> { - try (MdcCloseable mdc = registerInstance(connectionId)) { + try (MdcCloseable mdc = withContext(context)) { runnable.run(); } }; @@ -198,21 +226,21 @@ private static Runnable wrap(Runnable runnable) { } private static class MdcFutureTask extends FutureTask { - private final String connectionId; + private final ConnectionLogContext context; - public MdcFutureTask(Runnable runnable, V result, String connectionId) { + public MdcFutureTask(Runnable runnable, V result, ConnectionLogContext context) { super(runnable, result); - this.connectionId = connectionId; + this.context = context; } - public MdcFutureTask(Callable callable, String connectionId) { + public MdcFutureTask(Callable callable, ConnectionLogContext context) { super(callable); - this.connectionId = connectionId; + this.context = context; } @Override public void run() { - try (MdcCloseable mdc = registerInstance(connectionId)) { + try (MdcCloseable mdc = withContext(context)) { super.run(); } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java new file mode 100644 index 000000000000..8a19e6604e5e --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java @@ -0,0 +1,431 @@ +/* + * 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 + * + * https://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.bigquery.jdbc; + +import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +// Uses java.net.ServerSocket (java.base) to avoid requiring jdk.httpserver in custom jlink or OSGi +// runtimes. +final class BigQueryJdbcOAuthCallbackServer implements AutoCloseable { + + static final int MAX_HTTP_REQUEST_LINE_BYTES = 8192; + static final int MAX_HTTP_HEADER_BYTES = 65536; + + private static final int USER_AUTH_DRAIN_TIMEOUT_MS = 50; + private static final int USER_AUTH_BACKLOG = 8; + private static final int MAX_OAUTH_ERROR_LENGTH = 64; + + private static final String USER_AUTH_SUCCESS_HTML_BODY = + "\n" + + "Thank you for using JDBC Driver for Google BigQuery!\n" + + "You may now close the window."; + private static final String USER_AUTH_BAD_REQUEST_HTML_BODY = + "\n" + + "Authentication could not be completed. Please close this window and retry.\n" + + ""; + private static final String USER_AUTH_NOT_FOUND_HTML_BODY = + "Not Found"; + + private static final byte[] USER_AUTH_SUCCESS_HTTP_RESPONSE_BYTES = + buildHttpResponseBytes(200, "OK", USER_AUTH_SUCCESS_HTML_BODY); + private static final byte[] USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES = + buildHttpResponseBytes(400, "Bad Request", USER_AUTH_BAD_REQUEST_HTML_BODY); + private static final byte[] USER_AUTH_NOT_FOUND_HTTP_RESPONSE_BYTES = + buildHttpResponseBytes(404, "Not Found", USER_AUTH_NOT_FOUND_HTML_BODY); + + private static final BigQueryJdbcCustomLogger LOG = + new BigQueryJdbcCustomLogger(BigQueryJdbcOAuthCallbackServer.class.getName()); + + @FunctionalInterface + interface ServerSocketSupplier { + ServerSocket open() throws IOException; + } + + @FunctionalInterface + interface LoopbackSocketBinder { + ServerSocket bind(InetAddress bindAddress, int backlog) throws IOException; + } + + static final class HttpCallbackException extends Exception { + private HttpCallbackException(String message) { + super(message); + } + } + + private final ServerSocket serverSocket; + + BigQueryJdbcOAuthCallbackServer(ServerSocket serverSocket) { + this.serverSocket = serverSocket; + } + + URI getCallbackUri() { + return buildLoopbackCallbackUri(serverSocket.getInetAddress(), serverSocket.getLocalPort()); + } + + String waitForAuthorizationCode(String expectedState, int authTimeoutMs, int socketReadTimeoutMs) + throws IOException { + LOG.finer("++enter++"); + try { + long overallDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(authTimeoutMs); + String lastRejectedReason = null; + while (true) { + int acceptTimeoutMs = remainingMillis(overallDeadlineNanos); + if (acceptTimeoutMs <= 0) { + throw callbackTimeoutException(lastRejectedReason); + } + serverSocket.setSoTimeout(acceptTimeoutMs); + Socket acceptedSocket; + try { + acceptedSocket = serverSocket.accept(); + } catch (SocketTimeoutException acceptTimedOut) { + throw callbackTimeoutException(lastRejectedReason); + } + try (Socket socket = acceptedSocket) { + String code = + handleCallbackConnection( + socket, expectedState, overallDeadlineNanos, socketReadTimeoutMs); + if (code != null) { + return code; + } + } catch (HttpCallbackException rejectedRequest) { + lastRejectedReason = rejectedRequest.getMessage(); + } + } + } finally { + LOG.finer("++exit++"); + } + } + + @Override + public void close() throws IOException { + serverSocket.close(); + } + + static ServerSocket openLoopbackServerSocket() throws IOException { + return openLoopbackServerSocket((address, backlog) -> new ServerSocket(0, backlog, address)); + } + + static ServerSocket openLoopbackServerSocket(LoopbackSocketBinder binder) throws IOException { + InetAddress ipv4Loopback = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); + try { + return binder.bind(ipv4Loopback, USER_AUTH_BACKLOG); + } catch (IOException ipv4Unavailable) { + InetAddress ipv6Loopback = + InetAddress.getByAddress(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}); + try { + return binder.bind(ipv6Loopback, USER_AUTH_BACKLOG); + } catch (IOException ipv6Unavailable) { + ipv4Unavailable.addSuppressed(ipv6Unavailable); + throw ipv4Unavailable; + } + } + } + + static URI buildLoopbackCallbackUri(InetAddress bindAddress, int port) { + if (bindAddress instanceof Inet6Address) { + return URI.create("http://[::1]:" + port); + } + return URI.create("http://127.0.0.1:" + port); + } + + static Map parseOAuthQueryParameters(String rawQuery) + throws HttpCallbackException { + if (rawQuery == null || rawQuery.isEmpty()) { + return Collections.emptyMap(); + } + Map params = new HashMap<>(); + String[] pairs = rawQuery.split("&"); + for (String pair : pairs) { + if (pair.isEmpty()) { + continue; + } + int eqIndex = pair.indexOf('='); + String rawKey = eqIndex >= 0 ? pair.substring(0, eqIndex) : pair; + String rawValue = eqIndex >= 0 ? pair.substring(eqIndex + 1) : ""; + String key = urlDecodeUtf8(rawKey); + String value = urlDecodeUtf8(rawValue); + if (("code".equals(key) || "state".equals(key) || "error".equals(key)) + && params.containsKey(key)) { + throw new HttpCallbackException("Duplicate OAuth callback parameter: " + key); + } + params.put(key, value); + } + return params; + } + + private static String urlDecodeUtf8(String value) throws HttpCallbackException { + try { + return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name()); + } catch (IllegalArgumentException e) { + throw new HttpCallbackException("Malformed query parameter encoding in OAuth callback."); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException("UTF-8 encoding not supported", e); + } + } + + private static boolean isValidOAuthState(String expectedState, String actualState) { + if (actualState == null) { + return false; + } + return MessageDigest.isEqual( + expectedState.getBytes(StandardCharsets.UTF_8), + actualState.getBytes(StandardCharsets.UTF_8)); + } + + private static SocketTimeoutException callbackTimeoutException(String lastRejectedReason) { + if (lastRejectedReason == null) { + return new SocketTimeoutException("Timed out waiting for OAuth authorization callback."); + } + return new SocketTimeoutException( + "Timed out waiting for OAuth authorization callback. Last rejected callback request: " + + lastRejectedReason); + } + + private static String handleCallbackConnection( + Socket socket, String expectedState, long overallDeadlineNanos, int socketReadTimeoutMs) + throws HttpCallbackException { + long readDeadlineNanos = + Math.min( + overallDeadlineNanos, + System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(socketReadTimeoutMs)); + try { + BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream()); + boolean headersDrained = false; + try { + String requestLine = + readHttpRequestLine( + socket, inputStream, readDeadlineNanos, MAX_HTTP_REQUEST_LINE_BYTES); + if (requestLine == null) { + return null; + } + URI requestUri = parseHttpGetRequestTarget(requestLine); + drainHttpHeaders(socket, inputStream, readDeadlineNanos, MAX_HTTP_HEADER_BYTES); + headersDrained = true; + if (!"/".equals(requestUri.getPath())) { + writeHttpResponseQuietly(socket, USER_AUTH_NOT_FOUND_HTTP_RESPONSE_BYTES); + return null; + } + Map queryParams = parseOAuthQueryParameters(requestUri.getRawQuery()); + if (!isValidOAuthState(expectedState, queryParams.get("state"))) { + throw new HttpCallbackException("Missing or invalid state parameter in OAuth callback."); + } + String error = queryParams.get("error"); + if (error != null) { + writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES); + throw new BigQueryJdbcRuntimeException( + "OAuth authorization failed: " + sanitizeOAuthErrorCode(error)); + } + String code = queryParams.get("code"); + if (code == null || code.isEmpty()) { + writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES); + throw new BigQueryJdbcRuntimeException( + "Could not retrieve the authorization code from OAuth callback."); + } + writeHttpResponseQuietly(socket, USER_AUTH_SUCCESS_HTTP_RESPONSE_BYTES); + return code; + } catch (HttpCallbackException callbackError) { + if (!headersDrained) { + long drainDeadlineNanos = + Math.min( + overallDeadlineNanos, + System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(USER_AUTH_DRAIN_TIMEOUT_MS)); + drainHttpHeaders(socket, inputStream, drainDeadlineNanos, MAX_HTTP_HEADER_BYTES); + } + writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES); + throw callbackError; + } + } catch (IOException clientIoError) { + return null; + } + } + + private static int remainingMillis(long deadlineNanos) { + long remainingNanos = deadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + return 0; + } + long millis = TimeUnit.NANOSECONDS.toMillis(remainingNanos); + if (millis == 0L) { + return 1; + } + return (int) millis; + } + + private static int readByteBeforeDeadline( + Socket socket, BufferedInputStream inputStream, long deadlineNanos) throws IOException { + if (inputStream.available() > 0) { + return inputStream.read(); + } + int remainingMs = remainingMillis(deadlineNanos); + if (remainingMs <= 0) { + throw new SocketTimeoutException("Timed out reading OAuth callback request."); + } + socket.setSoTimeout(remainingMs); + return inputStream.read(); + } + + private static String readHttpRequestLine( + Socket socket, BufferedInputStream inputStream, long deadlineNanos, int maxBytes) + throws IOException, HttpCallbackException { + int b = readByteBeforeDeadline(socket, inputStream, deadlineNanos); + if (b == -1) { + return null; + } + ByteArrayOutputStream buffer = new ByteArrayOutputStream(256); + int totalRead = 0; + while (true) { + if (b == '\n') { + break; + } + if (b == -1) { + throw new HttpCallbackException("Incomplete OAuth callback HTTP request line."); + } + totalRead++; + if (totalRead > maxBytes) { + throw new HttpCallbackException( + "OAuth callback HTTP request line exceeded maximum length."); + } + if (b == '\r') { + int next = readByteBeforeDeadline(socket, inputStream, deadlineNanos); + if (next != '\n') { + throw new HttpCallbackException("Invalid bare CR in OAuth callback HTTP request line."); + } + break; + } + buffer.write(b); + b = readByteBeforeDeadline(socket, inputStream, deadlineNanos); + } + return new String(buffer.toByteArray(), StandardCharsets.US_ASCII); + } + + private static void drainHttpHeaders( + Socket socket, BufferedInputStream inputStream, long deadlineNanos, int maxHeaderBytes) { + int totalRead = 0; + int lineChars = 0; + try { + while (totalRead < maxHeaderBytes) { + int b = readByteBeforeDeadline(socket, inputStream, deadlineNanos); + if (b == -1) { + return; + } + totalRead++; + if (b == '\n') { + if (lineChars == 0) { + return; + } + lineChars = 0; + } else if (b != '\r') { + lineChars++; + } + } + } catch (IOException ignored) { + // Best-effort drain so closing the socket after writing the HTTP response avoids TCP RST. + } + } + + private static URI parseHttpGetRequestTarget(String requestLine) throws HttpCallbackException { + String[] parts = requestLine.split(" ", -1); + if (parts.length != 3 + || !"GET".equals(parts[0]) + || !parts[1].startsWith("/") + || (!"HTTP/1.1".equals(parts[2]) && !"HTTP/1.0".equals(parts[2]))) { + throw new HttpCallbackException("Invalid HTTP request line on OAuth callback."); + } + URI requestUri; + try { + requestUri = new URI(parts[1]); + } catch (URISyntaxException e) { + throw new HttpCallbackException("Malformed URI in OAuth callback request."); + } + if (requestUri.getRawAuthority() != null || requestUri.getRawFragment() != null) { + throw new HttpCallbackException("Unexpected URI format in OAuth callback request."); + } + return requestUri; + } + + private static String sanitizeOAuthErrorCode(String error) { + if (error.isEmpty()) { + return "unknown_error"; + } + int limit = Math.min(error.length(), MAX_OAUTH_ERROR_LENGTH); + StringBuilder sb = new StringBuilder(limit); + for (int i = 0; i < limit; i++) { + char c = error.charAt(i); + if (c >= 0x21 && c <= 0x7E && c != '"' && c != '\'') { + sb.append(c); + } else { + sb.append('_'); + } + } + return sb.toString(); + } + + private static byte[] buildHttpResponseBytes( + int statusCode, String reasonPhrase, String htmlBody) { + byte[] bodyBytes = htmlBody.getBytes(StandardCharsets.UTF_8); + String headers = + "HTTP/1.1 " + + statusCode + + " " + + reasonPhrase + + "\r\n" + + "Content-Type: text/html; charset=utf-8\r\n" + + "Content-Length: " + + bodyBytes.length + + "\r\n" + + "Cache-Control: no-store\r\n" + + "X-Content-Type-Options: nosniff\r\n" + + "Content-Security-Policy: default-src 'none'\r\n" + + "Connection: close\r\n" + + "\r\n"; + byte[] headerBytes = headers.getBytes(StandardCharsets.US_ASCII); + byte[] response = new byte[headerBytes.length + bodyBytes.length]; + System.arraycopy(headerBytes, 0, response, 0, headerBytes.length); + System.arraycopy(bodyBytes, 0, response, headerBytes.length, bodyBytes.length); + return response; + } + + private static void writeHttpResponseQuietly(Socket socket, byte[] responseBytes) { + try { + OutputStream outputStream = socket.getOutputStream(); + outputStream.write(responseBytes); + outputStream.flush(); + socket.shutdownOutput(); + } catch (IOException ignored) { + // Peer may have already closed its side of the connection. + } + } +} diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java index 49bff5f6982c..0b328cb31f26 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java @@ -27,6 +27,7 @@ import com.google.auth.oauth2.ExternalAccountCredentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.auth.oauth2.PKCEProvider; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserAuthorizer; import com.google.auth.oauth2.UserCredentials; @@ -37,18 +38,14 @@ import com.google.gson.Strictness; import com.google.gson.stream.JsonReader; import java.awt.Desktop; -import java.io.BufferedReader; +import java.awt.GraphicsEnvironment; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; import java.io.Reader; import java.io.StringReader; -import java.net.ServerSocket; -import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -57,31 +54,21 @@ import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyFactory; +import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; +import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; -import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.regex.Matcher; -import java.util.regex.Pattern; final class BigQueryJdbcOAuthUtility { - private static final String USER_AUTH_SUCCESS_HTTP_RESPONSE = - "HTTP/1.1 200 OK\n" - + "Content-Length: 300\n" - + "Connection: close\n" - + "Content-Type: text/html; charset=utf-8\n" - + "\n" - + "\n" - + "Thank you for using JDBC Driver for Google BigQuery!\n" - + "You may now close the window."; - static final String BIGQUERY_SCOPE = "https://www.googleapis.com/auth/bigquery"; static final String DRIVE_READONLY_SCOPE = "https://www.googleapis.com/auth/drive.readonly"; @@ -90,6 +77,10 @@ final class BigQueryJdbcOAuthUtility { Arrays.asList(BIGQUERY_SCOPE, DRIVE_READONLY_SCOPE); private static final int USER_AUTH_TIMEOUT_MS = 120000; + private static final int USER_AUTH_SOCKET_READ_TIMEOUT_MS = 1000; + private static final int OAUTH_RANDOM_TOKEN_BYTES = 32; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private static final String EXTERNAL_ACCOUNT_TYPE = "external_account"; private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(BigQueryJdbcOAuthUtility.class.getName()); @@ -217,10 +208,8 @@ static Map parseOAuthProperties(DataSource ds, String callerClas BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME, ds.getByoidSubjectTokenType()); } - if (ds.getByoidTokenUri() != null) { - oauthProperties.put( - BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, ds.getByoidTokenUri()); - } + oauthProperties.put( + BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, ds.getByoidTokenUri()); String universeDomain = ds.getUniverseDomain(); if (universeDomain != null) { @@ -281,7 +270,11 @@ static GoogleCredentials getCredentials( case GOOGLE_USER_ACCOUNT: credentials = getGoogleUserAccountCredentials( - authProperties, overrideProperties, httpTransportFactory, callerClassName); + authProperties, + overrideProperties, + Boolean.TRUE.equals(reqGoogleDriveScopeBool), + httpTransportFactory, + callerClassName); break; case PRE_GENERATED_TOKEN: credentials = @@ -387,8 +380,9 @@ private static GoogleCredentials getGoogleServiceAccountCredentials( builder.setTokenServerUri( new URI(overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME))); } - if (overrideProperties.containsKey( - BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) { + if (stream == null + && overrideProperties.containsKey( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) { builder.setUniverseDomain( overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); } @@ -400,21 +394,61 @@ private static GoogleCredentials getGoogleServiceAccountCredentials( return builder.build(); } + @FunctionalInterface + interface BrowserOpener { + void open(URI authorizationUri) throws IOException; + } + + // DefaultPKCEProvider in google-auth-library-oauth2-http 1.58.0 emits a 172-character padded + // code_verifier, outside RFC 7636 Section 4.1 (43..128 unreserved characters, unpadded). + private static final class Rfc7636PkceProvider implements PKCEProvider { + private static final String CHALLENGE_METHOD_S256 = "S256"; + private final String codeVerifier; + private final String codeChallenge; + + private Rfc7636PkceProvider() { + byte[] verifierBytes = new byte[OAUTH_RANDOM_TOKEN_BYTES]; + SECURE_RANDOM.nextBytes(verifierBytes); + this.codeVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(verifierBytes); + this.codeChallenge = computeS256Challenge(this.codeVerifier); + } + + private static String computeS256Challenge(String verifier) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(verifier.getBytes(StandardCharsets.US_ASCII)); + return Base64.getUrlEncoder().withoutPadding().encodeToString(hash); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 MessageDigest not available", e); + } + } + + @Override + public String getCodeVerifier() { + return codeVerifier; + } + + @Override + public String getCodeChallenge() { + return codeChallenge; + } + + @Override + public String getCodeChallengeMethod() { + return CHALLENGE_METHOD_S256; + } + } + static UserAuthorizer getUserAuthorizer( Map authProperties, Map overrideProperties, - int port, + boolean requestDriveScope, + URI callbackUri, HttpTransportFactory httpTransportFactory, String callerClassName) throws URISyntaxException { LOG.finer("++enter++\t" + callerClassName); - List scopes = new ArrayList<>(); - scopes.add("https://www.googleapis.com/auth/bigquery"); - - List responseTypes = new ArrayList<>(); - responseTypes.add("code"); - ClientId clientId = ClientId.of( authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME), @@ -422,8 +456,9 @@ static UserAuthorizer getUserAuthorizer( UserAuthorizer.Builder userAuthorizerBuilder = UserAuthorizer.newBuilder() .setClientId(clientId) - .setScopes(scopes) - .setCallbackUri(URI.create("http://localhost:" + port)); + .setScopes(requestDriveScope ? BIGQUERY_WITH_DRIVE_SCOPES : DEFAULT_BIGQUERY_SCOPES) + .setCallbackUri(callbackUri) + .setPKCEProvider(new Rfc7636PkceProvider()); if (httpTransportFactory != null) { userAuthorizerBuilder.setHttpTransportFactory(httpTransportFactory); @@ -440,13 +475,23 @@ static UserAuthorizer getUserAuthorizer( static UserCredentials getCredentialsFromCode( UserAuthorizer userAuthorizer, String code, + Map overrideProperties, HttpTransportFactory httpTransportFactory, String callerClassName) throws IOException { LOG.finer("++enter++\t" + callerClassName); UserCredentials credentials = userAuthorizer.getCredentialsFromCode(code, URI.create("")); - if (httpTransportFactory != null) { - credentials = credentials.toBuilder().setHttpTransportFactory(httpTransportFactory).build(); + String universeDomain = + overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME); + if (httpTransportFactory != null || universeDomain != null) { + UserCredentials.Builder builder = credentials.toBuilder(); + if (httpTransportFactory != null) { + builder.setHttpTransportFactory(httpTransportFactory); + } + if (universeDomain != null) { + builder.setUniverseDomain(universeDomain); + } + credentials = builder.build(); } return credentials; } @@ -454,53 +499,76 @@ static UserCredentials getCredentialsFromCode( private static GoogleCredentials getGoogleUserAccountCredentials( Map authProperties, Map overrideProperties, + boolean requestDriveScope, HttpTransportFactory httpTransportFactory, String callerClassName) { + if (!isDesktopBrowseSupported()) { + throw new BigQueryJdbcRuntimeException("User auth only supported in desktop environments"); + } + return getGoogleUserAccountCredentials( + authProperties, + overrideProperties, + requestDriveScope, + httpTransportFactory, + callerClassName, + BigQueryJdbcOAuthCallbackServer::openLoopbackServerSocket, + uri -> Desktop.getDesktop().browse(uri), + USER_AUTH_TIMEOUT_MS, + USER_AUTH_SOCKET_READ_TIMEOUT_MS); + } + + static GoogleCredentials getGoogleUserAccountCredentials( + Map authProperties, + Map overrideProperties, + boolean requestDriveScope, + HttpTransportFactory httpTransportFactory, + String callerClassName, + BigQueryJdbcOAuthCallbackServer.ServerSocketSupplier serverSocketSupplier, + BrowserOpener browserOpener, + int authTimeoutMs, + int socketReadTimeoutMs) { LOG.finer("++enter++\t" + callerClassName); try { - ServerSocket serverSocket = new ServerSocket(0); - serverSocket.setSoTimeout(USER_AUTH_TIMEOUT_MS); - int port = serverSocket.getLocalPort(); - UserAuthorizer userAuthorizer = - getUserAuthorizer( - authProperties, overrideProperties, port, httpTransportFactory, callerClassName); - - URL authURL = userAuthorizer.getAuthorizationUrl("user", "", URI.create("")); + UserAuthorizer userAuthorizer; String code; - - if (Desktop.isDesktopSupported()) { - Desktop.getDesktop().browse(authURL.toURI()); - - Socket socket = serverSocket.accept(); - - OutputStream outputStream = socket.getOutputStream(); - PrintWriter printWriter = new PrintWriter(outputStream); - - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(socket.getInputStream())); - String response = bufferedReader.readLine(); - - Pattern p = Pattern.compile("(?<=code=).*?(?=&|$)"); - Matcher m = p.matcher(response); - - if (!m.find()) { - throw new BigQueryJdbcRuntimeException("Could not retrieve the code for user auth"); - } - code = m.group(); - - printWriter.println(USER_AUTH_SUCCESS_HTTP_RESPONSE); - printWriter.flush(); - socket.close(); - serverSocket.close(); - } else { - throw new BigQueryJdbcRuntimeException("User auth only supported in desktop environments"); + try (BigQueryJdbcOAuthCallbackServer callbackServer = + new BigQueryJdbcOAuthCallbackServer(serverSocketSupplier.open())) { + userAuthorizer = + getUserAuthorizer( + authProperties, + overrideProperties, + requestDriveScope, + callbackServer.getCallbackUri(), + httpTransportFactory, + callerClassName); + String expectedState = generateOAuthState(); + URL authUrl = userAuthorizer.getAuthorizationUrl("user", expectedState, URI.create("")); + browserOpener.open(authUrl.toURI()); + code = + callbackServer.waitForAuthorizationCode( + expectedState, authTimeoutMs, socketReadTimeoutMs); } - - return getCredentialsFromCode(userAuthorizer, code, httpTransportFactory, callerClassName); + return getCredentialsFromCode( + userAuthorizer, code, overrideProperties, httpTransportFactory, callerClassName); } catch (IOException | URISyntaxException ex) { throw new BigQueryJdbcRuntimeException( "Failed to establish connection using User Account authentication", ex); + } finally { + LOG.finer("++exit++\t" + callerClassName); + } + } + + static boolean isDesktopBrowseSupported() { + if (GraphicsEnvironment.isHeadless() || !Desktop.isDesktopSupported()) { + return false; } + return Desktop.getDesktop().isSupported(Desktop.Action.BROWSE); + } + + private static String generateOAuthState() { + byte[] stateBytes = new byte[OAUTH_RANDOM_TOKEN_BYTES]; + SECURE_RANDOM.nextBytes(stateBytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(stateBytes); } private static GoogleCredentials getPreGeneratedAccessTokenCredentials( @@ -630,22 +698,29 @@ private static GoogleCredentials getExternalAccountAuthCredentials( credentialsPath = authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME); } else { + // Synthesize an external_account JSON payload. token_url is always present here: + // DataSource.getByoidTokenUri() derives https://sts./v1/token from an + // explicit universeDomain when BYOID_TokenUri is omitted. jsonObject = new JsonObject(); + jsonObject.addProperty("type", EXTERNAL_ACCOUNT_TYPE); for (String property : BigQueryJdbcUrlUtility.BYOID_PROPERTIES) { + if (authProperties.get(property) == null) { + continue; + } if (Objects.equals( property, BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME)) { jsonObject.add( BYOID_NAME_MAP.get(property), JsonParser.parseString(authProperties.get(property)).getAsJsonObject()); - } else if (authProperties.containsKey(property)) { + } else { jsonObject.addProperty(BYOID_NAME_MAP.get(property), authProperties.get(property)); } } - if (authProperties.containsKey( - BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) { - jsonObject.addProperty( - "universe_domain", - authProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); + String byoidUniverseDomain = + BigQueryJdbcUrlUtility.normalizeUniverseDomain( + authProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); + if (byoidUniverseDomain != null) { + jsonObject.addProperty("universe_domain", byoidUniverseDomain); } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java index a885d8b9008b..fffa3d896091 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java @@ -204,6 +204,24 @@ public static Logging createLoggingClient( String effectiveProjectId, Credentials fallbackCredentials, HeaderProvider headerProvider) { + return createLoggingClient( + enableGcpLogExporter, + customOpenTelemetry, + effectiveCredentials, + effectiveProjectId, + fallbackCredentials, + headerProvider, + null); + } + + static Logging createLoggingClient( + boolean enableGcpLogExporter, + OpenTelemetry customOpenTelemetry, + String effectiveCredentials, + String effectiveProjectId, + Credentials fallbackCredentials, + HeaderProvider headerProvider, + String universeDomain) { if (!enableGcpLogExporter || customOpenTelemetry != null) { return null; @@ -225,6 +243,9 @@ public static Logging createLoggingClient( if (headerProvider != null) { loggingOptionsBuilder.setHeaderProvider(headerProvider); } + if (universeDomain != null) { + loggingOptionsBuilder.setUniverseDomain(universeDomain); + } return loggingOptionsBuilder.build().getService(); } catch (Exception e) { throw new BigQueryJdbcRuntimeException("Failed to initialize Logging client", e); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java index 2e5753fa2c46..925e42d155bf 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java @@ -48,6 +48,7 @@ public final class BigQueryJdbcResultSetLogger { private final BigQueryJdbcCustomLogger delegate; private final String targetClassName; + private final ConnectionLogContext connectionContext; private final String connectionId; private volatile BigQueryJdbcResultSetLogger arrowStructLogger; @@ -56,25 +57,36 @@ public final class BigQueryJdbcResultSetLogger { private volatile BigQueryJdbcResultSetLogger jsonArrayLogger; private BigQueryJdbcResultSetLogger( - BigQueryJdbcCustomLogger delegate, String targetClassName, String connectionId) { + BigQueryJdbcCustomLogger delegate, + String targetClassName, + ConnectionLogContext connectionContext) { this.delegate = delegate; this.targetClassName = targetClassName; - this.connectionId = connectionId; + this.connectionContext = connectionContext; + this.connectionId = connectionContext != null ? connectionContext.connectionId() : null; } public static BigQueryJdbcResultSetLogger getLogger(Class clazz) { - return getLogger(clazz, null); + return getLogger(clazz, (ConnectionLogContext) null); } public static BigQueryJdbcResultSetLogger getLogger(Class clazz, String connectionId) { + if (connectionId == null || connectionId.isEmpty()) { + return getLogger(clazz, (ConnectionLogContext) null); + } + return getLogger(clazz, BigQueryJdbcRootLogger.resolveContext(connectionId)); + } + + static BigQueryJdbcResultSetLogger getLogger( + Class clazz, ConnectionLogContext connectionContext) { String className = clazz.getName(); BigQueryJdbcCustomLogger delegate = DELEGATES.computeIfAbsent(className, BigQueryJdbcCustomLogger::new); - if (connectionId == null) { + if (connectionContext == null) { return GLOBAL_FACADES.computeIfAbsent( className, k -> new BigQueryJdbcResultSetLogger(delegate, k, null)); } - return new BigQueryJdbcResultSetLogger(delegate, className, connectionId); + return new BigQueryJdbcResultSetLogger(delegate, className, connectionContext); } public String getConnectionId() { @@ -87,60 +99,75 @@ BigQueryJdbcCustomLogger delegate() { } public boolean isLoggable(Level level) { - return delegate.isLoggable(level); + if (!delegate.isSuperLoggable(level)) { + return false; + } + ConnectionLogContext ctx = + connectionContext != null ? connectionContext : BigQueryJdbcMdc.getConnectionContext(); + return delegate.isLoggableAfterSuper(level, ctx); } public BigQueryJdbcResultSetLogger getArrowStructLogger() { if (arrowStructLogger == null) { - arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionId); + arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionContext); } return arrowStructLogger; } public BigQueryJdbcResultSetLogger getJsonStructLogger() { if (jsonStructLogger == null) { - jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionId); + jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionContext); } return jsonStructLogger; } public BigQueryJdbcResultSetLogger getArrowArrayLogger() { if (arrowArrayLogger == null) { - arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionId); + arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionContext); } return arrowArrayLogger; } public BigQueryJdbcResultSetLogger getJsonArrayLogger() { if (jsonArrayLogger == null) { - jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionId); + jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionContext); } return jsonArrayLogger; } /** - * Stamps the connection ID into {@code params[0]} and forwards to the shared logger. Does not - * touch the record's source class/method: hot-path callers set them explicitly, and cold-path - * callers ({@code severe}, {@code warning}) rely on {@link + * Stamps the {@link ConnectionLogContext} into {@code params[0]} and forwards to the shared + * logger. Does not touch the record's source class/method: hot-path callers set them explicitly, + * and cold-path callers ({@code severe}, {@code warning}) rely on {@link * BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily. */ public void log(LogRecord record) { - if (connectionId != null) { + if (record == null || !isLoggable(record.getLevel())) { + return; + } + if (connectionContext != null) { Object[] existingParams = record.getParameters(); if (existingParams == null || existingParams.length == 0) { - record.setParameters(new Object[] {connectionId}); - } else { + record.setParameters(new Object[] {connectionContext}); + } else if (!(existingParams[0] instanceof ConnectionLogContext)) { Object[] newParams = new Object[existingParams.length + 1]; - newParams[0] = connectionId; + newParams[0] = connectionContext; System.arraycopy(existingParams, 0, newParams, 1, existingParams.length); record.setParameters(newParams); } + if (BigQueryJdbcMdc.getConnectionContext() != connectionContext) { + try (BigQueryJdbcMdc.MdcCloseable ignored = + BigQueryJdbcMdc.withContext(connectionContext)) { + delegate.log(record); + } + return; + } } delegate.log(record); } private void logTrace(Level level, String methodName, String msg) { - if (!delegate.isLoggable(level)) { + if (!isLoggable(level)) { return; } LogRecord record = new LogRecord(level, msg); @@ -150,15 +177,18 @@ private void logTrace(Level level, String methodName, String msg) { } private void logTrace(Level level, String methodName, Supplier msgSupplier) { - if (!delegate.isLoggable(level)) { + if (!isLoggable(level)) { return; } - logTrace(level, methodName, msgSupplier.get()); + LogRecord record = new LogRecord(level, msgSupplier.get()); + record.setSourceClassName(targetClassName); + record.setSourceMethodName(methodName); + log(record); } /** Cold path: builds a record whose caller is inferred lazily by the formatter. */ private void logWithCaller(Level level, Throwable thrown, String msg) { - if (!delegate.isLoggable(level)) { + if (!isLoggable(level)) { return; } LogRecord record = new BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord(level, msg); @@ -226,7 +256,7 @@ public void fine(Supplier msgSupplier) { } public void warning(String format, Object... args) { - if (!delegate.isLoggable(Level.WARNING)) { + if (!isLoggable(Level.WARNING)) { return; } String message = (args == null || args.length == 0) ? format : String.format(format, args); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java index b6e1b13afc7e..4b2a94b123a3 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java @@ -21,30 +21,55 @@ import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.context.Context; import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; import java.lang.management.ManagementFactory; +import java.lang.ref.PhantomReference; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; +import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; /** This class is used to log messages from the BigQuery JDBC Driver. */ class BigQueryJdbcRootLogger { + private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS"); + private static volatile boolean externalHandlerAttached = false; + /** * Note: Each connection will have its own file handler with the level and logPath specified in * the connection properties. But the logs will be driver logs and not connection specific. */ - private static final Logger logger = Logger.getLogger("com.google.cloud.bigquery"); + private static final Logger logger = createRootLogger(); private static final Logger storageLogger = Logger.getLogger("com.google.cloud.bigquery.storage"); - private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS"); - private static Handler fileHandler = null; + private static final long CLEANER_IDLE_KEEPALIVE_MS = 60_000L; + private static final ReentrantLock HANDLER_LOCK = new ReentrantLock(); + private static final ConcurrentHashMap activeConnections = + new ConcurrentHashMap<>(); + private static final Map handlersByPath = new HashMap<>(); + private static final ReferenceQueue CLEANUP_QUEUE = new ReferenceQueue<>(); + private static Thread cleanerThread = null; + private static int trackedConnectionCount = 0; + private static int activePreConnectScopes = 0; + private static Level externalRootLevel = null; + private static Level lastManagedRootLevel = logger.getLevel(); static final String PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; @@ -75,12 +100,98 @@ static String getThreadName(long threadId) { static { logger.setUseParentHandlers(false); storageLogger.setUseParentHandlers(true); - if (isTest) { - ConsoleHandler consoleHandler = new ConsoleHandler(); + if (isTest && !hasDriverConsoleHandler(logger)) { + ConsoleHandler consoleHandler = new TestConsoleHandler(); consoleHandler.setLevel(Level.SEVERE); consoleHandler.setFormatter(getFormatter()); logger.addHandler(consoleHandler); } + externalHandlerAttached = scanForExternalHandler(logger); + } + + private static Logger createRootLogger() { + LogManager manager = LogManager.getLogManager(); + Logger existing = manager.getLogger("com.google.cloud.bigquery"); + if (existing != null) { + return existing; + } + RootDriverLogger customRoot = new RootDriverLogger("com.google.cloud.bigquery"); + if (manager.addLogger(customRoot)) { + return customRoot; + } + return Logger.getLogger("com.google.cloud.bigquery"); + } + + private static final class RootDriverLogger extends Logger { + RootDriverLogger(String name) { + super(name, null); + super.setUseParentHandlers(false); + } + + @Override + public synchronized void addHandler(Handler handler) throws SecurityException { + super.addHandler(handler); + externalHandlerAttached = scanForExternalHandler(this); + } + + @Override + public synchronized void removeHandler(Handler handler) throws SecurityException { + super.removeHandler(handler); + externalHandlerAttached = scanForExternalHandler(this); + } + + @Override + public synchronized void setUseParentHandlers(boolean useParentHandlers) { + super.setUseParentHandlers(useParentHandlers); + externalHandlerAttached = scanForExternalHandler(this); + } + } + + private static final class TestConsoleHandler extends ConsoleHandler {} + + private static boolean hasDriverConsoleHandler(Logger target) { + String expectedName = TestConsoleHandler.class.getName(); + for (Handler h : target.getHandlers()) { + if (h instanceof TestConsoleHandler + || (h != null && expectedName.equals(h.getClass().getName()))) { + return true; + } + } + return false; + } + + private static boolean isDriverOwnedHandler(Handler handler) { + if (handler == null) { + return false; + } + if (handler instanceof PerConnectionFileHandler + || handler instanceof OpenTelemetryJulHandler + || handler instanceof TestConsoleHandler) { + return true; + } + String className = handler.getClass().getName(); + return className.equals(PerConnectionFileHandler.class.getName()) + || className.equals(OpenTelemetryJulHandler.class.getName()) + || className.equals(TestConsoleHandler.class.getName()); + } + + static boolean scanForExternalHandler(Logger target) { + if (target.getUseParentHandlers()) { + return true; + } + for (Handler h : target.getHandlers()) { + if (!isDriverOwnedHandler(h)) { + return true; + } + } + return false; + } + + static boolean hasExternalHandler() { + if (logger instanceof RootDriverLogger) { + return externalHandlerAttached; + } + return scanForExternalHandler(logger); } public static Formatter getFormatter() { @@ -102,12 +213,10 @@ private void appendTraceBlock(StringBuilder sb) { @Override public String format(LogRecord record) { String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis())); - String connectionId = BigQueryJdbcMdc.getConnectionId(); + ConnectionLogContext paramContext = ConnectionLogContext.extractFromParameters(record); + String connectionId = paramContext != null ? paramContext.connectionId() : null; if (connectionId == null || connectionId.isEmpty()) { - Object[] params = record.getParameters(); - if (params != null && params.length > 0 && params[0] instanceof String) { - connectionId = (String) params[0]; - } + connectionId = BigQueryJdbcMdc.getConnectionId(); } String connStr = (connectionId != null && !connectionId.isEmpty()) ? connectionId : "NO_CONN"; @@ -148,8 +257,8 @@ public String format(LogRecord record) { .append(System.lineSeparator()); if (record.getThrown() != null) { - java.io.StringWriter sw = new java.io.StringWriter(); - record.getThrown().printStackTrace(new java.io.PrintWriter(sw)); + StringWriter sw = new StringWriter(); + record.getThrown().printStackTrace(new PrintWriter(sw)); sb.append(sw.toString()).append(System.lineSeparator()); } @@ -162,48 +271,446 @@ public static Logger getRootLogger() { return logger; } + static ConnectionLogContext getConnectionContext(String connectionId) { + if (connectionId == null) { + return null; + } + ConnectionLogConfig config = activeConnections.get(connectionId); + return config != null ? config.context : null; + } + + static ConnectionLogContext resolveContext(String connectionId) { + if (connectionId == null || connectionId.isEmpty()) { + return null; + } + ConnectionLogConfig config = activeConnections.get(connectionId); + return config != null ? config.context : ConnectionLogContext.unregistered(connectionId); + } + + static boolean isConnectionActive(String connectionId) { + return connectionId != null && activeConnections.containsKey(connectionId); + } + + static int activeConnectionCount() { + return activeConnections.size(); + } + public static void setLevel(Level level, String logPath) throws IOException { - if (level != Level.OFF) { - if (logPath != null) { - setPath(logPath, level); + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); + updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); + } + } + + static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logPath) { + Level effectiveLevel = level != null ? level : Level.OFF; + ManagedFileHandler tempHandler = null; + boolean countedScope = false; + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); + if (effectiveLevel != Level.OFF) { + activePreConnectScopes++; + countedScope = true; + if (logPath != null) { + try { + tempHandler = acquireHandlerLocked(logPath); + } catch (Exception ex) { + logger.log(Level.WARNING, "Log File warning", ex); + } + } + } + updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); + } + Path preConnectDir = tempHandler != null ? tempHandler.handler.getBaseLogPath() : null; + BigQueryJdbcMdc.MdcCloseable mdcScope = + BigQueryJdbcMdc.withContext( + ConnectionLogContext.preConnect(effectiveLevel.intValue(), preConnectDir)); + final ManagedFileHandler acquired = tempHandler; + final boolean decrementScope = countedScope; + return () -> { + try { + mdcScope.close(); + } finally { + if (decrementScope || acquired != null) { + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); + if (decrementScope && activePreConnectScopes > 0) { + activePreConnectScopes--; + } + releaseHandlerLocked(acquired); + updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); + } + } } - } else { - for (Handler h : logger.getHandlers()) { - h.close(); - logger.removeHandler(h); + }; + } + + static void registerConnection(String connectionId, String rawLogLevel, String logPath) { + if (connectionId == null || connectionId.isEmpty()) { + return; + } + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); + drainCleanupQueueLocked(); + Level connLevel = + rawLogLevel != null + ? BigQueryJdbcUrlUtility.parseLogLevel(rawLogLevel) + : (externalRootLevel != null ? externalRootLevel : Level.OFF); + if (connLevel == null) { + connLevel = Level.OFF; } - fileHandler = null; + ManagedFileHandler managed = null; + if (connLevel != Level.OFF && logPath != null) { + try { + managed = acquireHandlerLocked(logPath); + managed.handler.registerConnection(connectionId, connLevel); + } catch (Exception ex) { + logger.log(Level.WARNING, "Log File warning", ex); + } + } + ConnectionLogConfig previous = + activeConnections.put( + connectionId, + new ConnectionLogConfig( + new ConnectionLogContext(connectionId, connLevel.intValue()), + connLevel, + managed)); + if (previous != null) { + closeConfigLocked(connectionId, previous); + } + updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); } - logger.setLevel(level); } - static void setPath(String logPath, Level level) { + static void trackConnectionLifecycle(BigQueryConnection connection, String connectionId) { + if (connection == null || connectionId == null) { + return; + } + HANDLER_LOCK.lock(); try { - if (logPath == null) { - logPath = ""; + boolean reaped = drainCleanupQueueLocked(); + ConnectionLogConfig config = activeConnections.get(connectionId); + if (config != null) { + detachCleanableLocked(config); + config.cleanable = new ConnectionCleanable(connection, connectionId, CLEANUP_QUEUE); + trackedConnectionCount++; + ensureCleanerRunningLocked(); } - if (!logPath.isEmpty() && !logPath.endsWith("/")) { - logPath = logPath + "/"; + if (reaped) { + updateEffectiveRootLevelLocked(); } + } finally { + HANDLER_LOCK.unlock(); + } + } - if (fileHandler != null) { - fileHandler.close(); - logger.removeHandler(fileHandler); + private static void ensureCleanerRunningLocked() { + if (cleanerThread != null) { + return; + } + try { + Thread cleaner = + new Thread( + BigQueryJdbcRootLogger::runConnectionCleanerLoop, + "BigQuery-JDBC-Connection-Log-Cleaner"); + cleaner.setDaemon(true); + cleaner.setContextClassLoader(BigQueryJdbcRootLogger.class.getClassLoader()); + cleaner.start(); + cleanerThread = cleaner; + } catch (OutOfMemoryError | SecurityException ignored) { + // Best-effort daemon: drainCleanupQueueLocked() still reclaims queued refs on future calls. + } + } + + private static boolean drainCleanupQueueLocked() { + boolean reapedAny = false; + Reference ref; + while ((ref = CLEANUP_QUEUE.poll()) != null) { + if (ref instanceof ConnectionCleanable && reapSingleLocked((ConnectionCleanable) ref)) { + reapedAny = true; } + } + return reapedAny; + } - fileHandler = new PerConnectionFileHandler(logPath, level); - fileHandler.setLevel(level); - logger.addHandler(fileHandler); - logger.setUseParentHandlers(false); + private static boolean reapSingleLocked(ConnectionCleanable ref) { + ref.clear(); + ConnectionLogConfig current = activeConnections.get(ref.connectionId); + if (current == null || current.cleanable != ref) { + return false; + } + captureExternalRootLevelLocked(); + activeConnections.remove(ref.connectionId); + closeConfigLocked(ref.connectionId, current); + return true; + } - } catch (Exception ex) { - logger.warning("Log File warning : " + ex); + private static void runConnectionCleanerLoop() { + BigQueryJdbcMdc.clear(); + while (true) { + try { + boolean waitIndefinitely; + HANDLER_LOCK.lock(); + try { + if (drainCleanupQueueLocked()) { + updateEffectiveRootLevelLocked(); + } + waitIndefinitely = trackedConnectionCount > 0; + Thread.interrupted(); + } finally { + HANDLER_LOCK.unlock(); + } + + Reference ref = + waitIndefinitely + ? CLEANUP_QUEUE.remove() + : CLEANUP_QUEUE.remove(CLEANER_IDLE_KEEPALIVE_MS); + + HANDLER_LOCK.lock(); + try { + boolean reaped = + (ref instanceof ConnectionCleanable) && reapSingleLocked((ConnectionCleanable) ref); + try { + if (drainCleanupQueueLocked()) { + reaped = true; + } + } finally { + if (reaped) { + updateEffectiveRootLevelLocked(); + } + } + if (ref == null && trackedConnectionCount == 0 && CLEANUP_QUEUE.poll() == null) { + if (cleanerThread == Thread.currentThread()) { + cleanerThread = null; + } + return; + } + } finally { + HANDLER_LOCK.unlock(); + } + } catch (InterruptedException ignored) { + // Woken when trackedConnectionCount reaches 0 to switch to the idle keep-alive window. + } catch (Throwable ignored) { + // Survive OOM or unexpected errors while cleaner is active. + } } } public static void closeConnectionHandler(String connectionId) { - if (fileHandler instanceof PerConnectionFileHandler) { - ((PerConnectionFileHandler) fileHandler).closeHandler(connectionId); + if (connectionId == null) { + return; + } + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); + drainCleanupQueueLocked(); + ConnectionLogConfig removed = activeConnections.remove(connectionId); + if (removed != null) { + closeConfigLocked(connectionId, removed); + } + updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); + } + } + + static void resetForTest() { + HANDLER_LOCK.lock(); + try { + for (ConnectionLogConfig cfg : activeConnections.values()) { + detachCleanableLocked(cfg); + cfg.context.setLevelValue(ConnectionLogContext.OFF_VALUE); + } + trackedConnectionCount = 0; + activeConnections.clear(); + for (ManagedFileHandler managed : handlersByPath.values()) { + try { + managed.handler.close(); + } catch (Exception ignored) { + } finally { + logger.removeHandler(managed.handler); + } + } + handlersByPath.clear(); + activePreConnectScopes = 0; + externalRootLevel = null; + lastManagedRootLevel = Level.OFF; + logger.setUseParentHandlers(false); + logger.setLevel(Level.OFF); + externalHandlerAttached = scanForExternalHandler(logger); + } finally { + HANDLER_LOCK.unlock(); + } + } + + private static void detachCleanableLocked(ConnectionLogConfig config) { + if (config.cleanable != null) { + config.cleanable.clear(); + config.cleanable = null; + if (trackedConnectionCount > 0) { + trackedConnectionCount--; + } + if (trackedConnectionCount == 0 + && cleanerThread != null + && cleanerThread != Thread.currentThread()) { + cleanerThread.interrupt(); + } + } + } + + private static void closeConfigLocked(String connectionId, ConnectionLogConfig config) { + detachCleanableLocked(config); + config.context.setLevelValue(ConnectionLogContext.OFF_VALUE); + if (config.managedHandler != null) { + try { + config.managedHandler.handler.closeHandler(connectionId); + } finally { + releaseHandlerLocked(config.managedHandler); + } + } + } + + private static void captureExternalRootLevelLocked() { + if (!hasExternalHandler()) { + externalRootLevel = null; + return; + } + Level current = logger.getLevel(); + if (current != lastManagedRootLevel) { + externalRootLevel = current; + } + } + + private static Level resolveInheritedLevel(Logger target) { + for (Logger parent = target.getParent(); parent != null; parent = parent.getParent()) { + Level parentLevel = parent.getLevel(); + if (parentLevel != null) { + return parentLevel; + } + } + return Level.INFO; + } + + private static void updateEffectiveRootLevelLocked() { + if (activePreConnectScopes > 0) { + lastManagedRootLevel = Level.ALL; + logger.setLevel(Level.ALL); + return; + } + Level effective = externalRootLevel != null ? externalRootLevel : Level.OFF; + int minVal = effective != null ? effective.intValue() : Level.OFF.intValue(); + for (ConnectionLogConfig cfg : activeConnections.values()) { + int connVal = cfg.level.intValue(); + if (connVal < minVal) { + minVal = connVal; + effective = cfg.level; + } + } + if (externalRootLevel == null && hasExternalHandler()) { + Level inherited = resolveInheritedLevel(logger); + if (minVal >= inherited.intValue()) { + lastManagedRootLevel = null; + logger.setLevel(null); + return; + } + } + if (effective == null) { + effective = Level.OFF; + } + lastManagedRootLevel = effective; + logger.setLevel(effective); + } + + private static String canonicalPathKey(String logPath) { + String normalized = logPath == null ? "" : logPath; + try { + return Paths.get(normalized).toAbsolutePath().normalize().toString(); + } catch (InvalidPathException e) { + return normalized; + } + } + + private static ManagedFileHandler acquireHandlerLocked(String logPath) { + String key = canonicalPathKey(logPath); + ManagedFileHandler managed = handlersByPath.get(key); + if (managed == null) { + String pathArg = logPath == null ? "" : logPath; + if (!pathArg.isEmpty() && !pathArg.endsWith("/")) { + pathArg = pathArg + "/"; + } + PerConnectionFileHandler created = + new PerConnectionFileHandler( + pathArg, Level.ALL, PerConnectionFileHandler.resolveMaxLogFileBytes(), true); + logger.addHandler(created); + managed = new ManagedFileHandler(key, created); + handlersByPath.put(key, managed); + } + managed.refCount++; + return managed; + } + + private static void releaseHandlerLocked(ManagedFileHandler managed) { + if (managed == null) { + return; + } + managed.refCount--; + if (managed.refCount <= 0) { + handlersByPath.remove(managed.pathKey); + try { + managed.handler.close(); + } finally { + logger.removeHandler(managed.handler); + } + } + } + + private static final class ManagedFileHandler { + final String pathKey; + final PerConnectionFileHandler handler; + int refCount; + + ManagedFileHandler(String pathKey, PerConnectionFileHandler handler) { + this.pathKey = pathKey; + this.handler = handler; + this.refCount = 0; + } + } + + private static final class ConnectionLogConfig { + final ConnectionLogContext context; + final Level level; + final ManagedFileHandler managedHandler; + ConnectionCleanable cleanable; + + ConnectionLogConfig( + ConnectionLogContext context, Level level, ManagedFileHandler managedHandler) { + this.context = context; + this.level = level; + this.managedHandler = managedHandler; + } + } + + private static final class ConnectionCleanable extends PhantomReference { + final String connectionId; + + ConnectionCleanable( + BigQueryConnection referent, + String connectionId, + ReferenceQueue queue) { + super(referent, queue); + this.connectionId = connectionId; } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index d22846470081..41a1df22f939 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -67,6 +67,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes static final String DEFAULT_QUERY_DIALECT_VALUE = "SQL"; static final String UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME = "universeDomain"; static final String DEFAULT_UNIVERSE_DOMAIN_VALUE = "googleapis.com"; + static final String GOOGLE_CLOUD_UNIVERSE_DOMAIN_ENV_VAR = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"; + private static final String STS_TOKEN_URI_FORMAT = "https://sts.%s/v1/token"; static final String PROJECT_ID_PROPERTY_NAME = "ProjectId"; static final String DEFAULT_DATASET_PROPERTY_NAME = "DefaultDataset"; static final String OAUTH_TYPE_PROPERTY_NAME = "OAuthType"; @@ -123,6 +125,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes static final String LOG_PATH_PROPERTY_NAME = "LogPath"; static final String LOG_LEVEL_ENV_VAR = "BIGQUERY_JDBC_LOG_LEVEL"; static final String LOG_PATH_ENV_VAR = "BIGQUERY_JDBC_LOG_PATH"; + static final String ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY = + "com.google.cloud.bigquery.jdbc.allowUrlLogPath"; static final String ENABLE_SESSION_PROPERTY_NAME = "EnableSession"; static final String ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME = "EnableTimestampPicos"; static final boolean DEFAULT_ENABLE_TIMESTAMP_PICOS_VALUE = false; @@ -377,8 +381,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes BigQueryConnectionProperty.newBuilder() .setName(UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME) .setDescription( - "The name of the partner-operated cloud which is a new instance of Google" - + " production, known as a Trusted Partner Cloud universe.") + "The universe domain for the target cloud environment. Defaults to" + + " googleapis.com.") .setDefaultValue(DEFAULT_UNIVERSE_DOMAIN_VALUE) .build(), BigQueryConnectionProperty.newBuilder() @@ -834,7 +838,8 @@ private static Map parseUrlInternal(String url) { throw new BigQueryJdbcRuntimeException( String.format("Wrong value or unknown setting: %s", safeRef)); } else { - LOG.warning("Wrong value or unknown setting: %s", safeRef); + LOG.warning( + "Wrong value or unknown setting: %s", BigQueryConnection.sanitizeForLog(safeRef)); continue; } } @@ -845,6 +850,33 @@ private static Map parseUrlInternal(String url) { return Collections.unmodifiableMap(map); } + static boolean isUrlLogPathAllowed() { + try { + String prop = System.getProperty(ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); + if (prop == null) { + return true; + } + String trimmed = prop.trim(); + return trimmed.isEmpty() || "true".equalsIgnoreCase(trimmed) || "1".equals(trimmed); + } catch (SecurityException e) { + return true; + } + } + + static String resolveEffectiveLogPath( + String urlLogPath, String envLogPath, boolean allowDefaultFallback) { + if (!isUrlLogPathAllowed()) { + return envLogPath; + } + if (urlLogPath != null) { + return urlLogPath; + } + if (envLogPath != null) { + return envLogPath; + } + return allowDefaultFallback ? DEFAULT_LOG_PATH : null; + } + /** * Appends the given properties to the given URL. * @@ -853,16 +885,28 @@ private static Map parseUrlInternal(String url) { * @return The string value of the updated URL. */ static String appendPropertiesToURL(String url, String callerClassName, Properties properties) { - LOG.finest("++enter++ " + callerClassName); + LOG.finest(() -> "++enter++ " + callerClassName); + if (properties == null || properties.isEmpty()) { + return url; + } StringBuilder urlBuilder = new StringBuilder(url); for (Entry entry : properties.entrySet()) { - if (entry.getValue() != null && !"".equals(entry.getValue())) { - LOG.finest("Appending %s with value %s to URL", entry.getKey(), entry.getValue()); - String encodedValue = - UrlEscapers.urlFormParameterEscaper() - .escape((String) entry.getValue()) - .replace("+", "%20"); - urlBuilder.append(";").append(entry.getKey()).append("=").append(encodedValue); + Object rawKey = entry.getKey(); + Object rawValue = entry.getValue(); + if (rawKey != null && rawValue != null) { + String key = String.valueOf(rawKey); + String valueStr = String.valueOf(rawValue); + if (!valueStr.isEmpty()) { + LOG.finest( + () -> + String.format( + "Appending %s with value %s to URL", + BigQueryConnection.sanitizeForLog(key), + BigQueryConnection.maskPropertyValue(key, valueStr))); + String encodedValue = + UrlEscapers.urlFormParameterEscaper().escape(valueStr).replace("+", "%20"); + urlBuilder.append(";").append(key).append("=").append(encodedValue); + } } } return urlBuilder.toString(); @@ -973,4 +1017,42 @@ static DatasetId parseDefaultDataset(String defaultDataset) { return DatasetId.of(trimmed); } + + /** + * Reads {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} from the environment. Returns {@code null} when the + * variable is unset, or {@code googleapis.com} when set to an empty/whitespace string so callers + * override GAX EndpointContext's raw {@code System.getenv} read instead of producing an empty + * host. + */ + static String getEnvUniverseDomain() { + return resolveEnvUniverseDomain(readRawEnvUniverseDomain()); + } + + static String readRawEnvUniverseDomain() { + return System.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN_ENV_VAR); + } + + static String resolveEnvUniverseDomain(String rawEnvValue) { + if (rawEnvValue == null) { + return null; + } + String trimmed = rawEnvValue.trim(); + return trimmed.isEmpty() ? DEFAULT_UNIVERSE_DOMAIN_VALUE : trimmed; + } + + /** Trims a universe domain string and normalizes empty/whitespace values to {@code null}. */ + static String normalizeUniverseDomain(String universeDomain) { + if (universeDomain == null) { + return null; + } + String trimmed = universeDomain.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + + /** Derives the Security Token Service (STS) token URI from the resolved universe domain. */ + static String formatByoidTokenUri(String universeDomain) { + String normalized = normalizeUniverseDomain(universeDomain); + String domain = normalized != null ? normalized : DEFAULT_UNIVERSE_DOMAIN_VALUE; + return String.format(STS_TOKEN_URI_FORMAT, domain); + } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryParameterHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryParameterHandler.java index 2fc89afbf173..0262af78c4e2 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryParameterHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryParameterHandler.java @@ -45,6 +45,22 @@ class BigQueryParameterHandler { new BigQueryJdbcCustomLogger(BigQueryParameterHandler.class.getName()); private final int parametersArraySize; private final boolean enableTimestampPicos; + private final boolean recordTelemetry; + + /** + * DRIVER_FEATURE_PARAMETER_BINDING is an adoption signal, recorded once per handler (i.e. per + * prepared statement) rather than once per setX call. Handlers are confined to one statement, + * which JDBC defines as single-threaded, so a plain field is sufficient. + */ + private boolean bindingRecorded; + + private void recordBinding() { + if (this.recordTelemetry && !this.bindingRecorded) { + this.bindingRecorded = true; + TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING); + } + } + final ArrayList parametersList; // TIMESTAMP is rendered in UTC with a trailing 'Z': the instant is preserved, the output does not // depend on the JVM zone, and QueryParameterValue's validator accepts 'Z' but rejects "-05:00". @@ -100,16 +116,30 @@ static Tuple> bindingForJavaTime(Object value) { } BigQueryParameterHandler(int parameterCount, boolean enableTimestampPicos) { - this(parameterCount, new ArrayList<>(parameterCount), enableTimestampPicos); + this(parameterCount, enableTimestampPicos, true); + } + + BigQueryParameterHandler( + int parameterCount, boolean enableTimestampPicos, boolean recordTelemetry) { + this(parameterCount, new ArrayList<>(parameterCount), enableTimestampPicos, recordTelemetry); } BigQueryParameterHandler( int parameterCount, ArrayList parametersList, boolean enableTimestampPicos) { + this(parameterCount, parametersList, enableTimestampPicos, true); + } + + BigQueryParameterHandler( + int parameterCount, + ArrayList parametersList, + boolean enableTimestampPicos, + boolean recordTelemetry) { this.parametersArraySize = parameterCount; this.parametersList = parametersList; this.enableTimestampPicos = enableTimestampPicos; + this.recordTelemetry = recordTelemetry; } // Indicates whether the parameter is input, output or both @@ -271,7 +301,7 @@ void setNullParameter(int parameterIndex, Class declaredJavaType) { parameter.setParamType(BigQueryStatementParameterType.UNSPECIFIED); parameter.setScale(-1); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING); + recordBinding(); LOG.finest("Parameter set { %s }", parameter.toString()); } @@ -289,7 +319,7 @@ void setParameter(int parameterIndex, Object value, Class type) { parameter.setParamType(BigQueryStatementParameterType.UNSPECIFIED); parameter.setScale(-1); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING); + recordBinding(); LOG.finest("Parameter set { %s }", parameter.toString()); } @@ -385,7 +415,7 @@ void setParameter( parametersList.add(parameter); } - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING); + recordBinding(); LOG.finest("Parameter set { %s }", parameter.toString()); } @@ -411,7 +441,7 @@ void setParameter( parameter.setParamType(paramType); parameter.setScale(scale); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING); + recordBinding(); LOG.finest("Parameter set { %s }", parameter.toString()); } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnection.java index 24571e0480b6..05017671c619 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnection.java @@ -16,13 +16,31 @@ package com.google.cloud.bigquery.jdbc; +import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.common.annotations.VisibleForTesting; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.CallableStatement; +import java.sql.ClientInfoStatus; import java.sql.Connection; import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLClientInfoException; import java.sql.SQLException; -import java.util.UUID; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.concurrent.Executor; -import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; @@ -32,472 +50,974 @@ class BigQueryPooledConnection implements PooledConnection { private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(BigQueryPooledConnection.class.getName()); - private String id; // Mainly for internal use - private Connection bqConnection; - private boolean inUse = false; - private Long listenerPoolSize = 10L; - private LinkedBlockingDeque listeners; + enum State { + IDLE, + IN_USE, + RETIRED, + CLOSED + } + + private final BigQueryConnection bqConnection; + private final String connectionId; + private final Connection proxiedConnection; + private final Long listenerPoolSize; + private final int maxListenerCapacity; + private final List listeners; + private final Object physicalLock = new Object(); + private final Object stateLock = new Object(); + private PooledConnectionListener internalPoolListener; + private boolean detachedFromInternalPool = false; + private boolean nonPoolListenerAttached = false; + private PooledConnectionInvocationHandler activeHandle; + private PooledConnectionInvocationHandler resettingHandle; + private volatile State state = State.IDLE; BigQueryPooledConnection(BigQueryConnection bqConnection) { this.bqConnection = bqConnection; - this.id = UUID.randomUUID().toString(); - this.listenerPoolSize = bqConnection.getListenerPoolSize(); - if (getListenerPoolSize() > 0L) { - listeners = new LinkedBlockingDeque<>(getListenerPoolSize().intValue()); - } else { - listeners = new LinkedBlockingDeque<>(); + this.connectionId = bqConnection.getConnectionId(); + this.proxiedConnection = BigQueryJdbcContextProxy.wrap(bqConnection, Connection.class); + Long configuredListenerPoolSize = bqConnection.getListenerPoolSize(); + this.listenerPoolSize = + configuredListenerPoolSize != null + ? configuredListenerPoolSize + : BigQueryJdbcUrlUtility.DEFAULT_LISTENER_POOL_SIZE_VALUE; + this.maxListenerCapacity = clampCapacity(this.listenerPoolSize); + this.listeners = new ArrayList<>(); + } + + static int clampCapacity(long configuredSize) { + if (configuredSize <= 0L) { + return Integer.MAX_VALUE; } + return (int) Math.min(configuredSize, Integer.MAX_VALUE); } Long getListenerPoolSize() { return listenerPoolSize; } - @VisibleForTesting boolean inUse() { - return inUse; + return this.state == State.IN_USE; } - @VisibleForTesting - boolean isListenerPooled(ConnectionEventListener l) { - return listeners.contains(l); + boolean isAvailableForPool() { + return this.state == State.IDLE && !this.bqConnection.isClosed(); } - @Override - public synchronized Connection getConnection() throws SQLException { - LOG.finest("++enter++"); - if (inUse) { - SQLException ex = new SQLException("PooledConnection is already in use."); - LOG.severe(ex.getMessage(), ex); - throw ex; - } - inUse = true; - // Return a wrapper around the underlying physical connection. - return new BigQueryPooledConnectionWrapper(bqConnection, this); + boolean isClosed() { + return this.state == State.CLOSED + || this.state == State.RETIRED + || this.bqConnection.isClosed(); } - @Override - public synchronized void close() throws SQLException { - LOG.finest("++enter++"); - // Notify listeners that the *PooledConnection* is being closed. - ConnectionEvent event = new ConnectionEvent(this); - for (ConnectionEventListener listener : listeners) { - listener.connectionClosed(event); // This is likely not the intended event for this action + @VisibleForTesting + boolean isListenerPooled(ConnectionEventListener listener) { + synchronized (stateLock) { + return this.internalPoolListener == listener || this.listeners.contains(listener); } - // Marks the pooled connection to be not in use. - inUse = false; } - @Override - public synchronized void addConnectionEventListener(ConnectionEventListener listener) { - LOG.finest("++enter++"); - if (listener == null) { + void registerInternalPoolListener(PooledConnectionListener poolManager) { + if (poolManager == null) { return; } - if (this.listeners.contains(listener)) { - return; + synchronized (stateLock) { + if (isHolderTerminalLocked() + || this.bqConnection.isClosed() + || this.detachedFromInternalPool) { + return; + } + this.internalPoolListener = poolManager; } - this.listeners.add(listener); } - @Override - public synchronized void removeConnectionEventListener(ConnectionEventListener listener) { - LOG.finest("++enter++"); - if (listener == null) { - return; + BigQueryConnection claimPhysicalForReuse(PooledConnectionListener poolManager) { + synchronized (stateLock) { + if (this.state != State.IDLE + || this.bqConnection.isClosed() + || this.activeHandle != null + || this.resettingHandle != null + || this.detachedFromInternalPool + || this.nonPoolListenerAttached + || poolManager == null + || this.internalPoolListener != poolManager + || !this.listeners.isEmpty()) { + return null; + } + this.state = State.RETIRED; + this.internalPoolListener = null; + this.listeners.clear(); + return this.bqConnection; } - if (!this.listeners.contains(listener)) { - return; + } + + void closeIfIdleAndSoleListener(ConnectionEventListener expectedListener) { + synchronized (physicalLock) { + synchronized (stateLock) { + if (this.state != State.IDLE + || this.bqConnection.isClosed() + || this.activeHandle != null + || this.resettingHandle != null + || !isSolelyOwnedByPoolListenerLocked(expectedListener)) { + return; + } + this.state = State.CLOSED; + this.internalPoolListener = null; + this.listeners.clear(); + } + try { + this.bqConnection.close(); + } catch (SQLException ex) { + LOG.warning(ex, "Failed to close excess pooled connection"); + } } - this.listeners.remove(listener); } - // Method called by the BigQueryPooledConnectionWrapper when the logical - // Connection is closed. - public synchronized void connectionHandleClosed(BigQueryPooledConnectionWrapper handle) { - LOG.finest("++enter++"); - inUse = false; - ConnectionEvent event = new ConnectionEvent(this); - for (ConnectionEventListener listener : listeners) { - listener.connectionClosed(event); + @VisibleForTesting + PooledConnectionInvocationHandler getActiveHandleForTesting() { + synchronized (stateLock) { + return this.activeHandle; } - LOG.finest("Connection handle returned to the pool."); } - // Method to notify listeners about a connection error. This can be called - // by the application if they are using PooledConnection directly or by the - // BigQueryPooledConnectionWrapper when a connection is aborted. - public synchronized void fireConnectionError(SQLException e) { - LOG.finest("++enter++"); - inUse = false; - ConnectionEvent event = new ConnectionEvent(this, e); - for (ConnectionEventListener listener : listeners) { - listener.connectionErrorOccurred(event); + private boolean isSolelyOwnedByPoolListenerLocked(ConnectionEventListener expectedListener) { + if (this.nonPoolListenerAttached || expectedListener == null) { + return false; } - LOG.finest("Connection handle removed from the pool due to error: %s", e.getMessage()); - // Listners no longer need to listen for this connection since it has been removed from the - // pool. - for (ConnectionEventListener listener : listeners) { - removeConnectionEventListener(listener); + if (!this.detachedFromInternalPool && this.internalPoolListener != null) { + return this.internalPoolListener == expectedListener && this.listeners.isEmpty(); } + return this.internalPoolListener == null + && this.listeners.size() == 1 + && this.listeners.get(0) == expectedListener; } - @Override - public void addStatementEventListener(StatementEventListener arg0) { - UnsupportedOperationException ex = - new UnsupportedOperationException( - "Method 'addStatementEventListener' is not supported by the BQ Driver"); - LOG.severe(ex.getMessage(), ex); - throw ex; + private List snapshotAllListenersLocked() { + List snapshot = + new ArrayList<>(this.listeners.size() + (this.internalPoolListener != null ? 1 : 0)); + if (this.internalPoolListener != null) { + snapshot.add(this.internalPoolListener); + } + snapshot.addAll(this.listeners); + return snapshot; } - @Override - public void removeStatementEventListener(StatementEventListener arg0) { - UnsupportedOperationException ex = - new UnsupportedOperationException( - "Method 'removeStatementEventListener' is not supported by the BQ Driver"); - LOG.severe(ex.getMessage(), ex); - throw ex; + private boolean isHolderTerminalLocked() { + return this.state == State.CLOSED || this.state == State.RETIRED; } - // Inner class: Connection Wrapper around the actual physical Connection - // This class notifies the listeners or calls the listner notification methods - // provided by the pooled connection. - static class BigQueryPooledConnectionWrapper implements Connection { - private static final BigQueryJdbcCustomLogger LOG = - new BigQueryJdbcCustomLogger(BigQueryPooledConnectionWrapper.class.getName()); - private Connection bqConnectionDelegate; - private BigQueryPooledConnection pooledConnection; - private boolean closed = false; - - public BigQueryPooledConnectionWrapper( - Connection bqConnectionDelegate, BigQueryPooledConnection pooledConnection) { - this.bqConnectionDelegate = bqConnectionDelegate; - this.pooledConnection = pooledConnection; + private void checkHolderOpenLocked() throws BigQueryJdbcException { + if (this.state == State.RETIRED) { + throw new BigQueryJdbcException( + "PooledConnection was retired and recycled by PooledConnectionDataSource."); + } + if (this.state == State.CLOSED || this.bqConnection.isClosed()) { + throw new BigQueryJdbcException("PooledConnection is closed."); } + } - @Override - public void close() throws SQLException { - LOG.finest("++enter++"); - if (!closed) { - // Instead of physically closing, we notify the PooledConnection - // that this handle is no longer in use. - pooledConnection.connectionHandleClosed(this); - closed = true; - LOG.finest("Logical connection closed (returned to pool)."); + @Override + public Connection getConnection() throws SQLException { + SQLException resetFailure = null; + SQLException outOfBandClosedError = null; + Connection handleProxy = null; + + synchronized (physicalLock) { + PooledConnectionInvocationHandler previousHandle = null; + boolean needsReset = false; + synchronized (stateLock) { + if (this.state == State.RETIRED) { + throw new BigQueryJdbcException( + "PooledConnection was retired and recycled by PooledConnectionDataSource."); + } + if (isHolderTerminalLocked()) { + throw new BigQueryJdbcException("PooledConnection is closed."); + } + if (this.bqConnection.isClosed()) { + outOfBandClosedError = + new BigQueryJdbcException("Underlying physical connection was closed."); + } else { + // Per javax.sql.PooledConnection#getConnection() (JDBC 4.3 section 11.1), calling + // getConnection() while a logical handle is open invalidates the prior handle and + // resets connection state without notifying ConnectionEventListeners. + previousHandle = this.activeHandle; + if (previousHandle != null) { + previousHandle.markClosed(); + } + // Keep state == State.IN_USE in needsReset so a prior reset aborted by an Error + // still forces a clean reset on a subsequent checkout attempt. + needsReset = (this.state == State.IN_USE) || (previousHandle != null); + this.activeHandle = null; + this.resettingHandle = previousHandle; + this.state = State.IN_USE; + } } - } - @Override - public boolean isClosed() throws SQLException { - return closed || bqConnectionDelegate.isClosed(); + if (outOfBandClosedError == null) { + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(this.connectionId)) { + LOG.finer("++enter++"); + if (previousHandle != null) { + previousHandle.awaitQuiescence(); + } + if (needsReset) { + resetFailure = runResetCapturingException(); + } + synchronized (stateLock) { + this.resettingHandle = null; + if (resetFailure == null) { + checkHolderOpenLocked(); + PooledConnectionInvocationHandler handler = + new PooledConnectionInvocationHandler( + this.bqConnection, this.proxiedConnection, this); + handleProxy = handler.createConnectionProxy(); + this.activeHandle = handler; + } + } + if (resetFailure == null) { + LOG.finer("++exit++"); + return handleProxy; + } + } + } } - @Override - public java.sql.Statement createStatement() throws SQLException { - return bqConnectionDelegate.createStatement(); + if (outOfBandClosedError != null) { + fireConnectionError(outOfBandClosedError); + throw new BigQueryJdbcException("PooledConnection is closed."); } + fireConnectionError(resetFailure); + throw resetFailure; + } - @Override - public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException { - return bqConnectionDelegate.prepareStatement(sql); + @Override + public void close() throws SQLException { + TerminalTransition transition = transitionToClosedAndMarkActiveHandle(); + if (transition == null) { + return; } - - @Override - public java.sql.CallableStatement prepareCall(String sql) throws SQLException { - return bqConnectionDelegate.prepareCall(sql); + for (ConnectionEventListener listener : transition.listeners) { + if (listener instanceof PooledConnectionListener) { + ((PooledConnectionListener) listener).removeConnection(this); + } } - - @Override - public String nativeSQL(String sql) throws SQLException { - return bqConnectionDelegate.nativeSQL(sql); + synchronized (physicalLock) { + if (!this.bqConnection.isClosed()) { + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(this.connectionId)) { + LOG.finer("++enter++"); + if (transition.previousHandle != null) { + transition.previousHandle.awaitQuiescence(); + } + } + } else if (transition.previousHandle != null) { + transition.previousHandle.awaitQuiescence(); + } + // Omit ++exit++ after bqConnection.close() since physical close unmounts the per-connection + // file handler. + this.bqConnection.close(); } + } - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException { - bqConnectionDelegate.setAutoCommit(autoCommit); + @Override + public void addConnectionEventListener(ConnectionEventListener listener) { + if (listener == null) { + return; } - - @Override - public boolean getAutoCommit() throws SQLException { - return bqConnectionDelegate.getAutoCommit(); + PooledConnectionListener detachedInternal = null; + synchronized (stateLock) { + if (isHolderTerminalLocked() + || this.bqConnection.isClosed() + || this.listeners.contains(listener)) { + return; + } + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { + LOG.finer("++enter++"); + try { + if (this.listeners.size() >= maxListenerCapacity) { + throw new BigQueryJdbcRuntimeException( + "Listener pool capacity exceeded: " + listenerPoolSize); + } + this.listeners.add(listener); + if (!(listener instanceof PooledConnectionListener) || this.listeners.size() > 1) { + this.nonPoolListenerAttached = true; + } + if (this.nonPoolListenerAttached + || (this.internalPoolListener != null && listener != this.internalPoolListener)) { + this.detachedFromInternalPool = true; + detachedInternal = this.internalPoolListener; + this.internalPoolListener = null; + } + } finally { + LOG.finer("++exit++"); + } + } } - - @Override - public void commit() throws SQLException { - bqConnectionDelegate.commit(); + if (detachedInternal != null) { + detachedInternal.removeConnection(this); } + } - @Override - public void rollback() throws SQLException { - bqConnectionDelegate.rollback(); + @Override + public void removeConnectionEventListener(ConnectionEventListener listener) { + if (listener == null) { + return; } - - @Override - public DatabaseMetaData getMetaData() throws SQLException { - return bqConnectionDelegate.getMetaData(); + synchronized (stateLock) { + this.listeners.remove(listener); } + } - @Override - public void setReadOnly(boolean readOnly) throws SQLException { - bqConnectionDelegate.setReadOnly(readOnly); - } + void connectionHandleClosed(PooledConnectionInvocationHandler handle) throws SQLException { + SQLException resetFailure = null; + SQLException outOfBandClosedError = null; + List listenersToNotify = null; + + synchronized (physicalLock) { + synchronized (stateLock) { + if (isHolderTerminalLocked() || handle != this.activeHandle) { + return; + } + this.activeHandle = null; + if (this.bqConnection.isClosed()) { + outOfBandClosedError = + new BigQueryJdbcException("Underlying physical connection was closed."); + } else { + this.resettingHandle = handle; + } + } - @Override - public boolean isReadOnly() throws SQLException { - return bqConnectionDelegate.isReadOnly(); + if (outOfBandClosedError == null) { + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(this.connectionId)) { + LOG.finer("++enter++"); + resetFailure = runResetCapturingException(); + synchronized (stateLock) { + this.resettingHandle = null; + if (resetFailure == null) { + if (isHolderTerminalLocked()) { + return; + } + if (this.bqConnection.isClosed()) { + outOfBandClosedError = + new BigQueryJdbcException("Underlying physical connection was closed."); + } else { + this.state = State.IDLE; + listenersToNotify = snapshotAllListenersLocked(); + } + } + } + if (outOfBandClosedError == null && resetFailure == null && listenersToNotify != null) { + LOG.finer( + "Logical connection handle returned to pool [connectionId=%s]", this.connectionId); + LOG.finer("++exit++"); + } + } + } } - @Override - public void setCatalog(String catalog) throws SQLException { - bqConnectionDelegate.setCatalog(catalog); + if (outOfBandClosedError != null) { + fireConnectionError(outOfBandClosedError); + return; } - - @Override - public String getCatalog() throws SQLException { - return bqConnectionDelegate.getCatalog(); + if (resetFailure != null) { + fireConnectionError(resetFailure); + throw resetFailure; } - - @Override - public void setTransactionIsolation(int level) throws SQLException { - bqConnectionDelegate.setTransactionIsolation(level); + if (listenersToNotify != null) { + notifyConnectionClosedListeners(listenersToNotify); } + } - @Override - public int getTransactionIsolation() throws SQLException { - return bqConnectionDelegate.getTransactionIsolation(); + void abortHandle(PooledConnectionInvocationHandler handle, Executor executor) + throws SQLException { + List snapshot; + synchronized (stateLock) { + if (isHolderTerminalLocked() + || (handle != this.activeHandle && handle != this.resettingHandle)) { + return; + } + this.state = State.CLOSED; + this.activeHandle = null; + this.resettingHandle = null; + snapshot = snapshotAllListenersLocked(); + this.internalPoolListener = null; + this.listeners.clear(); + } + + SQLException abortError = + new BigQueryJdbcException("Connection is being terminated and aborted."); + try { + this.proxiedConnection.abort(executor); + } catch (SQLException ex) { + abortError.addSuppressed(ex); + scheduleFallbackClose(executor, abortError); + throw ex; + } catch (RuntimeException ex) { + abortError.addSuppressed(ex); + scheduleFallbackClose(executor, abortError); + throw ex; + } finally { + notifyConnectionErrorListeners(snapshot, abortError); } + } - @Override - public java.sql.SQLWarning getWarnings() throws SQLException { - return bqConnectionDelegate.getWarnings(); + private void scheduleFallbackClose(Executor executor, SQLException abortError) { + try { + executor.execute(() -> closePhysicalQuietly(abortError)); + } catch (RuntimeException rejectedEx) { + abortError.addSuppressed(rejectedEx); + closePhysicalQuietly(abortError); } + } - @Override - public void clearWarnings() throws SQLException { - bqConnectionDelegate.clearWarnings(); + void fireConnectionError(SQLException error) { + TerminalTransition transition = transitionToClosedAndMarkActiveHandle(); + if (transition == null) { + return; } - - @Override - public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) - throws SQLException { - return bqConnectionDelegate.createStatement(resultSetType, resultSetConcurrency); + synchronized (physicalLock) { + if (transition.previousHandle != null) { + transition.previousHandle.awaitQuiescence(); + } + closePhysicalQuietly(error); } + notifyConnectionErrorListeners(transition.listeners, error); + } - @Override - public java.sql.PreparedStatement prepareStatement( - String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return bqConnectionDelegate.prepareStatement(sql, resultSetType, resultSetConcurrency); + private void closePhysicalQuietly(SQLException primaryError) { + try { + this.bqConnection.close(); + } catch (SQLException closeEx) { + if (primaryError != null && closeEx != primaryError) { + primaryError.addSuppressed(closeEx); + } else { + LOG.warning(closeEx, "Failed to close physical connection after error"); + } } + } - @Override - public java.sql.CallableStatement prepareCall( - String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return bqConnectionDelegate.prepareCall(sql, resultSetType, resultSetConcurrency); + private void notifyConnectionClosedListeners(List snapshot) { + if (snapshot.isEmpty()) { + return; } - - @Override - public java.util.Map> getTypeMap() throws SQLException { - return bqConnectionDelegate.getTypeMap(); + ConnectionEvent event = new ConnectionEvent(this); + for (ConnectionEventListener listener : snapshot) { + try { + listener.connectionClosed(event); + } catch (RuntimeException ex) { + LOG.warning(ex, "ConnectionEventListener threw an exception during connectionClosed"); + } } + } - @Override - public void setTypeMap(java.util.Map> map) throws SQLException { - bqConnectionDelegate.setTypeMap(map); + private void notifyConnectionErrorListeners( + List snapshot, SQLException error) { + if (snapshot.isEmpty()) { + return; } - - @Override - public void setHoldability(int holdability) throws SQLException { - bqConnectionDelegate.setHoldability(holdability); + ConnectionEvent event = new ConnectionEvent(this, error); + for (ConnectionEventListener listener : snapshot) { + try { + listener.connectionErrorOccurred(event); + } catch (RuntimeException ex) { + LOG.warning( + ex, "ConnectionEventListener threw an exception during connectionErrorOccurred"); + } } + String message = error != null ? error.getMessage() : "Connection error occurred"; + LOG.finer( + "Pooled connection removed from pool due to error [connectionId=%s]: %s", + this.connectionId, message); + } - @Override - public int getHoldability() throws SQLException { - return bqConnectionDelegate.getHoldability(); + private SQLException runResetCapturingException() { + try { + this.bqConnection.resetForReuse(); + return null; + } catch (SQLException ex) { + return ex; + } catch (RuntimeException ex) { + return new BigQueryJdbcException("Failed to reset pooled connection state", ex); } + } - @Override - public java.sql.Savepoint setSavepoint() throws SQLException { - return bqConnectionDelegate.setSavepoint(); - } + private static final class TerminalTransition { + final List listeners; + final PooledConnectionInvocationHandler previousHandle; - @Override - public java.sql.Savepoint setSavepoint(String name) throws SQLException { - return bqConnectionDelegate.setSavepoint(name); + TerminalTransition( + List listeners, PooledConnectionInvocationHandler previousHandle) { + this.listeners = listeners; + this.previousHandle = previousHandle; } + } - @Override - public void rollback(java.sql.Savepoint savepoint) throws SQLException { - bqConnectionDelegate.rollback(savepoint); + private TerminalTransition transitionToClosedAndMarkActiveHandle() { + synchronized (stateLock) { + if (isHolderTerminalLocked()) { + return null; + } + this.state = State.CLOSED; + PooledConnectionInvocationHandler previous = this.activeHandle; + if (previous != null) { + previous.markClosed(); + this.activeHandle = null; + } + this.resettingHandle = null; + List snapshot = snapshotAllListenersLocked(); + this.internalPoolListener = null; + this.listeners.clear(); + return new TerminalTransition(snapshot, previous); } + } - @Override - public void releaseSavepoint(java.sql.Savepoint savepoint) throws SQLException { - bqConnectionDelegate.releaseSavepoint(savepoint); - } + @Override + public void addStatementEventListener(StatementEventListener arg0) { + UnsupportedOperationException ex = + new UnsupportedOperationException( + "Method 'addStatementEventListener' is not supported by the BQ Driver"); + LOG.severe(ex.getMessage(), ex); + throw ex; + } - @Override - public java.sql.Statement createStatement( - int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return bqConnectionDelegate.createStatement( - resultSetType, resultSetConcurrency, resultSetHoldability); - } + @Override + public void removeStatementEventListener(StatementEventListener arg0) { + UnsupportedOperationException ex = + new UnsupportedOperationException( + "Method 'removeStatementEventListener' is not supported by the BQ Driver"); + LOG.severe(ex.getMessage(), ex); + throw ex; + } - @Override - public java.sql.PreparedStatement prepareStatement( - String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException { - return bqConnectionDelegate.prepareStatement( - sql, resultSetType, resultSetConcurrency, resultSetHoldability); + static final class PooledConnectionInvocationHandler implements InvocationHandler { + private static final BigQueryJdbcCustomLogger LOG = + new BigQueryJdbcCustomLogger(PooledConnectionInvocationHandler.class.getName()); + + private final BigQueryConnection bqConnection; + private final Connection proxiedDelegate; + private final BigQueryPooledConnection pooledConnection; + private final AtomicBoolean closed = new AtomicBoolean(false); + private final ReentrantReadWriteLock handleLock = new ReentrantReadWriteLock(); + + PooledConnectionInvocationHandler( + BigQueryConnection bqConnection, + Connection proxiedDelegate, + BigQueryPooledConnection pooledConnection) { + this.bqConnection = bqConnection; + this.proxiedDelegate = proxiedDelegate; + this.pooledConnection = pooledConnection; } - @Override - public java.sql.CallableStatement prepareCall( - String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) - throws SQLException { - return bqConnectionDelegate.prepareCall( - sql, resultSetType, resultSetConcurrency, resultSetHoldability); + Connection createConnectionProxy() { + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), new Class[] {Connection.class}, this); } - @Override - public java.sql.PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) - throws SQLException { - return bqConnectionDelegate.prepareStatement(sql, autoGeneratedKeys); + void markClosed() { + this.closed.set(true); } - @Override - public java.sql.PreparedStatement prepareStatement(String sql, int[] columnIndices) - throws SQLException { - return bqConnectionDelegate.prepareStatement(sql, columnIndices); + void awaitQuiescence() { + this.handleLock.writeLock().lock(); + this.handleLock.writeLock().unlock(); } - @Override - public java.sql.PreparedStatement prepareStatement(String sql, String[] columnNames) - throws SQLException { - return bqConnectionDelegate.prepareStatement(sql, columnNames); + boolean isClosed() { + return this.closed.get() || this.bqConnection.isClosed(); } - @Override - public java.sql.Clob createClob() throws SQLException { - return bqConnectionDelegate.createClob(); + void checkClosed() throws BigQueryJdbcException { + if (isClosed()) { + throw new BigQueryJdbcException("Connection is closed."); + } } - @Override - public java.sql.Blob createBlob() throws SQLException { - return bqConnectionDelegate.createBlob(); + private void checkClosedForClientInfo(Object[] args) throws SQLClientInfoException { + if (isClosed()) { + throw buildClosedClientInfoException(args); + } } - @Override - public java.sql.NClob createNClob() throws SQLException { - return bqConnectionDelegate.createNClob(); + private static SQLClientInfoException buildClosedClientInfoException(Object[] args) { + if (args == null || args.length == 0 || args[0] == null) { + return new SQLClientInfoException("Connection is closed.", Collections.emptyMap()); + } + if (args.length == 2 && args[0] instanceof String) { + return new SQLClientInfoException( + "Connection is closed.", + Collections.singletonMap((String) args[0], ClientInfoStatus.REASON_UNKNOWN)); + } + if (args.length == 1 && args[0] instanceof Properties) { + Properties props = (Properties) args[0]; + Map failed = new HashMap<>(); + for (String name : props.stringPropertyNames()) { + failed.put(name, ClientInfoStatus.REASON_UNKNOWN); + } + return new SQLClientInfoException("Connection is closed.", failed); + } + return new SQLClientInfoException("Connection is closed.", Collections.emptyMap()); } @Override - public java.sql.SQLXML createSQLXML() throws SQLException { - return bqConnectionDelegate.createSQLXML(); - } + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); - @Override - public boolean isValid(int timeout) throws SQLException { - return bqConnectionDelegate.isValid(timeout); - } + if (method.getDeclaringClass() == Object.class) { + return invokeObjectMethod(proxy, methodName, args); + } - @Override - public void setClientInfo(String name, String value) throws java.sql.SQLClientInfoException { - bqConnectionDelegate.setClientInfo(name, value); - } + if ("close".equals(methodName) && (args == null || args.length == 0)) { + if (!this.closed.compareAndSet(false, true)) { + return null; + } + if (!this.bqConnection.isClosed()) { + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(this.bqConnection.getConnectionId())) { + LOG.finer("Closing logical connection handle."); + } + } + awaitQuiescence(); + this.pooledConnection.connectionHandleClosed(this); + return null; + } - @Override - public void setClientInfo(java.util.Properties properties) - throws java.sql.SQLClientInfoException { - bqConnectionDelegate.setClientInfo(properties); - } + if ("isClosed".equals(methodName) && (args == null || args.length == 0)) { + return isClosed(); + } - @Override - public String getClientInfo(String name) throws SQLException { - return bqConnectionDelegate.getClientInfo(name); - } + if ("abort".equals(methodName) && args != null && args.length == 1) { + Executor executor = (Executor) args[0]; + if (executor == null) { + throw new BigQueryJdbcException("Executor cannot be null."); + } + this.closed.set(true); + this.pooledConnection.abortHandle(this, executor); + return null; + } - @Override - public java.util.Properties getClientInfo() throws SQLException { - return bqConnectionDelegate.getClientInfo(); - } + if ("isValid".equals(methodName) && args != null && args.length == 1) { + int timeout = (Integer) args[0]; + if (timeout < 0) { + throw new BigQueryJdbcException("timeout must be >= 0"); + } + this.handleLock.readLock().lock(); + try { + if (isClosed()) { + return false; + } + return invokeDelegate(this.proxiedDelegate, method, args); + } finally { + this.handleLock.readLock().unlock(); + } + } - @Override - public java.sql.Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return bqConnectionDelegate.createArrayOf(typeName, elements); + if ("isWrapperFor".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + if (iface == null) { + return false; + } + this.handleLock.readLock().lock(); + try { + if (isClosed()) { + return false; + } + if (iface.isInstance(proxy)) { + return true; + } + return invokeDelegate(this.proxiedDelegate, method, args); + } finally { + this.handleLock.readLock().unlock(); + } + } + + if ("unwrap".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + this.handleLock.readLock().lock(); + try { + checkClosed(); + if (iface == null) { + throw new BigQueryJdbcException("Unable to unwrap to null interface."); + } + if (iface.isInstance(proxy)) { + return iface.cast(proxy); + } + return invokeDelegate(this.proxiedDelegate, method, args); + } finally { + this.handleLock.readLock().unlock(); + } + } + + if ("setClientInfo".equals(methodName)) { + this.handleLock.readLock().lock(); + try { + checkClosedForClientInfo(args); + Object result = invokeDelegate(this.proxiedDelegate, method, args); + checkClosedForClientInfo(args); + return result; + } finally { + this.handleLock.readLock().unlock(); + } + } + + this.handleLock.readLock().lock(); + try { + checkClosed(); + Object result = invokeDelegate(this.proxiedDelegate, method, args); + if (isClosed()) { + if (result instanceof Statement) { + closeStatementQuietly((Statement) result); + } + throw new BigQueryJdbcException("Connection is closed."); + } + return wrapChildObject((Connection) proxy, result); + } finally { + this.handleLock.readLock().unlock(); + } } - @Override - public java.sql.Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return bqConnectionDelegate.createStruct(typeName, attributes); + private Object wrapChildObject(Connection connectionProxy, Object result) throws SQLException { + if (result == null) { + return null; + } + if (result instanceof Statement) { + Statement stmt = (Statement) result; + Class stmtInterface = resolveStatementInterface(stmt); + Statement stmtProxy = + (Statement) + Proxy.newProxyInstance( + stmtInterface.getClassLoader(), + new Class[] {stmtInterface}, + new PooledStatementInvocationHandler(stmt, connectionProxy, this)); + if (stmt.isWrapperFor(BigQueryStatement.class)) { + stmt.unwrap(BigQueryStatement.class).attachPooledProxies(connectionProxy, stmtProxy); + } + return stmtProxy; + } + if (result instanceof DatabaseMetaData) { + return Proxy.newProxyInstance( + DatabaseMetaData.class.getClassLoader(), + new Class[] {DatabaseMetaData.class}, + new PooledDatabaseMetaDataInvocationHandler( + (DatabaseMetaData) result, connectionProxy, this)); + } + return result; } - @Override - public T unwrap(Class iface) throws SQLException { - return bqConnectionDelegate.unwrap(iface); + private static Class resolveStatementInterface(Statement stmt) { + if (stmt instanceof CallableStatement) { + return CallableStatement.class; + } + if (stmt instanceof PreparedStatement) { + return PreparedStatement.class; + } + return Statement.class; } + } - @Override - public boolean isWrapperFor(Class iface) throws SQLException { - return bqConnectionDelegate.isWrapperFor(iface); + private static final class PooledStatementInvocationHandler implements InvocationHandler { + private final Statement delegate; + private final Connection connectionProxy; + private final PooledConnectionInvocationHandler parentHandler; + + PooledStatementInvocationHandler( + Statement delegate, + Connection connectionProxy, + PooledConnectionInvocationHandler parentHandler) { + this.delegate = delegate; + this.connectionProxy = connectionProxy; + this.parentHandler = parentHandler; } @Override - public void setSchema(String schema) throws SQLException { - bqConnectionDelegate.setSchema(schema); + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + if (method.getDeclaringClass() == Object.class) { + return invokeObjectMethod(proxy, methodName, args); + } + if (("close".equals(methodName) + || "isClosed".equals(methodName) + || "cancel".equals(methodName)) + && (args == null || args.length == 0)) { + return invokeDelegate(this.delegate, method, args); + } + if ("getConnection".equals(methodName) && (args == null || args.length == 0)) { + if (this.delegate.isClosed()) { + throw new BigQueryJdbcException("Statement is closed."); + } + this.parentHandler.checkClosed(); + return this.connectionProxy; + } + if ("isWrapperFor".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + if (iface == null) { + return false; + } + this.parentHandler.handleLock.readLock().lock(); + try { + if (this.delegate.isClosed() || this.parentHandler.isClosed()) { + return false; + } + if (iface.isInstance(proxy)) { + return true; + } + return invokeDelegate(this.delegate, method, args); + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } + } + if ("unwrap".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + this.parentHandler.handleLock.readLock().lock(); + try { + if (this.delegate.isClosed()) { + throw new BigQueryJdbcException("Statement is closed."); + } + this.parentHandler.checkClosed(); + if (iface == null) { + throw new BigQueryJdbcException("Unable to unwrap to null interface."); + } + if (iface.isInstance(proxy)) { + return iface.cast(proxy); + } + return invokeDelegate(this.delegate, method, args); + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } + } + + this.parentHandler.handleLock.readLock().lock(); + try { + if (this.delegate.isClosed()) { + throw new BigQueryJdbcException("Statement is closed."); + } + this.parentHandler.checkClosed(); + Object result = invokeDelegate(this.delegate, method, args); + if (this.parentHandler.isClosed()) { + if (result instanceof ResultSet) { + closeResultSetQuietly((ResultSet) result); + } + closeStatementQuietly(this.delegate); + throw new BigQueryJdbcException("Connection is closed."); + } + return result; + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } } + } - @Override - public String getSchema() throws SQLException { - return bqConnectionDelegate.getSchema(); + private static final class PooledDatabaseMetaDataInvocationHandler implements InvocationHandler { + private final DatabaseMetaData delegate; + private final Connection connectionProxy; + private final PooledConnectionInvocationHandler parentHandler; + + PooledDatabaseMetaDataInvocationHandler( + DatabaseMetaData delegate, + Connection connectionProxy, + PooledConnectionInvocationHandler parentHandler) { + this.delegate = delegate; + this.connectionProxy = connectionProxy; + this.parentHandler = parentHandler; } @Override - public void setNetworkTimeout(java.util.concurrent.Executor executor, int milliseconds) - throws SQLException { - bqConnectionDelegate.setNetworkTimeout(executor, milliseconds); + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + if (method.getDeclaringClass() == Object.class) { + return invokeObjectMethod(proxy, methodName, args); + } + if ("getConnection".equals(methodName) && (args == null || args.length == 0)) { + this.parentHandler.checkClosed(); + return this.connectionProxy; + } + if ("isWrapperFor".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + if (iface == null) { + return false; + } + this.parentHandler.handleLock.readLock().lock(); + try { + if (this.parentHandler.isClosed()) { + return false; + } + if (iface.isInstance(proxy)) { + return true; + } + return invokeDelegate(this.delegate, method, args); + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } + } + if ("unwrap".equals(methodName) && args != null && args.length == 1) { + Class iface = (Class) args[0]; + this.parentHandler.handleLock.readLock().lock(); + try { + this.parentHandler.checkClosed(); + if (iface == null) { + throw new BigQueryJdbcException("Unable to unwrap to null interface."); + } + if (iface.isInstance(proxy)) { + return iface.cast(proxy); + } + return invokeDelegate(this.delegate, method, args); + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } + } + this.parentHandler.handleLock.readLock().lock(); + try { + this.parentHandler.checkClosed(); + Object result = invokeDelegate(this.delegate, method, args); + if (this.parentHandler.isClosed()) { + if (result instanceof ResultSet) { + closeResultSetQuietly((ResultSet) result); + } + throw new BigQueryJdbcException("Connection is closed."); + } + return result; + } finally { + this.parentHandler.handleLock.readLock().unlock(); + } } + } - @Override - public int getNetworkTimeout() throws SQLException { - return bqConnectionDelegate.getNetworkTimeout(); + private static void closeStatementQuietly(Statement statement) { + try { + statement.close(); + } catch (SQLException ignored) { + // Primary closed-connection exception takes precedence. } + } - @Override - public void abort(Executor arg0) throws SQLException { - LOG.finest("++enter++"); - if (!closed) { - // We notify the pooled connection that physical connection - // is being aborted. We assume here that abort() is called for - // error cases. - SQLException e = new SQLException("Connection is being terminated and aborted"); - pooledConnection.fireConnectionError(e); - closed = true; - LOG.finest("Logical connection aborted (removed from pool)."); - } - // Call the delate abort to actually close the undelying connection. - bqConnectionDelegate.abort(arg0); + private static void closeResultSetQuietly(ResultSet resultSet) { + try { + resultSet.close(); + } catch (SQLException ignored) { + // Primary closed-connection exception takes precedence. } } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; + private static Object invokeObjectMethod(Object proxy, String methodName, Object[] args) { + if ("equals".equals(methodName)) { + return proxy == args[0]; + } + if ("hashCode".equals(methodName)) { + return System.identityHashCode(proxy); + } + if ("toString".equals(methodName)) { + return proxy.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(proxy)); + } + throw new AssertionError("Unexpected Object method: " + methodName); } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - BigQueryPooledConnection other = (BigQueryPooledConnection) obj; - if (id == null) { - if (other.id != null) return false; - } else if (!id.equals(other.id)) return false; - return true; + private static Object invokeDelegate(Object target, Method method, Object[] args) + throws Throwable { + try { + return method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getCause(); + } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java index ffec23a4819a..01cf735f88fd 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatement.java @@ -31,6 +31,7 @@ import com.google.cloud.bigquery.exception.BigQueryJdbcSqlFeatureNotSupportedException; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.StatementExecution; +import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; import com.google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsRequest; import com.google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsResponse; @@ -82,15 +83,28 @@ class BigQueryPreparedStatement extends BigQueryStatement implements PreparedSta Schema resultSchema = null; // Feeds getMetaData(). Schema insertSchema = null; // Feeds the Storage Write API. private TableName insertTableName = null; + // Per-object adoption signal for getMetaData(); see BigQueryParameterHandler#bindingRecorded. + private boolean resultSetMetadataRecorded; + + BigQueryPreparedStatement(BigQueryConnection connection, String query) throws SQLException { + this(connection, query, false, true); + } BigQueryPreparedStatement(BigQueryConnection connection, String query, boolean skipDryRun) throws SQLException { - super(connection); + this(connection, query, skipDryRun, true); + } + + BigQueryPreparedStatement( + BigQueryConnection connection, String query, boolean skipDryRun, boolean recordTelemetry) + throws SQLException { + super(connection, recordTelemetry); this.currentQuery = query; QueryStatistics queryStatistics = skipDryRun ? null : describeQueryQuietly(); this.parameterCount = resolveParameterCount(query, queryStatistics); this.parameterHandler = - new BigQueryParameterHandler(this.parameterCount, this.isEnableTimestampPicos()); + new BigQueryParameterHandler( + this.parameterCount, this.isEnableTimestampPicos(), recordTelemetry); if (queryStatistics != null) { applyInferredParameterTypes(queryStatistics); captureInsertMetadata(queryStatistics); @@ -418,33 +432,47 @@ public int[] executeBatch() throws SQLException { .setQueryApiType( com.google.cloud.bigquery.jdbc.telemetry.v1.QueryApiType .QUERY_API_TYPE_WRITE_API); - try (BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient()) { - LOG.info("Using Write API for bulk INSERT operation."); - - long rowCount = bulkInsertWithWriteAPI(writeClient); - int[] insertArray = new int[Math.toIntExact(rowCount)]; - Arrays.fill(insertArray, 1); - - writeApiExecutionBuilder.setStatus( - com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_SUCCESS); + try { + int[] insertArray; + try (BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient()) { + LOG.info("Using Write API for bulk INSERT operation."); + long rowCount = bulkInsertWithWriteAPI(writeClient); + insertArray = new int[Math.toIntExact(rowCount)]; + Arrays.fill(insertArray, 1); + } + writeApiExecutionBuilder.setStatus(Status.STATUS_SUCCESS); + // Success-only, matching BigQueryStatement.executeBatch; failures are already captured + // by the StatementExecution status recorded in the finally block. + recordFeature(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); return insertArray; - } catch (InterruptedException e) { Thread.currentThread().interrupt(); writeApiExecutionBuilder - .setStatus(com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR) + .setStatus(Status.STATUS_ERROR) .setErrorCode(TelemetryManager.extractErrorCode(e)); throw new BigQueryJdbcException("Interrupted during Write API batch", e); } catch (DescriptorValidationException | IOException e) { writeApiExecutionBuilder - .setStatus(com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR) + .setStatus(Status.STATUS_ERROR) + .setErrorCode(TelemetryManager.extractErrorCode(e)); + throw new BigQueryJdbcException("Failed to execute batch with Write API", e); + } catch (SQLException e) { + writeApiExecutionBuilder + .setStatus(Status.STATUS_ERROR) + .setErrorCode(TelemetryManager.extractErrorCode(e)); + throw e; + } catch (RuntimeException e) { + writeApiExecutionBuilder + .setStatus(Status.STATUS_ERROR) .setErrorCode(TelemetryManager.extractErrorCode(e)); throw new BigQueryJdbcException("Failed to execute batch with Write API", e); } finally { + if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) { + writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(1000); + } long durationMs = System.currentTimeMillis() - startTime; - TelemetryManager.recordStatementExecution(writeApiExecutionBuilder, durationMs); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); + recordExecution(writeApiExecutionBuilder, durationMs); } } else { @@ -470,11 +498,10 @@ public int[] executeBatch() throws SQLException { getMoreResults(); i++; } + recordFeature(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); return result; } catch (SQLException e) { throw new BigQueryJdbcException("SQL error during individual INSERT batch", e); - } finally { - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); } } } @@ -629,9 +656,12 @@ public ResultSetMetaData getMetaData() throws SQLException { return null; } - TelemetryManager.recordFeatureUsage( - DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, - "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"); + if (!this.resultSetMetadataRecorded && isRecordingTelemetry()) { + this.resultSetMetadataRecorded = true; + TelemetryManager.recordFeatureUsage( + DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, + "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"); + } return BigQueryResultSetMetadata.of(this.resultSchema.getFields(), this); } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java index 13181dfc4806..640d7e9c28ca 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java @@ -76,6 +76,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; +import java.sql.Statement; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; @@ -91,6 +92,7 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; /** @@ -122,7 +124,9 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { protected JobIdWrapper parentJobId = null; protected int currentJobIdIndex = -1; protected List batchQueries = new ArrayList<>(); - protected BigQueryConnection connection; + protected volatile BigQueryConnection connection; + private volatile Connection logicalConnection; + private volatile Statement logicalStatementProxy; protected BigQueryParameterHandler parameterHandler = null; protected String connectionId; protected int maxFieldSize = 0; @@ -161,6 +165,39 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { protected StatementExecution.Builder currentExecutionBuilder = StatementExecution.newBuilder(); + /** + * False for statements the driver creates for its own purposes (connection validation, metadata + * queries). Those must not be reported as user activity, neither as feature usage nor as + * statement executions. + */ + private final boolean recordTelemetry; + + // Statement#cancel() is cross-thread per JDBC 4.3; AtomicBoolean ensures once-per-object + // recording. + private final AtomicBoolean cancelRecorded = new AtomicBoolean(); + + boolean isRecordingTelemetry() { + return this.recordTelemetry; + } + + boolean isInternal() { + return !this.recordTelemetry; + } + + /** Single choke point for execution records so internal statements never reach the batcher. */ + protected void recordExecution(StatementExecution.Builder builder, long durationMs) { + if (this.recordTelemetry) { + TelemetryManager.recordStatementExecution(builder, durationMs); + } + } + + /** Records {@code feature} unless this statement is internal. */ + protected void recordFeature(DriverFeature feature) { + if (this.recordTelemetry) { + TelemetryManager.recordFeatureUsage(feature); + } + } + static { BigQueryDaemonPollingTask.startGcDaemonTask( referenceQueueArrowRs, @@ -171,7 +208,12 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { @VisibleForTesting public BigQueryStatement(BigQueryConnection connection) throws SQLException { + this(connection, true); + } + + BigQueryStatement(BigQueryConnection connection, boolean recordTelemetry) throws SQLException { this.connection = connection; + this.recordTelemetry = recordTelemetry; this.connectionId = connection.getConnectionId(); this.bigQuery = connection.getBigQuery(); this.querySettings = generateBigQuerySettings(); @@ -415,6 +457,8 @@ public void close() throws SQLException { closeStatementResources(); } this.connection = null; + this.logicalConnection = null; + this.logicalStatementProxy = null; } } @@ -468,7 +512,9 @@ public void setQueryTimeout(int seconds) { public void cancel() throws SQLException { LOG.finer("Statement %s cancelled", this); cancelInternal(); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_STATEMENT_CANCEL); + if (this.cancelRecorded.compareAndSet(false, true)) { + recordFeature(DriverFeature.DRIVER_FEATURE_STATEMENT_CANCEL); + } } /** @@ -716,7 +762,7 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx .setErrorCode(errorCode); } - TelemetryManager.recordStatementExecution(this.currentExecutionBuilder, durationMs); + recordExecution(this.currentExecutionBuilder, durationMs); } } @@ -1828,14 +1874,24 @@ private int[] executeBatchImpl(String combinedQueries) throws SQLException { clearBatch(); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); + recordFeature(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); return result; } + void attachPooledProxies(Connection logicalConnection, Statement logicalStatementProxy) { + this.logicalConnection = logicalConnection; + this.logicalStatementProxy = logicalStatementProxy; + } + + Statement getLogicalStatementProxy() { + return this.logicalStatementProxy; + } + @Override public Connection getConnection() { - return this.connection; + Connection owner = this.logicalConnection; + return owner != null ? owner : this.connection; } public boolean hasMoreResults() { diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtility.java index b8346eaa77f4..e24e84378293 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtility.java @@ -234,7 +234,7 @@ static Instant parseEpochDecimalToInstant(String epochDecimal) { return null; } - BigDecimal bd = new BigDecimal(epochDecimal).setScale(9, RoundingMode.DOWN); + BigDecimal bd = parseScaledEpochDecimal(epochDecimal, 9); BigDecimal secondsBd = bd.setScale(0, RoundingMode.FLOOR); BigDecimal fractionBd = bd.subtract(secondsBd); int nanos = fractionBd.multiply(NANOS_PER_SECOND).intValue(); @@ -260,7 +260,7 @@ static String formatTimestampStringFromEpochDecimal( int scale = enableTimestampPicos ? 12 : 6; BigDecimal bd; try { - bd = new BigDecimal(epochDecimal).setScale(scale, RoundingMode.DOWN); + bd = parseScaledEpochDecimal(epochDecimal, scale); } catch (NumberFormatException e) { try { return formatTimestampStringFromIso(epochDecimal, enableTimestampPicos); @@ -275,12 +275,34 @@ static String formatTimestampStringFromEpochDecimal( BigDecimal multiplier = scale == 12 ? PICOS_PER_SECOND : MICROS_PER_SECOND; long fractionVal = fractionBd.multiply(multiplier).setScale(0, RoundingMode.DOWN).longValue(); - LocalDateTime dt = LocalDateTime.ofEpochSecond(epochSeconds, 0, ZoneOffset.UTC); + LocalDateTime dt; + try { + dt = LocalDateTime.ofEpochSecond(epochSeconds, 0, ZoneOffset.UTC); + } catch (DateTimeException e) { + throw new BigQueryJdbcException("Invalid timestamp value: " + epochDecimal, e); + } StringBuilder sb = formatDateTimeBase(dt, scale); appendPadded(sb, fractionVal, scale); return sb.toString(); } + private static BigDecimal parseScaledEpochDecimal(String epochDecimal, int scale) { + if (epochDecimal.length() > 128) { + throw new NumberFormatException("Epoch timestamp string too long"); + } + BigDecimal raw = new BigDecimal(epochDecimal); + if (raw.signum() == 0) { + return BigDecimal.ZERO.setScale(scale); + } + long integerDigits = (long) raw.precision() - (long) raw.scale(); + if (integerDigits > 17) { + throw new NumberFormatException("Epoch timestamp out of range"); + } + return integerDigits <= -scale + ? BigDecimal.ZERO.setScale(scale) + : raw.setScale(scale, RoundingMode.DOWN); + } + /** * Normalizes an ISO-8601 or civil timestamp string into a standard UTC JDBC timestamp string * formatted with 6 or 12 fractional digits according to {@code enableTimestampPicos}. diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java new file mode 100644 index 000000000000..75410fec19d6 --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java @@ -0,0 +1,110 @@ +/* + * 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.bigquery.jdbc; + +import java.nio.file.Path; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +/** + * Carries per-connection logging identity and threshold across threads and unproxied {@code + * ResultSet} log records without colliding with user or library {@code String} log parameters. + */ +final class ConnectionLogContext { + static final int OFF_VALUE = Level.OFF.intValue(); + static final int ALL_VALUE = Level.ALL.intValue(); + + private final String connectionId; + private final Path preConnectDir; + private final boolean explicitLevel; + private volatile int levelValue; + + ConnectionLogContext(String connectionId, int levelValue) { + this( + Objects.requireNonNull(connectionId, "connectionId cannot be null"), + levelValue, + null, + true); + } + + private ConnectionLogContext( + String connectionId, int levelValue, Path preConnectDir, boolean explicitLevel) { + this.connectionId = connectionId; + this.levelValue = levelValue; + this.preConnectDir = preConnectDir; + this.explicitLevel = explicitLevel; + } + + static ConnectionLogContext unregistered(String connectionId) { + return new ConnectionLogContext( + Objects.requireNonNull(connectionId, "connectionId cannot be null"), + ALL_VALUE, + null, + false); + } + + static ConnectionLogContext preConnect(int levelValue, Path preConnectDir) { + return new ConnectionLogContext(null, levelValue, preConnectDir, true); + } + + String connectionId() { + return connectionId; + } + + Path preConnectDir() { + return preConnectDir; + } + + boolean hasExplicitLevel() { + return explicitLevel; + } + + int levelValue() { + return levelValue; + } + + void setLevelValue(int levelValue) { + this.levelValue = levelValue; + } + + boolean isLoggable(Level level) { + if (level == null || levelValue == OFF_VALUE) { + return false; + } + if (levelValue == ALL_VALUE) { + return true; + } + return level.intValue() >= levelValue; + } + + static ConnectionLogContext extractFromParameters(LogRecord record) { + if (record == null) { + return null; + } + Object[] params = record.getParameters(); + if (params != null && params.length > 0 && params[0] instanceof ConnectionLogContext) { + return (ConnectionLogContext) params[0]; + } + return null; + } + + @Override + public String toString() { + return connectionId != null ? connectionId : "NO_CONN"; + } +} diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java index 7d91c128d9a7..61f5ac9f581a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -1013,10 +1013,18 @@ public void setGcpTelemetryCredentials(String gcpTelemetryCredentials) { this.gcpTelemetryCredentials = gcpTelemetryCredentials; } + /** Returns the universe domain explicitly set via URL or setter, or {@code null} if omitted. */ public String getUniverseDomain() { - return universeDomain != null - ? universeDomain - : BigQueryJdbcUrlUtility.DEFAULT_UNIVERSE_DOMAIN_VALUE; + return BigQueryJdbcUrlUtility.normalizeUniverseDomain(universeDomain); + } + + /** + * Resolves the client-endpoint universe domain from the explicit URL/DataSource setting or {@code + * GOOGLE_CLOUD_UNIVERSE_DOMAIN}, returning {@code null} when neither is set. + */ + String resolveUniverseDomain() { + String explicit = getUniverseDomain(); + return explicit != null ? explicit : BigQueryJdbcUrlUtility.getEnvUniverseDomain(); } public void setUniverseDomain(String universeDomain) { @@ -1523,10 +1531,14 @@ public void setByoidSubjectTokenType(String byoidSubjectTokenType) { this.byoidSubjectTokenType = byoidSubjectTokenType; } + /** + * Returns the explicit BYOID token URI if configured; otherwise derives {@code + * https://sts./v1/token} from the explicit universe domain. + */ public String getByoidTokenUri() { return byoidTokenUri != null ? byoidTokenUri - : BigQueryJdbcUrlUtility.DEFAULT_BYOID_TOKEN_URI_VALUE; + : BigQueryJdbcUrlUtility.formatByoidTokenUri(getUniverseDomain()); } public void setByoidTokenUri(String byoidTokenUri) { diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java index 79874f7d085a..a2829814c7e7 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java @@ -28,7 +28,9 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.context.Context; +import java.text.MessageFormat; import java.time.Instant; +import java.util.Arrays; import java.util.Collections; import java.util.logging.ErrorManager; import java.util.logging.Handler; @@ -54,19 +56,32 @@ public void publish(LogRecord record) { } try { - // Extract connection ID from baggage + ConnectionLogContext logContext = ConnectionLogContext.extractFromParameters(record); + if (logContext == null) { + logContext = BigQueryJdbcMdc.getConnectionContext(); + } + + // Extract connection ID from baggage, falling back to ConnectionLogContext String connectionId = Baggage.fromContext(Context.current()) .getEntryValue(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY); - if (connectionId == null || connectionId.isEmpty()) { - connectionId = BigQueryJdbcMdc.getConnectionId(); + connectionId = logContext != null ? logContext.connectionId() : null; } if (connectionId == null || connectionId.isEmpty()) { return; } + if (logContext == null || !connectionId.equals(logContext.connectionId())) { + logContext = BigQueryJdbcRootLogger.getConnectionContext(connectionId); + } + if (logContext != null + && logContext.hasExplicitLevel() + && !logContext.isLoggable(record.getLevel())) { + return; + } + BigQueryJdbcOpenTelemetry.TelemetryConfig config = BigQueryJdbcOpenTelemetry.getConnectionConfig(connectionId); if (config == null) { @@ -97,8 +112,9 @@ private void publishToGcp(LogRecord record, String connectionId, Logging logging logId = UNSAFE_LOG_CHARACTERS.matcher(logId).replaceAll("_"); } + String formatted = formatMessage(record); LogEntry.Builder builder = - LogEntry.newBuilder(Payload.StringPayload.of(formatMessage(record))) + LogEntry.newBuilder(Payload.StringPayload.of(formatted != null ? formatted : "")) .setSeverity(mapGcpSeverity(record.getLevel())) .setTimestamp(Instant.ofEpochMilli(record.getMillis())) .setLogName(logId); @@ -135,13 +151,16 @@ private void publishToOTel(LogRecord record, String connectionId, OpenTelemetry ? loggerName : BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME); + String formatted = formatMessage(record); LogRecordBuilder builder = logger .logRecordBuilder() - .setBody(formatMessage(record)) .setSeverity(mapSeverity(record.getLevel())) .setTimestamp(Instant.ofEpochMilli(record.getMillis())) .setContext(Context.current()); + if (formatted != null) { + builder.setBody(formatted); + } if (connectionId != null) { builder.setAttribute( @@ -165,15 +184,33 @@ private Severity mapSeverity(Level level) { private String formatMessage(LogRecord record) { String message = record.getMessage(); + if (message == null) { + return null; + } Object[] params = record.getParameters(); - if (params != null && params.length > 0) { - try { - return java.text.MessageFormat.format(message, params); - } catch (IllegalArgumentException e) { - return message; + if (params == null || params.length == 0) { + return message; + } + int startIndex = (params[0] instanceof ConnectionLogContext) ? 1 : 0; + if (params.length <= startIndex || !hasPositionalPlaceholder(message)) { + return message; + } + Object[] messageParams = + startIndex == 0 ? params : Arrays.copyOfRange(params, startIndex, params.length); + try { + return MessageFormat.format(message, messageParams); + } catch (IllegalArgumentException e) { + return message; + } + } + + private static boolean hasPositionalPlaceholder(String message) { + for (int i = 0; i <= 9; i++) { + if (message.indexOf("{" + i) >= 0) { + return true; } } - return message; + return false; } @Override diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index 0b5279cf6bf0..cce9cce44bc5 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -17,129 +17,990 @@ package com.google.cloud.bigquery.jdbc; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.FileSystems; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.nio.file.attribute.UserPrincipal; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.FileHandler; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.ErrorManager; +import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.regex.Pattern; /** * Custom logging handler that dynamically creates and routes log records to per-connection specific * log files using the connection ID retrieved from BigQueryJdbcMdc. */ class PerConnectionFileHandler extends Handler { + static final long DEFAULT_MAX_LOG_FILE_BYTES = 1024L * 1024L * 1024L; + static final String MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY = + "com.google.cloud.bigquery.jdbc.maxLogFileBytes"; + private static final String DEFAULT_HANDLER_ID = "Jdbc-default"; + private static final String GLOBAL_LOG_FILE_NAME = "BQ-JDBC-GLOBAL.log"; + private static final long GLOBAL_LOCK_POSITION = Long.MAX_VALUE - 1; + private static final int MAX_CREATE_ATTEMPTS = 16; + private static final int MAX_REOPEN_ATTEMPTS = 3; + private static final int MAX_WRITE_CHUNK_BYTES = 8192; + private static final int MAX_DISTINCT_REPORTED_ERRORS = 64; + private static final long OPEN_RETRY_BACKOFF_NANOS = 5_000_000_000L; + private static final Set ACTIVE_GLOBAL_PATHS = ConcurrentHashMap.newKeySet(); + private static final DateTimeFormatter FILE_TIMESTAMP_FORMAT = + DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + private static final Pattern UNSAFE_ID_CHARS = Pattern.compile("[^A-Za-z0-9_-]"); + private static final Set DIR_PERMS_0700 = + PosixFilePermissions.fromString("rwx------"); + private static final Set FILE_PERMS_0600 = + PosixFilePermissions.fromString("rw-------"); + private static final FileAttribute> DIR_ATTR_0700 = + PosixFilePermissions.asFileAttribute(DIR_PERMS_0700); + private static final FileAttribute> FILE_ATTR_0600 = + PosixFilePermissions.asFileAttribute(FILE_PERMS_0600); + private static final int PROCESS_UID = resolveProcessUid(); + private static final UserPrincipal PROCESS_PRINCIPAL = resolveProcessPrincipal(); + private static final AtomicReference LAST_WARNED_MAX_BYTES = new AtomicReference<>(); + static volatile Integer overrideUidForTesting; + private final Path baseLogPath; + private final boolean basePathPosix; private final Level level; - private final ConcurrentHashMap handlers = new ConcurrentHashMap<>(); - private FileHandler defaultHandler; + private final long maxFileBytes; + private final boolean managed; + private final Formatter logFormatter; + private final ConcurrentHashMap slots = new ConcurrentHashMap<>(); + private final ReentrantLock defaultWriterLock = new ReentrantLock(); + private ChannelLogWriter defaultWriter; + private boolean defaultWriterHasBackoff; + private long defaultWriterNextOpenNanos; + private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { - this.baseLogPath = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); + this(baseLogPath, level, resolveMaxLogFileBytes(), false); + } + + PerConnectionFileHandler(String baseLogPath, Level level, long maxFileBytes) { + this(baseLogPath, level, maxFileBytes, false); + } + + PerConnectionFileHandler(String baseLogPath, Level level, long maxFileBytes, boolean managed) { this.level = level; + this.maxFileBytes = maxFileBytes <= 0L ? DEFAULT_MAX_LOG_FILE_BYTES : maxFileBytes; + this.managed = managed; + this.logFormatter = BigQueryJdbcRootLogger.getFormatter(); + setLevel(level); + setFormatter(this.logFormatter); + setErrorManager(new DeduplicatingErrorManager()); + + Path initializedDir = null; + boolean detectedPosix = false; + try { + Path candidate = + Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath().normalize(); + Path root = candidate.getRoot(); + detectedPosix = root != null && supportsPosix(root); + initializedDir = ensureSecureDirectory(candidate, detectedPosix); + } catch (Exception e) { + reportError("Failed to initialize default log file", e, ErrorManager.OPEN_FAILURE); + } + this.baseLogPath = initializedDir; + this.basePathPosix = detectedPosix; + } + + Path getBaseLogPath() { + return baseLogPath; + } + + void registerConnection(String connectionId, Level connLevel) { + if (!managed + || handlerClosed + || connectionId == null + || connectionId.isEmpty() + || connLevel == null + || connLevel == Level.OFF) { + return; + } + ConnectionWriterSlot previous = slots.put(connectionId, new ConnectionWriterSlot(connLevel)); + if (previous != null) { + previous.closeSlot(); + } + } + static long resolveMaxLogFileBytes() { + String raw; try { - if (!Files.exists(this.baseLogPath)) { - Files.createDirectories(this.baseLogPath); + raw = System.getProperty(MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY); + } catch (SecurityException e) { + return DEFAULT_MAX_LOG_FILE_BYTES; + } + if (raw != null && !raw.trim().isEmpty()) { + String trimmed = raw.trim(); + try { + long parsed = Long.parseLong(trimmed); + if (parsed > 0L) { + return parsed; + } + } catch (NumberFormatException ignored) { + // Fall back to 1 GiB default on invalid property value. + } + if (!trimmed.equals(LAST_WARNED_MAX_BYTES.getAndSet(trimmed))) { + new ErrorManager() + .error( + "Ignoring invalid " + MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY + " value: " + trimmed, + null, + ErrorManager.GENERIC_FAILURE); + } + } + return DEFAULT_MAX_LOG_FILE_BYTES; + } + + private static int resolveProcessUid() { + Path procSelfStatus = Paths.get("/proc/self/status"); + if (Files.isReadable(procSelfStatus)) { + try { + List lines = Files.readAllLines(procSelfStatus, StandardCharsets.UTF_8); + for (String line : lines) { + if (line.startsWith("Uid:")) { + String[] parts = line.split("\\s+"); + if (parts.length >= 3) { + return Integer.parseInt(parts[2]); + } + } + } + } catch (Exception ignored) { + // Fall back to UserPrincipal lookup on platforms without /proc/self/status. } + } + return -1; + } + + private static UserPrincipal resolveProcessPrincipal() { + String userName = System.getProperty("user.name"); + if (userName == null || userName.isEmpty() || "?".equals(userName)) { + return null; + } + try { + return FileSystems.getDefault() + .getUserPrincipalLookupService() + .lookupPrincipalByName(userName); + } catch (Exception ignored) { + return null; + } + } - this.defaultHandler = createFileHandler("Jdbc-default"); + private static boolean supportsPosix(Path path) { + try { + return Files.getFileStore(path).supportsFileAttributeView("posix"); } catch (IOException e) { - reportError( - "Failed to initialize default log file", e, java.util.logging.ErrorManager.OPEN_FAILURE); + return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + } + } + + private static int effectiveProcessUid() { + Integer override = overrideUidForTesting; + return override != null ? override : PROCESS_UID; + } + + private static void verifySingleLinkCount(Path path) throws IOException { + try { + Object nlinkAttr = Files.getAttribute(path, "unix:nlink", LinkOption.NOFOLLOW_LINKS); + if (nlinkAttr instanceof Number && ((Number) nlinkAttr).intValue() > 1) { + throw new IOException("Refusing hard-linked log file (nlink > 1): " + path); + } + } catch (UnsupportedOperationException | IllegalArgumentException ignored) { + // Non-Unix filesystems do not expose unix:nlink. } } - private String getLogFilePath(String id) { - if ("Jdbc-default".equals(id)) { - return baseLogPath.resolve("BQ-JDBC-GLOBAL.log").toString(); + private static void verifyPosixOwner(Path path, boolean allowRootOwner) throws IOException { + int processUid = effectiveProcessUid(); + if (processUid >= 0) { + Object uidAttr = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (uidAttr instanceof Number) { + int fileUid = ((Number) uidAttr).intValue(); + if (fileUid == processUid || (allowRootOwner && fileUid == 0)) { + return; + } + throw new IOException("Refusing to use path owned by uid " + fileUid + ": " + path); + } } + PosixFileAttributes posixAttrs = + Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + UserPrincipal owner = posixAttrs.owner(); + if (allowRootOwner && owner != null && "root".equals(owner.getName())) { + return; + } + if (PROCESS_PRINCIPAL != null && PROCESS_PRINCIPAL.equals(owner)) { + return; + } + throw new IOException("Refusing to use path owned by untrusted user: " + path); + } + + static Path ensureSecureDirectory(Path dir) throws IOException { + Path normalized = dir.toAbsolutePath().normalize(); + Path root = normalized.getRoot(); + return ensureSecureDirectory(normalized, root != null && supportsPosix(root)); + } + + private static Path ensureSecureDirectory(Path dir, boolean isPosix) throws IOException { + Path normalized = dir.toAbsolutePath().normalize(); + Path root = normalized.getRoot(); + if (root == null) { + throw new IOException("Cannot resolve root for log path: " + dir); + } + Path current = root; + int nameCount = normalized.getNameCount(); + for (int i = 0; i < nameCount; i++) { + current = current.resolve(normalized.getName(i)); + boolean isTarget = (i == nameCount - 1); + if (Files.exists(current, LinkOption.NOFOLLOW_LINKS)) { + BasicFileAttributes attrs = + Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attrs.isSymbolicLink()) { + if (isTarget || !isPosix) { + throw new IOException("Refusing to use symbolic link in log path: " + current); + } + verifyPosixOwner(current, true); + if (!Files.isDirectory(current)) { + throw new IOException("Ancestor symlink does not resolve to directory: " + current); + } + continue; + } + if (!attrs.isDirectory() || attrs.isOther()) { + throw new IOException("Log path component is not a regular directory: " + current); + } + if (isTarget && isPosix) { + verifyPosixOwner(current, true); + } + } else { + try { + if (isPosix) { + Files.createDirectory(current, DIR_ATTR_0700); + } else { + Files.createDirectory(current); + } + } catch (FileAlreadyExistsException raceIgnored) { + BasicFileAttributes attrs = + Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attrs.isSymbolicLink() || !attrs.isDirectory() || attrs.isOther()) { + throw new IOException("Concurrent non-directory created at log path: " + current); + } + if (isTarget && isPosix) { + verifyPosixOwner(current, true); + } + } + } + } + return normalized; + } + + private static String sanitizeIdSegment(String id) { String uuid = id; if (id.startsWith("BQ-JDBC-")) { uuid = id.substring("BQ-JDBC-".length()); } - String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); - String shortUuid = uuid.length() >= 4 ? uuid.substring(0, 4) : uuid; - return baseLogPath.resolve("BQ-JDBC-" + timestamp + "-" + shortUuid + ".log").toString(); + String cleaned = UNSAFE_ID_CHARS.matcher(uuid).replaceAll(""); + if (cleaned.isEmpty()) { + cleaned = "conn"; + } + return cleaned.length() >= 4 ? cleaned.substring(0, 4) : cleaned; + } + + private static FileChannel openExclusiveNewChannel(Path path, boolean isPosix) + throws IOException { + EnumSet opts = + EnumSet.of( + StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.APPEND); + if (isPosix) { + return FileChannel.open(path, opts, FILE_ATTR_0600); + } + return FileChannel.open(path, opts); + } + + private static FileChannel openAppendValidated(Path path, boolean isPosix) throws IOException { + BasicFileAttributes attrs = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attrs.isSymbolicLink() || !attrs.isRegularFile() || attrs.isOther()) { + throw new IOException("Refusing non-regular log file: " + path); + } + if (isPosix) { + verifyPosixOwner(path, false); + verifySingleLinkCount(path); + Files.setPosixFilePermissions(path, FILE_PERMS_0600); + } + FileChannel fc = + FileChannel.open( + path, StandardOpenOption.WRITE, StandardOpenOption.APPEND, LinkOption.NOFOLLOW_LINKS); + try { + BasicFileAttributes postAttrs = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (postAttrs.isSymbolicLink() || !postAttrs.isRegularFile() || postAttrs.isOther()) { + throw new IOException("Log file changed to non-regular file during open: " + path); + } + if (isPosix) { + verifyPosixOwner(path, false); + verifySingleLinkCount(path); + } + return fc; + } catch (IOException | RuntimeException e) { + try { + fc.close(); + } catch (IOException suppressed) { + e.addSuppressed(suppressed); + } + throw e; + } } - private FileHandler createFileHandler(String id) { + private static FileLock tryAcquireSentinelLock(FileChannel fc) throws IOException { try { - String filePath = getLogFilePath(id); - FileHandler fh = new FileHandler(filePath, 0, 1, true); - fh.setLevel(level); - fh.setFormatter(BigQueryJdbcRootLogger.getFormatter()); - return fh; - } catch (IOException e) { - reportError( - "Failed to create log file for connection " + id, - e, - java.util.logging.ErrorManager.OPEN_FAILURE); + return fc.tryLock(GLOBAL_LOCK_POSITION, 1L, false); + } catch (OverlappingFileLockException contendedInJvm) { return null; } } + private static OpenedLogFile openFallbackGlobalChannel(Path logDir, boolean isPosix) + throws IOException { + String timestamp = LocalDateTime.now().format(FILE_TIMESTAMP_FORMAT); + for (int attempt = 0; attempt < MAX_CREATE_ATTEMPTS; attempt++) { + String suffix = String.format("%04x", ThreadLocalRandom.current().nextInt(0x10000)); + Path candidate = logDir.resolve("BQ-JDBC-GLOBAL-" + timestamp + "-" + suffix + ".log"); + try { + FileChannel fc = openExclusiveNewChannel(candidate, isPosix); + FileLock lock = null; + try { + lock = tryAcquireSentinelLock(fc); + } catch (IOException ignored) { + // Exclusive CREATE_NEW already guarantees uniqueness if locking is unsupported. + } + return new OpenedLogFile(candidate, fc, lock, null); + } catch (FileAlreadyExistsException collision) { + // Retry with fresh random suffix. + } + } + throw new IOException("Unable to allocate fallback global log file in " + logDir); + } + + private static OpenedLogFile openGlobalChannel(Path logDir, boolean isPosix) throws IOException { + Path realLogDir = logDir.toRealPath(); + Path globalPath = realLogDir.resolve(GLOBAL_LOG_FILE_NAME); + Path claimKey = globalPath; + if (ACTIVE_GLOBAL_PATHS.add(claimKey)) { + boolean keepClaim = false; + try { + FileChannel fc; + try { + fc = openExclusiveNewChannel(globalPath, isPosix); + } catch (FileAlreadyExistsException existing) { + fc = openAppendValidated(globalPath, isPosix); + } + FileLock lock = null; + boolean lockSupported = true; + try { + lock = tryAcquireSentinelLock(fc); + } catch (IOException lockUnsupported) { + lockSupported = false; + } + if (lock != null || !lockSupported) { + keepClaim = true; + return new OpenedLogFile(globalPath, fc, lock, claimKey); + } + fc.close(); + } catch (IOException | RuntimeException primaryFailure) { + // Fall through to unique per-process global log file when primary is foreign-owned/locked. + } finally { + if (!keepClaim) { + ACTIVE_GLOBAL_PATHS.remove(claimKey); + } + } + } + return openFallbackGlobalChannel(realLogDir, isPosix); + } + + private static OpenedLogFile openConnectionChannel(Path logDir, String id, boolean isPosix) + throws IOException { + String shortUuid = sanitizeIdSegment(id); + String timestamp = LocalDateTime.now().format(FILE_TIMESTAMP_FORMAT); + for (int attempt = 0; attempt < MAX_CREATE_ATTEMPTS; attempt++) { + String fileName = + attempt == 0 + ? "BQ-JDBC-" + timestamp + "-" + shortUuid + ".log" + : "BQ-JDBC-" + timestamp + "-" + attempt + "-" + shortUuid + ".log"; + Path candidate = logDir.resolve(fileName); + try { + FileChannel fc = openExclusiveNewChannel(candidate, isPosix); + return new OpenedLogFile(candidate, fc, null, null); + } catch (FileAlreadyExistsException collision) { + // Retry with collision counter when two connections share timestamp + 4-char prefix. + } + } + throw new IOException("Unable to allocate unique log file for connection " + id); + } + + private static Path deriveBackupPath(Path activePath) { + String fileName = activePath.getFileName().toString(); + String backupName = + fileName.endsWith(".log") + ? fileName.substring(0, fileName.length() - 4) + ".1.log" + : fileName + ".1"; + return activePath.resolveSibling(backupName); + } + + private static OpenedLogFile reopenRotatedTarget( + Path logDir, String id, Path preferredPath, Path heldClaimKey, boolean isPosix) + throws IOException { + try { + FileChannel fc = openExclusiveNewChannel(preferredPath, isPosix); + FileLock lock = null; + if (DEFAULT_HANDLER_ID.equals(id)) { + try { + lock = tryAcquireSentinelLock(fc); + } catch (IOException ignored) { + // Locking unsupported on filesystem; CREATE_NEW still succeeded. + } + } + return new OpenedLogFile(preferredPath, fc, lock, heldClaimKey); + } catch (FileAlreadyExistsException contended) { + if (heldClaimKey != null) { + ACTIVE_GLOBAL_PATHS.remove(heldClaimKey); + } + return DEFAULT_HANDLER_ID.equals(id) + ? openFallbackGlobalChannel(logDir, isPosix) + : openConnectionChannel(logDir, id, isPosix); + } + } + + ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel, long limitBytes) { + if (logDir == null) { + return null; + } + boolean interrupted = Thread.interrupted(); + try { + boolean isPosix = (logDir == baseLogPath) ? basePathPosix : supportsPosix(logDir); + Path verifiedDir = ensureSecureDirectory(logDir, isPosix); + OpenedLogFile opened = + DEFAULT_HANDLER_ID.equals(id) + ? openGlobalChannel(verifiedDir, isPosix) + : openConnectionChannel(verifiedDir, id, isPosix); + return new ChannelLogWriter( + id, verifiedDir, opened, isPosix, writerLevel, limitBytes, logFormatter, this); + } catch (Exception e) { + reportError("Failed to create log file for connection " + id, e, ErrorManager.OPEN_FAILURE); + return null; + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + @Override public void publish(LogRecord record) { - if (!isLoggable(record)) { + if (handlerClosed || record == null || !isLoggable(record)) { return; } - String connectionId = BigQueryJdbcMdc.getConnectionId(); - if (connectionId == null || connectionId.isEmpty()) { - Object[] params = record.getParameters(); - if (params != null && params.length > 0 && params[0] instanceof String) { - connectionId = (String) params[0]; + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context == null) { + context = BigQueryJdbcMdc.getConnectionContext(); + } + String connectionId = context != null ? context.connectionId() : null; + + if (managed) { + if (connectionId != null && !connectionId.isEmpty()) { + ConnectionWriterSlot slot = slots.get(connectionId); + if (slot == null || !slot.allows(record.getLevel())) { + return; + } + if (baseLogPath != null) { + publishToSlot(slot, connectionId, record); + } + return; } + if (context == null + || !context.isLoggable(record.getLevel()) + || context.preConnectDir() == null + || baseLogPath == null + || !baseLogPath.equals(context.preConnectDir())) { + return; + } + publishToDefault(record); + return; } - FileHandler handler = defaultHandler; - if (connectionId != null && !connectionId.isEmpty()) { - handler = handlers.computeIfAbsent(connectionId, this::createFileHandler); - if (handler == null) { - handler = defaultHandler; + if (connectionId != null && !connectionId.isEmpty() && baseLogPath != null) { + ConnectionWriterSlot slot = + slots.compute( + connectionId, + (id, existing) -> { + if (handlerClosed) { + return null; + } + if (existing != null && !existing.isClosed()) { + return existing; + } + return new ConnectionWriterSlot(this.level); + }); + if (slot != null) { + publishToSlot(slot, connectionId, record); } + return; } - if (handler != null) { - handler.publish(record); + publishToDefault(record); + } + + private void publishToDefault(LogRecord record) { + ChannelLogWriter target; + defaultWriterLock.lock(); + try { + if (handlerClosed || baseLogPath == null) { + return; + } + if (defaultWriter == null) { + long now = System.nanoTime(); + if (!defaultWriterHasBackoff || now - defaultWriterNextOpenNanos >= 0L) { + defaultWriter = createLogWriter(DEFAULT_HANDLER_ID, baseLogPath, level, maxFileBytes); + defaultWriterHasBackoff = (defaultWriter == null); + defaultWriterNextOpenNanos = now + OPEN_RETRY_BACKOFF_NANOS; + } + } + target = defaultWriter; + } finally { + defaultWriterLock.unlock(); + } + if (!handlerClosed && target != null && !target.publish(record)) { + defaultWriterLock.lock(); + try { + if (defaultWriter == target) { + defaultWriter = null; + } + } finally { + defaultWriterLock.unlock(); + } } } - @Override - public void flush() { - if (defaultHandler != null) { - defaultHandler.flush(); + private void publishToSlot(ConnectionWriterSlot slot, String connectionId, LogRecord record) { + ChannelLogWriter target; + slot.lock.lock(); + try { + if (slot.closed || handlerClosed) { + slot.closeSlot(); + return; + } + if (slot.writer == null) { + long now = System.nanoTime(); + if (!slot.hasBackoff || now - slot.nextOpenAttemptNanos >= 0L) { + slot.writer = createLogWriter(connectionId, baseLogPath, slot.allowedLevel, maxFileBytes); + slot.hasBackoff = (slot.writer == null); + slot.nextOpenAttemptNanos = now + OPEN_RETRY_BACKOFF_NANOS; + } + } + target = slot.writer; + } finally { + slot.lock.unlock(); } - for (FileHandler h : handlers.values()) { - h.flush(); + if (handlerClosed) { + return; + } + if (target == null) { + publishToDefault(record); + } else if (!target.publish(record)) { + slot.lock.lock(); + try { + if (slot.writer == target) { + slot.writer = null; + } + } finally { + slot.lock.unlock(); + } } } + @Override + public void flush() { + // Unbuffered OS file channel writes are immediately visible to readers without JVM buffering. + } + @Override public void close() throws SecurityException { - for (FileHandler h : handlers.values()) { - try { - h.close(); - } catch (Exception e) { + handlerClosed = true; + for (String id : slots.keySet()) { + ConnectionWriterSlot removed = slots.remove(id); + if (removed != null) { + removed.closeSlot(); } } + for (ConnectionWriterSlot remaining : slots.values()) { + remaining.closeSlot(); + } + slots.clear(); + defaultWriterLock.lock(); try { - if (defaultHandler != null) defaultHandler.close(); + if (defaultWriter != null) { + defaultWriter.close(); + defaultWriter = null; + } } finally { - handlers.clear(); + defaultWriterLock.unlock(); } } - public void closeHandler(String connectionId) { + void closeHandler(String connectionId) { if (connectionId != null) { - FileHandler handler = handlers.remove(connectionId); - if (handler != null) { - handler.close(); + ConnectionWriterSlot removed = slots.remove(connectionId); + if (removed != null) { + removed.closeSlot(); + } + } + } + + private static final class ConnectionWriterSlot { + final ReentrantLock lock = new ReentrantLock(); + final Level allowedLevel; + ChannelLogWriter writer; + boolean closed; + boolean hasBackoff; + long nextOpenAttemptNanos; + + ConnectionWriterSlot(Level allowedLevel) { + this.allowedLevel = allowedLevel; + } + + boolean allows(Level recordLevel) { + return allowedLevel != null + && allowedLevel != Level.OFF + && recordLevel != null + && recordLevel.intValue() >= allowedLevel.intValue(); + } + + boolean isClosed() { + lock.lock(); + try { + return closed; + } finally { + lock.unlock(); + } + } + + void closeSlot() { + lock.lock(); + try { + if (closed) { + return; + } + closed = true; + if (writer != null) { + try { + writer.close(); + } finally { + writer = null; + } + } + } finally { + lock.unlock(); + } + } + } + + private static final class DeduplicatingErrorManager extends ErrorManager { + private final Set seen = ConcurrentHashMap.newKeySet(); + + @Override + public void error(String msg, Exception ex, int code) { + String key = code + ":" + (msg != null ? msg : ""); + if (seen.size() >= MAX_DISTINCT_REPORTED_ERRORS || !seen.add(key)) { + return; + } + String text = "java.util.logging.ErrorManager: " + code + (msg != null ? ": " + msg : ""); + System.err.println(text); + if (ex != null) { + ex.printStackTrace(System.err); + } + } + } + + static final class OpenedLogFile { + final Path path; + final FileChannel channel; + final FileLock lock; + final Path globalClaimKey; + + OpenedLogFile(Path path, FileChannel channel, FileLock lock, Path globalClaimKey) { + this.path = path; + this.channel = channel; + this.lock = lock; + this.globalClaimKey = globalClaimKey; + } + } + + static final class ChannelLogWriter { + private final ReentrantLock lock = new ReentrantLock(); + private final String id; + private final Path logDir; + private final boolean isPosix; + private final Level writerLevel; + private final long maxBytes; + private final Formatter formatter; + private final PerConnectionFileHandler owner; + private Path filePath; + private Path globalClaimKey; + private FileChannel channel; + private FileLock fileLock; + private long writtenBytes; + private boolean closed; + + ChannelLogWriter( + String id, + Path logDir, + OpenedLogFile opened, + boolean isPosix, + Level writerLevel, + long maxBytes, + Formatter formatter, + PerConnectionFileHandler owner) + throws IOException { + this.id = id; + this.logDir = logDir; + this.filePath = opened.path; + this.channel = opened.channel; + this.fileLock = opened.lock; + this.globalClaimKey = opened.globalClaimKey; + this.isPosix = isPosix; + this.writerLevel = writerLevel; + this.maxBytes = maxBytes; + this.formatter = formatter; + this.owner = owner; + this.writtenBytes = opened.channel.size(); + } + + private void reopenAfterInterrupt() throws IOException { + FileChannel reopened = openAppendValidated(filePath, isPosix); + FileLock reacquired = null; + if (globalClaimKey != null) { + try { + reacquired = tryAcquireSentinelLock(reopened); + if (reacquired == null) { + reopened.close(); + throw new IOException( + "Lost global log file lock during interrupt recovery: " + filePath); + } + } catch (IOException e) { + try { + reopened.close(); + } catch (IOException suppressed) { + e.addSuppressed(suppressed); + } + throw e; + } + } + this.channel = reopened; + this.fileLock = reacquired; + this.writtenBytes = reopened.size(); + } + + private void rotate() throws IOException { + Path backupPath = deriveBackupPath(filePath); + if (Files.exists(backupPath, LinkOption.NOFOLLOW_LINKS)) { + BasicFileAttributes backupAttrs = + Files.readAttributes(backupPath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (backupAttrs.isSymbolicLink()) { + Files.deleteIfExists(backupPath); + } else if (!backupAttrs.isRegularFile() || backupAttrs.isOther()) { + throw new IOException("Refusing to rotate onto non-regular backup path: " + backupPath); + } + } + if (fileLock != null && fileLock.isValid()) { + try { + fileLock.release(); + } catch (IOException ignored) { + } + fileLock = null; + } + if (channel != null) { + channel.close(); + channel = null; + } + try { + Files.move(filePath, backupPath, StandardCopyOption.REPLACE_EXISTING); + } catch (Exception moveEx) { + try { + reopenAfterInterrupt(); + } catch (Exception recoverEx) { + moveEx.addSuppressed(recoverEx); + } + if (moveEx instanceof IOException) { + throw (IOException) moveEx; + } + throw new IOException("Failed to move active log file to backup", moveEx); + } + if (isPosix) { + try { + Files.setPosixFilePermissions(backupPath, FILE_PERMS_0600); + } catch (Exception permEx) { + owner.reportError( + "Failed to set permissions on rotated log file", permEx, ErrorManager.WRITE_FAILURE); + } + } + OpenedLogFile reopened = reopenRotatedTarget(logDir, id, filePath, globalClaimKey, isPosix); + this.filePath = reopened.path; + this.channel = reopened.channel; + this.fileLock = reopened.lock; + this.globalClaimKey = reopened.globalClaimKey; + this.writtenBytes = reopened.channel.size(); + } + + private void truncateInPlace(Exception rotEx, int incomingBytes) throws IOException { + if (channel == null || !channel.isOpen()) { + reopenAfterInterrupt(); + } + channel.truncate(0L); + channel.position(0L); + writtenBytes = 0L; + String reason = rotEx.getClass().getSimpleName(); + byte[] notice = + ("[LOG TRUNCATED: backup rotation failed (" + reason + ")]" + System.lineSeparator()) + .getBytes(StandardCharsets.UTF_8); + if (maxBytes <= 0L || notice.length <= maxBytes - incomingBytes) { + ByteBuffer noticeBuf = ByteBuffer.wrap(notice); + while (noticeBuf.hasRemaining()) { + writtenBytes += channel.write(noticeBuf); + } + } + } + + boolean publish(LogRecord record) { + if (record.getLevel().intValue() < writerLevel.intValue()) { + return true; + } + String formatted; + try { + formatted = formatter.format(record); + } catch (Exception e) { + owner.reportError("Failed to format log record", e, ErrorManager.FORMAT_FAILURE); + return true; + } + byte[] bytes = formatted.getBytes(StandardCharsets.UTF_8); + lock.lock(); + try { + if (closed) { + return false; + } + boolean interrupted = false; + try { + for (int attempt = 0; attempt < MAX_REOPEN_ATTEMPTS; attempt++) { + interrupted |= Thread.interrupted(); + try { + if (channel == null || !channel.isOpen()) { + reopenAfterInterrupt(); + } + if (maxBytes > 0L + && writtenBytes > 0L + && (writtenBytes >= maxBytes || bytes.length > maxBytes - writtenBytes)) { + try { + rotate(); + } catch (Exception rotEx) { + owner.reportError("Failed to rotate log file", rotEx, ErrorManager.WRITE_FAILURE); + truncateInPlace(rotEx, bytes.length); + } + } + ByteBuffer buf = ByteBuffer.wrap(bytes); + int total = bytes.length; + while (buf.position() < total) { + buf.limit(Math.min(buf.position() + MAX_WRITE_CHUNK_BYTES, total)); + while (buf.hasRemaining()) { + writtenBytes += channel.write(buf); + } + } + return true; + } catch (ClosedByInterruptException cbie) { + interrupted = true; + Thread.interrupted(); + if (attempt + 1 >= MAX_REOPEN_ATTEMPTS) { + owner.reportError( + "Failed to write log record after interrupt", cbie, ErrorManager.WRITE_FAILURE); + return true; + } + } + } + } catch (IOException e) { + owner.reportError("Failed to write log record", e, ErrorManager.WRITE_FAILURE); + if (channel == null) { + closed = true; + if (globalClaimKey != null) { + ACTIVE_GLOBAL_PATHS.remove(globalClaimKey); + globalClaimKey = null; + } + return false; + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + return true; + } finally { + lock.unlock(); + } + } + + void close() { + lock.lock(); + try { + if (closed) { + return; + } + closed = true; + try { + if (fileLock != null && fileLock.isValid()) { + try { + fileLock.release(); + } catch (IOException ignored) { + } + } + if (channel != null) { + try { + channel.close(); + } catch (IOException e) { + owner.reportError("Failed to close log file", e, ErrorManager.CLOSE_FAILURE); + } + } + } finally { + fileLock = null; + channel = null; + if (globalClaimKey != null) { + ACTIVE_GLOBAL_PATHS.remove(globalClaimKey); + globalClaimKey = null; + } + } + } finally { + lock.unlock(); } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSource.java index 0a986bd860b5..38eee2a11aee 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSource.java @@ -16,11 +16,9 @@ package com.google.cloud.bigquery.jdbc; -import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; import com.google.common.annotations.VisibleForTesting; -import java.sql.Connection; import java.sql.SQLException; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; @@ -28,42 +26,44 @@ public class PooledConnectionDataSource extends DataSource implements ConnectionPoolDataSource { private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(PooledConnectionDataSource.class.getName()); - private PooledConnectionListener connectionPoolManager = null; - Connection bqConnection = null; + private volatile PooledConnectionListener connectionPoolManager = null; @Override public PooledConnection getPooledConnection() throws SQLException { - if (connectionPoolManager != null && !connectionPoolManager.isConnectionPoolEmpty()) { - return connectionPoolManager.getPooledConnection(); - } - // Create the Underlying physical connection - if (bqConnection == null) { - bqConnection = super.getConnection(); - } - if (bqConnection == null) { - throw new BigQueryJdbcRuntimeException( - "Cannot get pooled connection: unable to get underlying physical connection"); - } - BigQueryConnection physicalConnection; - if (bqConnection.isWrapperFor(BigQueryConnection.class)) { - physicalConnection = bqConnection.unwrap(BigQueryConnection.class); - } else { - physicalConnection = (BigQueryConnection) bqConnection; - } - Long connectionPoolSize = physicalConnection.getConnectionPoolSize(); - if (connectionPoolManager == null) { - connectionPoolManager = new PooledConnectionListener(connectionPoolSize); + PooledConnectionListener poolManager = this.connectionPoolManager; + if (poolManager != null) { + BigQueryPooledConnection candidate; + while ((candidate = poolManager.getPooledConnection()) != null) { + BigQueryConnection reusedPhysical = candidate.claimPhysicalForReuse(poolManager); + if (reusedPhysical != null) { + BigQueryPooledConnection recycled = new BigQueryPooledConnection(reusedPhysical); + recycled.registerInternalPoolListener(poolManager); + TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_CONNECTION_POOLING); + return recycled; + } + } } + + BigQueryConnection physicalConnection = super.getConnection().unwrap(BigQueryConnection.class); + poolManager = getOrInitConnectionPoolManager(physicalConnection.getConnectionPoolSize()); BigQueryPooledConnection bqPooledConnection = new BigQueryPooledConnection(physicalConnection); - bqPooledConnection.addConnectionEventListener(connectionPoolManager); + bqPooledConnection.registerInternalPoolListener(poolManager); TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_CONNECTION_POOLING); return bqPooledConnection; } - @VisibleForTesting - void setConnection(Connection connection) { - this.bqConnection = connection; + private PooledConnectionListener getOrInitConnectionPoolManager(Long resolvedPoolSize) { + PooledConnectionListener existing = this.connectionPoolManager; + if (existing != null) { + return existing; + } + synchronized (this) { + if (this.connectionPoolManager == null) { + this.connectionPoolManager = new PooledConnectionListener(resolvedPoolSize); + } + return this.connectionPoolManager; + } } @VisibleForTesting diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionListener.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionListener.java index 86bc9626a08b..5eab5869d2ae 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionListener.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PooledConnectionListener.java @@ -16,8 +16,8 @@ package com.google.cloud.bigquery.jdbc; -import java.util.UUID; -import java.util.concurrent.LinkedBlockingDeque; +import java.util.ArrayDeque; +import java.util.Deque; import javax.sql.ConnectionEvent; import javax.sql.ConnectionEventListener; import javax.sql.PooledConnection; @@ -25,18 +25,18 @@ public class PooledConnectionListener implements ConnectionEventListener { private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(PooledConnectionListener.class.getName()); - private String id; // Mainly for internal use - private LinkedBlockingDeque connectionPool; - private Long connectionPoolSize = 0L; + private final Deque connectionPool; + private final Long connectionPoolSize; + private final int maxCapacity; + private final Object poolLock = new Object(); public PooledConnectionListener(Long connPoolSize) { - id = UUID.randomUUID().toString(); - this.connectionPoolSize = connPoolSize; - if (getConnectionPoolSize() > 0L) { - connectionPool = new LinkedBlockingDeque<>(getConnectionPoolSize().intValue()); - } else { - connectionPool = new LinkedBlockingDeque<>(); - } + this.connectionPoolSize = + connPoolSize != null + ? connPoolSize + : BigQueryJdbcUrlUtility.DEFAULT_CONNECTION_POOL_SIZE_VALUE; + this.maxCapacity = BigQueryPooledConnection.clampCapacity(this.connectionPoolSize); + this.connectionPool = new ArrayDeque<>(); } public Long getConnectionPoolSize() { @@ -44,107 +44,119 @@ public Long getConnectionPoolSize() { } public int getConnectionPoolCurrentCapacity() { - return this.connectionPool.size(); + synchronized (poolLock) { + return this.connectionPool.size(); + } } public boolean isConnectionPoolEmpty() { - return (connectionPool != null && connectionPool.isEmpty()); + synchronized (poolLock) { + return this.connectionPool.isEmpty(); + } } - PooledConnection getPooledConnection() { - if (isConnectionPoolEmpty()) { - LOG.warning("Connection pool is empty"); + BigQueryPooledConnection getPooledConnection() { + synchronized (poolLock) { + BigQueryPooledConnection candidate; + while ((candidate = connectionPool.pollFirst()) != null) { + if (!candidate.isAvailableForPool()) { + continue; + } + return candidate; + } + LOG.finer("Connection pool is empty"); return null; } - // Return the first element. - return connectionPool.getFirst(); } - void addConnection(PooledConnection connection) { - LOG.finest("++enter++"); - if (connection == null) { - LOG.warning("Connection passed in is null"); - return; + boolean addConnection(PooledConnection connection) { + LOG.finer("++enter++"); + try { + if (!(connection instanceof BigQueryPooledConnection)) { + LOG.warning("Connection passed in is null or unsupported"); + return false; + } + BigQueryPooledConnection bqConnection = (BigQueryPooledConnection) connection; + synchronized (poolLock) { + if (!bqConnection.isAvailableForPool()) { + return false; + } + if (connectionPool.contains(bqConnection)) { + LOG.finer("Connection already in the pool"); + return true; + } + if (connectionPool.size() >= maxCapacity) { + connectionPool.removeIf(entry -> !entry.isAvailableForPool()); + if (connectionPool.size() >= maxCapacity) { + return false; + } + } + // LIFO insertion keeps the most recently active idle connections warm. + connectionPool.addFirst(bqConnection); + return true; + } + } finally { + LOG.finer("++exit++"); } - if (connectionPool.contains(connection)) { - LOG.warning("Connection already in the pool"); - return; - } - connectionPool.add(connection); } void removeConnection(PooledConnection connection) { - LOG.finest("++enter++"); - if (connection == null) { - LOG.warning("Connection passed in is null"); - return; - } - if (!connectionPool.contains(connection)) { - LOG.warning("Connection already in the pool"); - return; + LOG.finer("++enter++"); + try { + if (connection == null) { + LOG.warning("Connection passed in is null"); + return; + } + synchronized (poolLock) { + if (!connectionPool.remove(connection)) { + LOG.finer("Connection not present in the pool"); + } + } + } finally { + LOG.finer("++exit++"); } - connectionPool.remove(connection); } @Override public void connectionClosed(ConnectionEvent event) { - LOG.finest("++enter++"); - Object eventSource = event.getSource(); - if (eventSource == null - || !(eventSource instanceof BigQueryPooledConnection) - || !(eventSource.getClass().isAssignableFrom(BigQueryPooledConnection.class))) { - IllegalArgumentException ex = - new IllegalArgumentException( - "Invalid ConnectionEvent source passed to connectionClosed. Expecting" - + " BigQueryPooledConnection."); - LOG.severe(ex.getMessage(), ex); - throw ex; + LOG.finer("++enter++"); + try { + BigQueryPooledConnection bqPooledConnection = extractPooledConnection(event); + if (addConnection(bqPooledConnection)) { + LOG.finer("Added pooled connection to connection pool"); + return; + } + bqPooledConnection.closeIfIdleAndSoleListener(this); + } finally { + LOG.finer("++exit++"); } - BigQueryPooledConnection bqPooledConnection = (BigQueryPooledConnection) eventSource; - addConnection(bqPooledConnection); - LOG.finest("Added pooled connection to connection pool"); } @Override public void connectionErrorOccurred(ConnectionEvent event) { - LOG.finest("++enter++"); - Object eventSource = event.getSource(); - if (eventSource == null - || !(eventSource instanceof BigQueryPooledConnection) - || !(eventSource.getClass().isAssignableFrom(BigQueryPooledConnection.class))) { + LOG.finer("++enter++"); + try { + BigQueryPooledConnection bqPooledConnection = extractPooledConnection(event); + removeConnection(bqPooledConnection); + String errorMessage = + (event.getSQLException() != null) + ? event.getSQLException().getMessage() + : "Connection error occurred"; + LOG.finer("Removed pooled connection from connection pool. Error: %s", errorMessage); + } finally { + LOG.finer("++exit++"); + } + } + + private static BigQueryPooledConnection extractPooledConnection(ConnectionEvent event) { + Object eventSource = event != null ? event.getSource() : null; + if (eventSource == null || eventSource.getClass() != BigQueryPooledConnection.class) { IllegalArgumentException ex = new IllegalArgumentException( - "Invalid ConnectionEvent source passed to connectionClosed. Expecting" - + " BigQueryPooledConnection."); + "Invalid ConnectionEvent source. Expecting BigQueryPooledConnection."); LOG.severe(ex.getMessage(), ex); throw ex; } - BigQueryPooledConnection bqPooledConnection = (BigQueryPooledConnection) eventSource; - removeConnection(bqPooledConnection); - String errorMessage = - (event.getSQLException() != null) - ? event.getSQLException().getMessage() - : "Connection error occured"; - LOG.finest("Removed pooled connection from connection pool. Error: %s", errorMessage); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - PooledConnectionListener other = (PooledConnectionListener) obj; - if (id == null) { - if (other.id != null) return false; - } else if (!id.equals(other.id)) return false; - return true; + return (BigQueryPooledConnection) eventSource; } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java index cea0b438e5a0..02c75013ef3a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryManager.java @@ -16,6 +16,7 @@ package com.google.cloud.bigquery.jdbc.telemetry.v1; +import com.google.api.gax.rpc.ApiException; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.JobStatistics.QueryStatistics; import com.google.cloud.bigquery.jdbc.BigQueryJdbcCustomLogger; @@ -283,6 +284,15 @@ public static int extractErrorCode(Throwable t) { return code; } } + if (t instanceof ApiException) { + ApiException apiEx = (ApiException) t; + if (apiEx.getStatusCode() != null && apiEx.getStatusCode().getCode() != null) { + int code = apiEx.getStatusCode().getCode().getHttpStatusCode(); + if (code != 0) { + return code; + } + } + } t = t.getCause(); } return 1000; diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java index fd82c6babb62..1fe40c127d60 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java @@ -25,10 +25,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -44,17 +49,28 @@ import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; +import com.google.cloud.RetryOption; import com.google.cloud.bigquery.BigQuery; +import com.google.cloud.bigquery.BigQueryError; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.DataFormatOptions; import com.google.cloud.bigquery.Job; import com.google.cloud.bigquery.JobInfo; +import com.google.cloud.bigquery.JobStatistics.QueryStatistics.StatementType; import com.google.cloud.bigquery.JobStatistics.SessionInfo; +import com.google.cloud.bigquery.JobStatus; import com.google.cloud.bigquery.Project; import com.google.cloud.bigquery.QueryJobConfiguration; import com.google.cloud.bigquery.QueryJobConfiguration.JobCreationMode; +import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.TableResult; import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; +import com.google.cloud.bigquery.jdbc.telemetry.v1.FeatureUsage; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPayload; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import com.google.cloud.bigquery.storage.v1.BigQueryReadClient; import com.google.cloud.bigquery.storage.v1.BigQueryReadSettings; import com.google.cloud.bigquery.storage.v1.BigQueryWriteClient; @@ -71,13 +87,33 @@ import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; +import java.util.Collections; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; @@ -96,7 +132,7 @@ public class BigQueryConnectionTest extends BigQueryJdbcLoggingBaseTest { private static final String DEFAULT_VERSION = "0.0.0"; private static final String DEFAULT_JDBC_TOKEN_VALUE = "Google-BigQuery-JDBC-Driver"; - private static final String TPC_UNIVERSE = "apis-tpczero.goog"; + private static final String CUSTOM_UNIVERSE = "example.com"; private static final String DEFAULT_UNIVERSE = "googleapis.com"; private static final String BASE_URL = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" @@ -564,7 +600,9 @@ public void testConnectionPropertiesLoggingAndMasking() throws IOException, SQLE String url = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + "OAuthType=2;ProjectId=MyTestProjectId;" - + "OAuthAccessToken=secretAccessToken;Location=US;"; + + "OAuthAccessToken=secretAccessToken;" + + "ProxyHost=proxy.example.com;ProxyPort=8080;ProxyUid=secretProxyUid;ProxyPwd=secretProxyPwd;" + + "Location=US;"; try (BigQueryConnection connection = new BigQueryConnection(url)) { // Just trigger the constructor } @@ -580,7 +618,16 @@ public void testConnectionPropertiesLoggingAndMasking() throws IOException, SQLE assertTrue(logMessage.contains("ProjectId=MyTestProjectId")); assertTrue(logMessage.contains("Location=US")); assertTrue(logMessage.contains("OAuthAccessToken=*****")); + assertTrue(logMessage.contains("ProxyUid=*****")); + assertTrue(logMessage.contains("ProxyPwd=*****")); assertFalse(logMessage.contains("secretAccessToken")); + assertFalse(logMessage.contains("secretProxyUid")); + assertFalse(logMessage.contains("secretProxyPwd")); + assertEquals( + "*****", + BigQueryConnection.maskPropertyValue( + BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, + "{\"headers\":{\"Authorization\":\"Bearer secretByoid\"}}")); } finally { rootLogger.setLevel(originalLevel); } @@ -656,7 +703,7 @@ public void testOpenTelemetryPrecedenceHierarchy( .when( () -> BigQueryJdbcOpenTelemetry.createLoggingClient( - anyBoolean(), any(), any(), any(), any(), any())) + anyBoolean(), any(), any(), any(), any(), any(), any())) .thenReturn(mockLogging); // Stub getOpenTelemetry to return the expected mock based on inputs @@ -974,28 +1021,29 @@ public void testDuplicateSessionIdKeysAreRejected() { } @Test - public void testReadAndWriteClientsScopeServiceAccountCredentialsForTpc() throws Exception { + public void testReadAndWriteClientsScopeServiceAccountCredentialsForCustomUniverse() + throws Exception { String url = getUriOAuthServiceAccount() .append("ProjectId", "project") - .append("universeDomain", TPC_UNIVERSE) + .append("universeDomain", CUSTOM_UNIVERSE) .toString(); try (BigQueryConnection connection = new BigQueryConnection(url)) { BigQueryReadClient readClient = connection.getBigQueryReadClient(); - assertEquals(TPC_UNIVERSE, readClient.getSettings().getUniverseDomain()); + assertEquals(CUSTOM_UNIVERSE, readClient.getSettings().getUniverseDomain()); assertStorageCredentialsScoped( readClient.getSettings().getCredentialsProvider().getCredentials(), - TPC_UNIVERSE, - storageUri(TPC_UNIVERSE, "BigQueryRead"), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryRead"), BigQueryReadSettings.getDefaultServiceScopes()); BigQueryWriteClient writeClient = connection.getBigQueryWriteClient(); - assertEquals(TPC_UNIVERSE, writeClient.getSettings().getUniverseDomain()); + assertEquals(CUSTOM_UNIVERSE, writeClient.getSettings().getUniverseDomain()); assertStorageCredentialsScoped( writeClient.getSettings().getCredentialsProvider().getCredentials(), - TPC_UNIVERSE, - storageUri(TPC_UNIVERSE, "BigQueryWrite"), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryWrite"), BigQueryWriteSettings.getDefaultServiceScopes()); } } @@ -1064,7 +1112,7 @@ public void testScopeStorageCredentialsPreservesExplicitScopes() throws Exceptio ServiceAccountCredentials.newBuilder() .setClientEmail("service@account") .setPrivateKeyString(fake_pkcs8_key) - .setUniverseDomain(TPC_UNIVERSE) + .setUniverseDomain(CUSTOM_UNIVERSE) .build() .createScoped(explicitScopes); @@ -1073,7 +1121,167 @@ public void testScopeStorageCredentialsPreservesExplicitScopes() throws Exceptio alreadyScoped, BigQueryReadSettings.getDefaultServiceScopes()); assertStorageCredentialsScoped( - result, TPC_UNIVERSE, storageUri(TPC_UNIVERSE, "BigQueryRead"), explicitScopes); + result, CUSTOM_UNIVERSE, storageUri(CUSTOM_UNIVERSE, "BigQueryRead"), explicitScopes); + } + + @Test + public void testCustomUniverseDomainServiceAccountJsonKeyNotOverwrittenWhenUniverseDomainOmitted() + throws Exception { + JsonObject saJson = new JsonObject(); + saJson.addProperty("type", "service_account"); + saJson.addProperty("project_id", "custom-universe-project"); + saJson.addProperty("private_key_id", "key-id-1"); + saJson.addProperty("private_key", fake_pkcs8_key); + saJson.addProperty("client_email", "sa@custom-universe-project.iam.gserviceaccount.com"); + saJson.addProperty("client_id", "123456"); + saJson.addProperty("universe_domain", CUSTOM_UNIVERSE); + + String url = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=custom-universe-project;OAuthType=0;EnableDiagnosticTelemetry=0;" + + "OAuthServiceAcctEmail=sa@custom-universe-project.iam.gserviceaccount.com;OAuthPvtKey=" + + saJson; + + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(null); + try (BigQueryConnection connection = new BigQueryConnection(url)) { + assertNull(connection.universeDomain); + assertFalse( + connection.overrideProperties.containsKey( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); + assertEquals(CUSTOM_UNIVERSE, connection.credentials.getUniverseDomain()); + // Client-side universe validation must fail-closed before any network RPC is sent to GDU. + BigQueryException ex = + assertThrows( + BigQueryException.class, + () -> + connection + .getBigQuery() + .query(QueryJobConfiguration.newBuilder("SELECT 1").build())); + assertTrue(ex.getMessage().contains("does not match the universe domain")); + } + + // Explicit universeDomain in URL must also NOT overwrite the JSON key's universe_domain. + try (BigQueryConnection explicitMismatchConn = + new BigQueryConnection(url + ";universeDomain=other-universe.example.com")) { + assertEquals("other-universe.example.com", explicitMismatchConn.universeDomain); + assertEquals(CUSTOM_UNIVERSE, explicitMismatchConn.credentials.getUniverseDomain()); + BigQueryException ex = + assertThrows( + BigQueryException.class, + () -> + explicitMismatchConn + .getBigQuery() + .query(QueryJobConfiguration.newBuilder("SELECT 1").build())); + assertTrue(ex.getMessage().contains("does not match the universe domain")); + } + } + } + + @Test + public void testConnectionHonorsEnvUniverseDomainWithoutOverwritingJsonCredentials() + throws Exception { + JsonObject gduSaJson = new JsonObject(); + gduSaJson.addProperty("type", "service_account"); + gduSaJson.addProperty("project_id", "gdu-project"); + gduSaJson.addProperty("private_key_id", "key-id-2"); + gduSaJson.addProperty("private_key", fake_pkcs8_key); + gduSaJson.addProperty("client_email", "sa@gdu-project.iam.gserviceaccount.com"); + gduSaJson.addProperty("client_id", "654321"); + + String url = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=gdu-project;OAuthType=0;EnableDiagnosticTelemetry=0;" + + "OAuthServiceAcctEmail=sa@gdu-project.iam.gserviceaccount.com;OAuthPvtKey=" + + gduSaJson; + + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(CUSTOM_UNIVERSE); + try (BigQueryConnection connection = new BigQueryConnection(url)) { + // Clients honor GOOGLE_CLOUD_UNIVERSE_DOMAIN, while GDU JSON credential stays + // googleapis.com + assertEquals(CUSTOM_UNIVERSE, connection.universeDomain); + assertEquals(CUSTOM_UNIVERSE, connection.getBigQuery().getOptions().getUniverseDomain()); + assertEquals( + CUSTOM_UNIVERSE, connection.getBigQueryReadClient().getSettings().getUniverseDomain()); + assertEquals( + CUSTOM_UNIVERSE, connection.getBigQueryWriteClient().getSettings().getUniverseDomain()); + assertFalse( + connection.overrideProperties.containsKey( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); + assertEquals(DEFAULT_UNIVERSE, connection.credentials.getUniverseDomain()); + } + } + + // Blank/whitespace GOOGLE_CLOUD_UNIVERSE_DOMAIN resolves to googleapis.com so GAX clients + // do not re-read the raw empty env var and construct an invalid host. + try (MockedStatic blankEnvUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + blankEnvUtil.when(BigQueryJdbcUrlUtility::readRawEnvUniverseDomain).thenReturn(""); + try (BigQueryConnection blankEnvConn = new BigQueryConnection(url)) { + assertEquals(DEFAULT_UNIVERSE, blankEnvConn.universeDomain); + assertEquals(DEFAULT_UNIVERSE, blankEnvConn.getBigQuery().getOptions().getUniverseDomain()); + assertEquals( + DEFAULT_UNIVERSE, + blankEnvConn.getBigQueryReadClient().getSettings().getUniverseDomain()); + assertEquals( + DEFAULT_UNIVERSE, + blankEnvConn.getBigQueryWriteClient().getSettings().getUniverseDomain()); + assertFalse( + blankEnvConn.overrideProperties.containsKey( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)); + } + } + } + + @Test + public void + testConnectionCustomUniverseDomainJsonKeyMatchesEnvUniverseDomainAcrossAllThreeClients() + throws Exception { + JsonObject customSaJson = new JsonObject(); + customSaJson.addProperty("type", "service_account"); + customSaJson.addProperty("project_id", "custom-universe-project"); + customSaJson.addProperty("private_key_id", "key-id-3"); + customSaJson.addProperty("private_key", fake_pkcs8_key); + customSaJson.addProperty("client_email", "sa@custom-universe-project.iam.gserviceaccount.com"); + customSaJson.addProperty("client_id", "999999"); + customSaJson.addProperty("universe_domain", CUSTOM_UNIVERSE); + + String url = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=custom-universe-project;OAuthType=0;EnableDiagnosticTelemetry=0;" + + "OAuthServiceAcctEmail=sa@custom-universe-project.iam.gserviceaccount.com;OAuthPvtKey=" + + customSaJson; + + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(CUSTOM_UNIVERSE); + try (BigQueryConnection connection = new BigQueryConnection(url)) { + assertEquals(CUSTOM_UNIVERSE, connection.universeDomain); + assertEquals(CUSTOM_UNIVERSE, connection.credentials.getUniverseDomain()); + assertTrue(connection.getBigQuery().getOptions().hasValidUniverseDomain()); + assertStorageCredentialsScoped( + connection + .getBigQueryReadClient() + .getSettings() + .getCredentialsProvider() + .getCredentials(), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryRead"), + BigQueryReadSettings.getDefaultServiceScopes()); + assertStorageCredentialsScoped( + connection + .getBigQueryWriteClient() + .getSettings() + .getCredentialsProvider() + .getCredentials(), + CUSTOM_UNIVERSE, + storageUri(CUSTOM_UNIVERSE, "BigQueryWrite"), + BigQueryWriteSettings.getDefaultServiceScopes()); + } + } } private static URI storageUri(String universeDomain, String service) { @@ -1118,4 +1326,765 @@ private static JsonObject extractBearerJwtPayload(Credentials credentials, URI u new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); return JsonParser.parseString(payloadJson).getAsJsonObject(); } + + // --- Usage-telemetry attribution: driver-internal calls must not count as user activity --- + + @Test + public void testGetMetaData_concurrentFirstCallsShareOneInstance() throws Exception { + // getMetaDataInternal() lazily creates the DatabaseMetaData; concurrent first calls must + // observe a single instance and record DRIVER_FEATURE_METADATA_RETRIEVAL exactly once across + // all worker threads. + List captured = Collections.synchronizedList(new ArrayList<>()); + TelemetryTestUtils.initCapturingPayloads(captured); + int threads = 8; + ExecutorService pool = Executors.newFixedThreadPool(threads); + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL)) { + CountDownLatch start = new CountDownLatch(1); + List> results = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + results.add( + pool.submit( + () -> { + start.await(); + return connection.getMetaData(); + })); + } + start.countDown(); + Set distinct = Collections.newSetFromMap(new IdentityHashMap<>()); + for (Future f : results) { + distinct.add(f.get(10, TimeUnit.SECONDS)); + } + assertEquals(1, distinct.size()); + TelemetryTestUtils.flush(); + long metadataFeatureCount = + captured.stream() + .flatMap(p -> p.getFeatureUsagesList().stream()) + .filter(e -> e.getDriverFeature() == DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL) + .mapToLong(FeatureUsage::getCount) + .sum(); + assertEquals(1L, metadataFeatureCount); + } finally { + pool.shutdownNow(); + TelemetryTestUtils.reset(); + } + } + + @Test + public void testGetMetaData_closedConnection_throwsAndRecordsNothing() throws SQLException { + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL); + MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + connection.close(); + assertThrows(BigQueryJdbcException.class, connection::getMetaData); + telemetry.verifyNoInteractions(); + } + } + + @Test + public void testGetMetaData_recordsOncePerConnection() throws SQLException { + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL); + MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + connection.getMetaData(); + connection.getMetaData(); + telemetry.verify( + () -> + TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL), + times(1)); + } + } + + @Test + public void testGetMetaDataInternal_recordsNothingAndDoesNotConsumeUserRecord() + throws SQLException { + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL); + MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + connection.getMetaDataInternal(); + telemetry.verifyNoInteractions(); + // The first *user* call still records, even though the instance already exists. + connection.getMetaData(); + telemetry.verify( + () -> + TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL), + times(1)); + } + } + + @Test + public void testCreateStatementInternal_recordsNoFeatureUsage() throws SQLException { + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL); + MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + BigQueryStatement statement = connection.createStatementInternal(); + assertFalse(statement.isRecordingTelemetry()); + telemetry.verifyNoInteractions(); + } + } + + @Test + public void testPrepareStatementInternal_recordsNoFeatureUsageIncludingBindings() + throws SQLException { + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL); + MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + BigQueryPreparedStatement statement = connection.prepareStatementInternal("SELECT ?"); + statement.setString(1, "x"); + assertFalse(statement.isRecordingTelemetry()); + telemetry.verifyNoInteractions(); + } + } + + @Test + public void testIsValid_healthCheckRecordsNoTelemetry() throws Exception { + // Regression guard: isValid() runs "SELECT 1" on an internal statement. Pools call it on + // every checkout, so counting it as a user statement or SELECT would swamp real usage. + try (BigQueryConnection connection = new BigQueryConnection(BASE_URL)) { + BigQuery mockBigQuery = mock(BigQuery.class); + connection.bigQuery = mockBigQuery; + TableResult tableResult = mock(TableResult.class); + when(tableResult.getSchema()).thenReturn(Schema.of()); + when(tableResult.getStatementType()).thenReturn(StatementType.SELECT); + when(mockBigQuery.queryWithTimeout(any(QueryJobConfiguration.class), any(), any())) + .thenReturn(tableResult); + + // CALLS_REAL_METHODS keeps TelemetryManager's pure helpers working; the record* calls + // are no-ops without an initialized instance but are still counted by verify. + try (MockedStatic telemetry = + mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { + connection.isValid(1); + telemetry.verify(() -> TelemetryManager.recordFeatureUsage(any()), never()); + telemetry.verify(() -> TelemetryManager.recordFeatureUsage(any(), any()), never()); + telemetry.verify( + () -> TelemetryManager.recordStatementExecution(any(), anyLong()), never()); + } + } + } + + private static URIBuilder sessionEnabledUri() { + return getUriOAuthToken().append("ProjectId", "test-project").append("EnableSession", 1); + } + + @Test + public void testResetForReuse_rollsBackActiveTransactionWithoutStartingNewOne() throws Exception { + try (BigQueryConnection conn = new BigQueryConnection(sessionEnabledUri().toString())) { + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("driver_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + conn.setAutoCommit(false); + assertTrue(conn.isTransactionStarted()); + assertFalse(conn.getAutoCommit()); + + conn.resetForReuse(); + + assertFalse(conn.isTransactionStarted()); + assertTrue(conn.getAutoCommit()); + assertNull(conn.getSessionInfoConnectionProperty()); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(JobInfo.class); + verify(mockBigQuery, times(1)).create(jobCaptor.capture()); + QueryJobConfiguration rollbackConfig = jobCaptor.getValue().getConfiguration(); + assertEquals("ROLLBACK TRANSACTION;", rollbackConfig.getQuery()); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, atLeastOnce()).query(queryCaptor.capture()); + List executedQueries = queryCaptor.getAllValues(); + long beginCount = + executedQueries.stream() + .filter(cfg -> "BEGIN TRANSACTION;".equals(cfg.getQuery())) + .count(); + assertEquals(1L, beginCount, "Reset must not start a follow-up transaction after rollback"); + assertTrue( + executedQueries.stream() + .anyMatch(cfg -> "CALL BQ.ABORT_SESSION();".equals(cfg.getQuery()))); + assertFalse( + executedQueries.stream().anyMatch(cfg -> "COMMIT TRANSACTION;".equals(cfg.getQuery()))); + } + } + + @Test + public void testResetForReuse_abortsDriverCreatedSessionAndPreservesQueryProperties() + throws Exception { + String url = + sessionEnabledUri().append("QueryProperties", "time_zone=America/Los_Angeles").toString(); + try (BigQueryConnection conn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenReturn(mock(TableResult.class)); + + conn.markSessionCreatedByDriver(); + conn.initSessionInfo("driver_query_session_1"); + assertEquals("driver_query_session_1", conn.getSessionInfoConnectionProperty().getValue()); + assertTrue(conn.isSessionCreatedByDriver()); + + conn.resetForReuse(); + + assertNull(conn.getSessionInfoConnectionProperty()); + assertFalse(conn.isSessionCreatedByDriver()); + assertTrue( + conn.getQueryProperties().stream() + .anyMatch( + cp -> + "time_zone".equals(cp.getKey()) + && "America/Los_Angeles".equals(cp.getValue()))); + assertFalse( + conn.getQueryProperties().stream() + .anyMatch(cp -> "session_id".equalsIgnoreCase(cp.getKey()))); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery).query(queryCaptor.capture()); + assertEquals("CALL BQ.ABORT_SESSION();", queryCaptor.getValue().getQuery()); + } + } + + @Test + public void testResetForReuse_preservesUserConfiguredSessionIdWhileRollingBackTransaction() + throws Exception { + String url = + sessionEnabledUri().append("QueryProperties", "session_id=caller_owned_77").toString(); + try (BigQueryConnection conn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("caller_owned_77"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + conn.setAutoCommit(false); + conn.resetForReuse(); + + assertFalse(conn.isTransactionStarted()); + assertTrue(conn.getAutoCommit()); + assertFalse(conn.isSessionCreatedByDriver()); + assertNotNull(conn.getSessionInfoConnectionProperty()); + assertEquals("caller_owned_77", conn.getSessionInfoConnectionProperty().getValue()); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, atLeastOnce()).query(queryCaptor.capture()); + assertFalse( + queryCaptor.getAllValues().stream() + .anyMatch(cfg -> "CALL BQ.ABORT_SESSION();".equals(cfg.getQuery()))); + } + } + + @Test + public void testResetForReuse_resetsClientInfoWarningsHoldabilityAndClosesOpenStatements() + throws Exception { + String url = getUriOAuthToken().append("ProjectId", "test-project").toString(); + BigQueryConnection closedConn; + try (BigQueryConnection conn = new BigQueryConnection(url)) { + closedConn = conn; + assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability()); + Statement stmt = conn.createStatement(); + PreparedStatement pstmt = conn.prepareStatement("SELECT 1"); + + conn.setClientInfo("ApplicationName", "BillingReport"); + conn.sqlWarnings.add(new SQLWarning("sample warning")); + conn.holdability = ResultSet.HOLD_CURSORS_OVER_COMMIT; + assertEquals(2, conn.openStatements.size()); + + conn.resetForReuse(); + + assertTrue(stmt.isClosed()); + assertTrue(pstmt.isClosed()); + assertTrue(conn.openStatements.isEmpty()); + assertTrue(conn.getClientInfo().isEmpty()); + assertNull(conn.getWarnings()); + assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn.getHoldability()); + } + assertThrows(BigQueryJdbcException.class, closedConn::resetForReuse); + } + + @Test + public void testResetForReuse_abortsDriverSessionEvenWhenCallingThreadIsInterrupted() + throws Exception { + try (BigQueryConnection conn = new BigQueryConnection(sessionEnabledUri().toString())) { + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + // Simulate real BigQueryImpl / AbstractFuture.get(), which throws immediately if the calling + // thread enters the RPC with its interrupt flag still set. + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenAnswer( + invocation -> { + if (Thread.interrupted()) { + throw new BigQueryException(0, "interrupted before RPC"); + } + return mock(TableResult.class); + }); + + conn.markSessionCreatedByDriver(); + conn.initSessionInfo("interrupted_caller_session"); + + Thread.currentThread().interrupt(); + try { + conn.resetForReuse(); + assertTrue(Thread.currentThread().isInterrupted()); + assertNull(conn.getSessionInfoConnectionProperty()); + assertFalse(conn.isSessionCreatedByDriver()); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery).query(queryCaptor.capture()); + assertEquals("CALL BQ.ABORT_SESSION();", queryCaptor.getValue().getQuery()); + } finally { + Thread.interrupted(); + } + } + } + + @Test + public void testResetForReuse_preservesSessionAndTransactionForPhysicalCloseWhenInterrupted() + throws Exception { + BigQueryConnection conn = new BigQueryConnection(sessionEnabledUri().toString()); + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("driver_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenAnswer( + invocation -> { + QueryJobConfiguration cfg = invocation.getArgument(0); + if ("BEGIN TRANSACTION;".equals(cfg.getQuery())) { + return beginResult; + } + throw new InterruptedException("interrupted session abort"); + }); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenThrow(new InterruptedException("interrupted rollback")); + + conn.setAutoCommit(false); + Statement failingStmt = mock(Statement.class); + SQLException stmtCloseEx = new SQLException("statement close failed"); + doThrow(stmtCloseEx).when(failingStmt).close(); + conn.openStatements.add(failingStmt); + + try { + SQLException thrown = assertThrows(SQLException.class, conn::resetForReuse); + assertSame(stmtCloseEx, thrown); + assertEquals(2, thrown.getSuppressed().length); + assertTrue(Thread.currentThread().isInterrupted()); + assertTrue(conn.isTransactionStarted()); + assertNotNull(conn.getSessionInfoConnectionProperty()); + assertEquals("driver_tx_session", conn.getSessionInfoConnectionProperty().getValue()); + } finally { + Thread.interrupted(); + } + + // Subsequent physical close must still see the active transaction and session and clean up. + doReturn(rollbackJob).when(rollbackJob).waitFor(); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(mock(TableResult.class)); + conn.close(); + + assertFalse(conn.isTransactionStarted()); + assertNull(conn.getSessionInfoConnectionProperty()); + verify(mockBigQuery, times(2)).create(any(JobInfo.class)); + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, times(3)).query(queryCaptor.capture()); + long abortCount = + queryCaptor.getAllValues().stream() + .filter(cfg -> "CALL BQ.ABORT_SESSION();".equals(cfg.getQuery())) + .count(); + assertEquals(2L, abortCount); + } + + @Test + public void testClose_rollsBackActiveTransactionWithoutStartingFollowUpTransaction() + throws Exception { + String url = + sessionEnabledUri().append("QueryProperties", "session_id=caller_owned_close").toString(); + BigQueryConnection conn = new BigQueryConnection(url); + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("caller_owned_close"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + conn.setAutoCommit(false); + conn.close(); + + verify(mockBigQuery, times(1)).create(any(JobInfo.class)); + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, times(1)).query(queryCaptor.capture()); + assertEquals("BEGIN TRANSACTION;", queryCaptor.getValue().getQuery()); + } + + @Test + public void + testAbort_marksClosedSynchronouslyAndExecutesTeardownViaExecutorWithConfiguredTimeout() + throws Exception { + String url = sessionEnabledUri().append("Timeout", 15).toString(); + BigQueryConnection conn = new BigQueryConnection(url); + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("abort_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor(any(RetryOption.class))).thenReturn(rollbackJob); + + conn.setAutoCommit(false); + Statement openStmt = conn.createStatement(); + Connection logicalProxy = mock(Connection.class); + Statement stmtProxy = mock(Statement.class); + assertSame(conn, openStmt.getConnection()); + assertNull(((BigQueryStatement) openStmt).getLogicalStatementProxy()); + ((BigQueryStatement) openStmt).attachPooledProxies(logicalProxy, stmtProxy); + assertSame(logicalProxy, openStmt.getConnection()); + assertSame(stmtProxy, ((BigQueryStatement) openStmt).getLogicalStatementProxy()); + + assertThrows(BigQueryJdbcException.class, () -> conn.abort(null)); + assertFalse(conn.isClosed()); + + // A rejecting Executor must roll back closeInitiated/isClosed so fallback close() can clean up. + assertThrows( + RejectedExecutionException.class, + () -> + conn.abort( + task -> { + throw new RejectedExecutionException("executor shut down"); + })); + assertFalse(conn.isClosed()); + + List scheduledTasks = new ArrayList<>(); + conn.abort(scheduledTasks::add); + + assertTrue(conn.isClosed()); + assertEquals(1, scheduledTasks.size()); + assertFalse(openStmt.isClosed(), "Resource teardown must be deferred to the executor"); + + // Second abort or close is a no-op once abort has claimed teardown. + conn.abort(scheduledTasks::add); + conn.close(); + assertEquals(1, scheduledTasks.size()); + + scheduledTasks.get(0).run(); + assertTrue(openStmt.isClosed()); + assertNull(openStmt.getConnection()); + verify(rollbackJob).waitFor(RetryOption.totalTimeoutDuration(Duration.ofSeconds(15))); + } + + @Test + public void testCommitAndRollback_surfaceTimedOutFailedAndExceptionTransactionJobs() + throws Exception { + String url = + sessionEnabledUri() + .append("Timeout", 10) + .append("QueryProperties", "session_id=tx_status_session") + .toString(); + try (BigQueryConnection conn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("tx_status_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + conn.setAutoCommit(false); + + // 1. Timed-out commit wait (JobStatus.State.RUNNING) throws and keeps transactionStarted. + Job runningCommitJob = mock(Job.class); + JobStatus runningStatus = mock(JobStatus.class); + when(runningStatus.getState()).thenReturn(JobStatus.State.RUNNING); + when(runningCommitJob.getStatus()).thenReturn(runningStatus); + when(runningCommitJob.waitFor(any(RetryOption.class))).thenReturn(runningCommitJob); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(runningCommitJob); + + assertThrows(BigQueryJdbcException.class, conn::commit); + assertTrue(conn.isTransactionStarted()); + verify(runningCommitJob).waitFor(RetryOption.totalTimeoutDuration(Duration.ofSeconds(10))); + + // 2. BigQueryException during commit is wrapped in BigQueryJdbcException. + when(mockBigQuery.create(any(JobInfo.class))) + .thenThrow(new BigQueryException(503, "commit unavailable")); + assertThrows(BigQueryJdbcException.class, conn::commit); + assertTrue(conn.isTransactionStarted()); + + // 3. Rollback job completing with a JobStatus error throws and keeps transactionStarted. + Job erroredRollbackJob = mock(Job.class); + JobStatus erroredStatus = mock(JobStatus.class); + when(erroredStatus.getState()).thenReturn(JobStatus.State.DONE); + when(erroredStatus.getError()) + .thenReturn(new BigQueryError("backendError", "server", "rollback failed")); + when(erroredRollbackJob.getStatus()).thenReturn(erroredStatus); + when(erroredRollbackJob.waitFor(any(RetryOption.class))).thenReturn(erroredRollbackJob); + doReturn(erroredRollbackJob).when(mockBigQuery).create(any(JobInfo.class)); + + assertThrows(BigQueryJdbcException.class, conn::resetForReuse); + assertTrue(conn.isTransactionStarted()); + + // Allow try-with-resources close() to succeed cleanly. + Job okRollbackJob = mock(Job.class); + when(okRollbackJob.waitFor(any(RetryOption.class))).thenReturn(okRollbackJob); + doReturn(okRollbackJob).when(mockBigQuery).create(any(JobInfo.class)); + } + } + + @Test + public void testConcurrentCloseDuringRejectingAbort_waitsForRollbackAndClosesConnection() + throws Exception { + String url = getUriOAuthToken().append("ProjectId", "test-project").toString(); + BigQueryConnection conn = new BigQueryConnection(url); + Statement openStmt = conn.createStatement(); + + CountDownLatch enteredExecute = new CountDownLatch(1); + CountDownLatch releaseRejection = new CountDownLatch(1); + AtomicBoolean isClosedDuringRejectingExecute = new AtomicBoolean(true); + AtomicReference closeThread = new AtomicReference<>(); + CountDownLatch closeStarted = new CountDownLatch(1); + + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future abortFuture = + workers.submit( + () -> { + assertThrows( + RejectedExecutionException.class, + () -> + conn.abort( + task -> { + isClosedDuringRejectingExecute.set(conn.isClosed()); + enteredExecute.countDown(); + try { + assertTrue(releaseRejection.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + throw new RejectedExecutionException("executor rejected"); + })); + return null; + }); + assertTrue(enteredExecute.await(5, TimeUnit.SECONDS)); + assertFalse( + isClosedDuringRejectingExecute.get(), + "isClosed() must remain false until executor accepts the abort task"); + + Future closeFuture = + workers.submit( + () -> { + closeThread.set(Thread.currentThread()); + closeStarted.countDown(); + conn.close(); + return null; + }); + assertTrue(closeStarted.await(5, TimeUnit.SECONDS)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (closeThread.get().getState() != Thread.State.BLOCKED && System.nanoTime() < deadline) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1)); + } + assertEquals(Thread.State.BLOCKED, closeThread.get().getState()); + + releaseRejection.countDown(); + abortFuture.get(5, TimeUnit.SECONDS); + closeFuture.get(5, TimeUnit.SECONDS); + + assertTrue(conn.isClosed()); + assertTrue(openStmt.isClosed()); + } finally { + workers.shutdownNow(); + } + + BigQueryConnection abortMdcConn = + new BigQueryConnection(getUriOAuthToken().append("ProjectId", "test-project").toString()); + try (BigQueryJdbcMdc.MdcCloseable outerMdc = + BigQueryJdbcMdc.registerInstance("outer-caller-conn")) { + abortMdcConn.abort(Runnable::run); + assertTrue(abortMdcConn.isClosed()); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + } + } + + @Test + public void testResetForReuse_surfacesBigQueryExceptionFromAbortSessionAndPreservesStateForClose() + throws Exception { + BigQueryConnection conn = new BigQueryConnection(sessionEnabledUri().toString()); + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenThrow(new BigQueryException(503, "session abort unavailable")); + + conn.markSessionCreatedByDriver(); + conn.initSessionInfo("driver_session_503"); + + BigQueryJdbcException resetEx = assertThrows(BigQueryJdbcException.class, conn::resetForReuse); + assertTrue(resetEx.getCause() instanceof BigQueryException); + assertNotNull(conn.getSessionInfoConnectionProperty()); + assertEquals("driver_session_503", conn.getSessionInfoConnectionProperty().getValue()); + assertTrue(conn.isSessionCreatedByDriver()); + + // Physical close retries session abort with throwOnError=false, logs warning, and clears state. + try (BigQueryJdbcMdc.MdcCloseable outerMdc = + BigQueryJdbcMdc.registerInstance("outer-caller-conn")) { + conn.close(); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + } + assertTrue(conn.isClosed()); + assertNull(conn.getSessionInfoConnectionProperty()); + verify(mockBigQuery, times(2)).query(any(QueryJobConfiguration.class)); + } + + @Test + public void testAsyncAbortSerializesCloseImplBehindInFlightResetForReuse() throws Exception { + BigQueryConnection conn = new BigQueryConnection(sessionEnabledUri().toString()); + BigQuery mockBigQuery = mock(BigQuery.class); + conn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("serialized_reset_abort_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + + CountDownLatch enteredAbortSessionRpc = new CountDownLatch(1); + CountDownLatch releaseAbortSessionRpc = new CountDownLatch(1); + AtomicBoolean resetStillInFlight = new AtomicBoolean(false); + AtomicBoolean closeOverlappedReset = new AtomicBoolean(false); + + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenAnswer( + invocation -> { + QueryJobConfiguration cfg = invocation.getArgument(0); + if ("BEGIN TRANSACTION;".equals(cfg.getQuery())) { + return beginResult; + } + resetStillInFlight.set(true); + enteredAbortSessionRpc.countDown(); + try { + assertTrue(releaseAbortSessionRpc.await(5, TimeUnit.SECONDS)); + } finally { + resetStillInFlight.set(false); + } + return mock(TableResult.class); + }); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + conn.setAutoCommit(false); + Statement checkOverlapStmt = mock(Statement.class); + when(checkOverlapStmt.isClosed()).thenReturn(false); + + ExecutorService resetExecutor = Executors.newSingleThreadExecutor(); + ExecutorService abortExecutor = Executors.newSingleThreadExecutor(); + try { + Future resetFuture = + resetExecutor.submit( + () -> { + conn.resetForReuse(); + return null; + }); + assertTrue(enteredAbortSessionRpc.await(5, TimeUnit.SECONDS)); + + // Add a sentinel statement while reset is paused inside ABORT_SESSION; closeImpl() closes + // openStatements, so if closeImpl() ran concurrently before reset exited lifecycleLock, + // resetStillInFlight would be true when checkOverlapStmt.close() is invoked. + doAnswer( + inv -> { + if (resetStillInFlight.get()) { + closeOverlappedReset.set(true); + } + return null; + }) + .when(checkOverlapStmt) + .close(); + conn.openStatements.add(checkOverlapStmt); + + conn.abort(abortExecutor); + assertTrue(conn.isClosed(), "abort(Executor) must return non-blockingly with isClosed=true"); + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(15)); + verify(checkOverlapStmt, never()).close(); + + releaseAbortSessionRpc.countDown(); + resetFuture.get(5, TimeUnit.SECONDS); + + abortExecutor.shutdown(); + assertTrue(abortExecutor.awaitTermination(5, TimeUnit.SECONDS)); + + assertFalse(closeOverlappedReset.get(), "closeImpl() must serialize behind resetForReuse()"); + verify(checkOverlapStmt, times(1)).close(); + verify(mockBigQuery, times(1)).create(any(JobInfo.class)); + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, times(2)).query(queryCaptor.capture()); + } finally { + resetExecutor.shutdownNow(); + abortExecutor.shutdownNow(); + } + } + + @Test + public void testConcurrentGetWarningsAndReset_neverThrowsIndexOutOfBounds() throws Exception { + String url = getUriOAuthToken().append("ProjectId", "test-project").toString(); + try (BigQueryConnection conn = new BigQueryConnection(url)) { + SQLWarning warning = new SQLWarning("sample warning"); + CountDownLatch startGate = new CountDownLatch(1); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future mutator = + workers.submit( + () -> { + assertTrue(startGate.await(5, TimeUnit.SECONDS)); + for (int i = 0; i < 1000; i++) { + conn.sqlWarnings.add(warning); + conn.resetForReuse(); + } + return null; + }); + Future reader = + workers.submit( + () -> { + assertTrue(startGate.await(5, TimeUnit.SECONDS)); + for (int i = 0; i < 1000; i++) { + SQLWarning observed = conn.getWarnings(); + if (observed != null) { + assertSame(warning, observed); + } + } + return null; + }); + startGate.countDown(); + mutator.get(5, TimeUnit.SECONDS); + reader.get(5, TimeUnit.SECONDS); + conn.resetForReuse(); + assertNull(conn.getWarnings()); + } finally { + workers.shutdownNow(); + } + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaDataTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaDataTest.java index 466790658ad1..875dab294a2d 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaDataTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaDataTest.java @@ -45,7 +45,6 @@ import java.io.IOException; import java.io.InputStream; import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -3534,18 +3533,56 @@ public void testGetImportedKeys_noKeys() throws SQLException { } } + @Test + public void testGraphMetadataQueries_useInternalPreparedStatements() throws SQLException { + // The PROPERTY_GRAPHS lookups behind getTables, getColumns and getPrimaryKeys are + // driver-internal and must not be reported as user PREPARED_STATEMENT / PARAMETER_BINDING / + // SELECT telemetry: they must go through prepareStatementInternal, never prepareStatement. + when(bigQueryConnection.isEnableGraphMetadata()).thenReturn(true); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); + ResultSet emptyRs = mock(ResultSet.class); + when(emptyRs.next()).thenReturn(false); + when(mockStmt.executeQuery()).thenReturn(emptyRs); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); + + List rows = new ArrayList<>(); + dbMetadata.appendGraphTableRows( + "test-project", + "dataset_p", + "Graph.%", + Collections.singleton("GRAPH TABLE"), + rows, + dbMetadata.defineGetTablesSchema().getFields()); + dbMetadata.appendGraphColumnRows( + "test-project", + "dataset_p", + "Graph.Node", + "%", + rows, + dbMetadata.defineGetColumnsSchema().getFields()); + try (ResultSet rs = dbMetadata.getPrimaryKeys("test-project", "dataset_p", "Graph.Node")) { + assertFalse(rs.next()); + } + + verify(bigQueryConnection, times(3)).prepareStatementInternal(anyString(), eq(true)); + verify(bigQueryConnection, never()).prepareStatement(anyString()); + verify(bigQueryConnection, never()).prepareStatement(anyString(), anyBoolean()); + } + private void assertExportedKeysPreparedQuery(String catalog, String schema, String table) throws SQLException { - PreparedStatement mockStmt = mock(PreparedStatement.class); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); ResultSet mockRs = mock(ResultSet.class); - when(bigQueryConnection.prepareStatement(anyString(), eq(true))).thenReturn(mockStmt); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); when(mockStmt.executeQuery()).thenReturn(mockRs); ResultSet rs = dbMetadata.getExportedKeys(catalog, schema, table); assertSame(mockRs, rs); ArgumentCaptor sqlCaptor = ArgumentCaptor.forClass(String.class); - verify(bigQueryConnection).prepareStatement(sqlCaptor.capture(), eq(true)); + verify(bigQueryConnection).prepareStatementInternal(sqlCaptor.capture(), eq(true)); + verify(bigQueryConnection, never()).prepareStatement(anyString()); + verify(bigQueryConnection, never()).prepareStatement(anyString(), anyBoolean()); String preparedSql = sqlCaptor.getValue(); assertThat(preparedSql) .contains(String.format("`%s.%s.INFORMATION_SCHEMA.KEY_COLUMN_USAGE`", catalog, schema)); @@ -3567,7 +3604,7 @@ private void assertExportedKeysPreparedQuery(String catalog, String schema, Stri static Stream exportedKeysFlexibleTableAndCatalogProvider() { return Stream.of( - Arguments.of("tpczero-system:bigquery-drivers", "_dataset_1", "my-table 01"), + Arguments.of("custom-universe:my-project", "_dataset_1", "my-table 01"), Arguments.of("domain.com:project-1", "dataset_p", "00_お客様")); } @@ -3586,9 +3623,9 @@ public void testGetExportedKeys_flexibleTableNamesAndPrefixedCatalog( @Test public void testGetPrimaryKeys_graphTableSkipsPreparedStatementDryRun() throws SQLException { when(bigQueryConnection.isEnableGraphMetadata()).thenReturn(true); - PreparedStatement mockStmt = mock(PreparedStatement.class); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); ResultSet mockRs = mock(ResultSet.class); - when(bigQueryConnection.prepareStatement(anyString(), eq(true))).thenReturn(mockStmt); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); when(mockStmt.executeQuery()).thenReturn(mockRs); when(mockRs.next()).thenReturn(false); @@ -3596,15 +3633,15 @@ public void testGetPrimaryKeys_graphTableSkipsPreparedStatementDryRun() throws S dbMetadata.getPrimaryKeys("test-project", "dataset_p", "RetailGraph.Product")) { assertFalse(rs.next()); } - verify(bigQueryConnection).prepareStatement(anyString(), eq(true)); + verify(bigQueryConnection).prepareStatementInternal(anyString(), eq(true)); verify(mockStmt).setString(1, "RetailGraph.Product"); } @Test public void testGetExportedKeys_closesStatementWhenBindingFails() throws SQLException { - PreparedStatement mockStmt = mock(PreparedStatement.class); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); SQLException bindFailure = new SQLException("parameter failure"); - when(bigQueryConnection.prepareStatement(anyString(), eq(true))).thenReturn(mockStmt); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); doThrow(bindFailure).when(mockStmt).setString(1, "ref_table"); BigQueryJdbcException ex = @@ -3618,9 +3655,9 @@ public void testGetExportedKeys_closesStatementWhenBindingFails() throws SQLExce @Test public void testGetExportedKeys_closesStatementWhenExecutionFails() throws SQLException { - PreparedStatement mockStmt = mock(PreparedStatement.class); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); SQLException execFailure = new SQLException("query failure"); - when(bigQueryConnection.prepareStatement(anyString(), eq(true))).thenReturn(mockStmt); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); when(mockStmt.executeQuery()).thenThrow(execFailure); BigQueryJdbcException ex = @@ -3633,9 +3670,9 @@ public void testGetExportedKeys_closesStatementWhenExecutionFails() throws SQLEx @Test public void testGetExportedKeys_closesStatementOnUncheckedException() throws SQLException { - PreparedStatement mockStmt = mock(PreparedStatement.class); + BigQueryPreparedStatement mockStmt = mock(BigQueryPreparedStatement.class); IllegalStateException unexpected = new IllegalStateException("unexpected state"); - when(bigQueryConnection.prepareStatement(anyString(), eq(true))).thenReturn(mockStmt); + when(bigQueryConnection.prepareStatementInternal(anyString(), eq(true))).thenReturn(mockStmt); when(mockStmt.executeQuery()).thenThrow(unexpected); IllegalStateException ex = @@ -3664,6 +3701,7 @@ public void testGetExportedKeys_invalidIdentifiersThrowException() throws SQLExc () -> dbMetadata.getExportedKeys("test-project", invalidSchema, "ref_table")); } + verify(bigQueryConnection, never()).prepareStatementInternal(anyString(), anyBoolean()); verify(bigQueryConnection, never()).prepareStatement(anyString(), anyBoolean()); } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java index c98e8dfabb53..dde6b644e1e6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -22,9 +22,10 @@ import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.times; +import static org.mockito.Mockito.never; import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; @@ -33,16 +34,21 @@ import com.google.cloud.bigquery.jdbc.utils.BigQueryJdbcVersionUtility; import io.opentelemetry.api.OpenTelemetry; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedStatic; public class BigQueryDriverTest extends BigQueryJdbcLoggingBaseTest { @@ -241,15 +247,16 @@ public void testConnect_optOut_noTelemetryRecorded() throws SQLException { } @Test - public void testConnect_recordsMetadataRetrievalOnce() throws SQLException { - // connect() logs four DatabaseMetaData values; it must fetch the object once, not four times. + public void testConnect_doesNotRecordMetadataRetrieval() throws SQLException { + // connect() reads DatabaseMetaData for its startup log line. That is driver-internal and + // must not be attributed to the user as DRIVER_FEATURE_METADATA_RETRIEVAL. try (MockedStatic telemetry = - mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { - bigQueryDriver.connect(VALID_TOKEN_URL, new Properties()); + mockStatic(TelemetryManager.class, CALLS_REAL_METHODS); + Connection ignored = bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())) { telemetry.verify( () -> TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL), - times(1)); + never()); } } @@ -261,7 +268,7 @@ public void testConnect_failedAttemptCarriesAuthType() { try (MockedStatic telemetry = mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { Assertions.assertThrows( - Exception.class, + BigQueryJdbcRuntimeException.class, () -> bigQueryDriver.connect( "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" @@ -281,7 +288,9 @@ public void testConnect_ioExceptionThrowsInsteadOfReturningNull() { // BigQueryJdbcRootLogger.setLevel is the only IOException source on the connect path. JDBC // requires connect() to throw for an accepted URL that fails, not return null. try (MockedStatic rootLogger = - mockStatic(BigQueryJdbcRootLogger.class)) { + mockStatic(BigQueryJdbcRootLogger.class); + MockedStatic telemetry = + mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { rootLogger .when(() -> BigQueryJdbcRootLogger.setLevel(any(), any())) .thenThrow(new IOException("simulated log path failure")); @@ -290,6 +299,119 @@ public void testConnect_ioExceptionThrowsInsteadOfReturningNull() { BigQueryJdbcException.class, () -> bigQueryDriver.connect(VALID_TOKEN_URL, new Properties())); assertThat(thrown.getCause()).isInstanceOf(IOException.class); + // The failure happens before the URL's auth type is resolved, hence UNSPECIFIED. + telemetry.verify( + () -> + TelemetryManager.recordConnectionAttempt( + eq(Status.STATUS_ERROR), + anyInt(), + eq(AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED))); + } + } + + @Test + public void testAllowUrlLogPathFalseBlocksUrlAndPropertiesLogPath(@TempDir Path tempDir) + throws Exception { + Path blockedUrlDir = tempDir.resolve("blocked_url_dir"); + Path blockedPropsDir = tempDir.resolve("blocked_props_dir"); + Path blockedDirectConnDir = tempDir.resolve("blocked_direct_conn_dir"); + String propName = BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY; + String prev = System.getProperty(propName); + System.setProperty(propName, " false "); + + try (BigQueryJdbcMdc.MdcCloseable outerMdc = + BigQueryJdbcMdc.registerInstance("enclosing-caller-conn")) { + Properties connectProps = new Properties(); + connectProps.setProperty("OAuthAccessToken", "connect-secret-token"); + String url = + getBaseUri() + .append("OAuthType", 2) + .append("ProjectId", "proj-locked") + .append("LogLevel", 7) + .append("LogPath", blockedUrlDir.toString()) + .toString(); + capturedLogs.clear(); + try (Connection conn = bigQueryDriver.connect(url, connectProps)) { + assertThat(conn.isClosed()).isFalse(); + Assertions.assertNotNull(conn.getWarnings()); + assertThat(conn.getWarnings().getMessage()).contains("Ignoring URL/Properties LogPath"); + } + assertThat(BigQueryJdbcMdc.getConnectionId()).isEqualTo("enclosing-caller-conn"); + assertThat(Files.exists(blockedUrlDir)).isFalse(); + assertThat(assertLogContains("Appending OAuthAccessToken with value ***** to URL")).isTrue(); + assertThat(assertLogContains("Ignoring URL/Properties LogPath")).isTrue(); + assertThat(assertLogContains("connect-secret-token")).isFalse(); + + // Fail-closed boolean parsing: "0", "no", "off" block URL LogPath; "", "true", "1" allow it + System.setProperty(propName, "0"); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isFalse(); + System.setProperty(propName, "no"); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isFalse(); + System.setProperty(propName, "off"); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isFalse(); + System.setProperty(propName, "1"); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isTrue(); + System.setProperty(propName, " TRUE "); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isTrue(); + System.setProperty(propName, " "); + assertThat(BigQueryJdbcUrlUtility.isUrlLogPathAllowed()).isTrue(); + System.setProperty(propName, "false"); + + // LogPath supplied via Properties is also ignored when allowUrlLogPath=false + Properties propsWithLogPath = new Properties(); + propsWithLogPath.setProperty("LogPath", blockedPropsDir.toString()); + String baseLogUrl = + getUriOAuthToken().append("ProjectId", "proj-props").append("LogLevel", 7).toString(); + try (Connection conn = bigQueryDriver.connect(baseLogUrl, propsWithLogPath)) { + assertThat(conn.isClosed()).isFalse(); + Assertions.assertNotNull(conn.getWarnings()); + assertThat(conn.getWarnings().getMessage()).contains("Ignoring URL/Properties LogPath"); + } + assertThat(Files.exists(blockedPropsDir)).isFalse(); + + // Direct BigQueryConnection construction also honors allowUrlLogPath=false + String directUrl = + getUriOAuthToken() + .append("ProjectId", "proj-direct") + .append("LogLevel", 7) + .append("LogPath", blockedDirectConnDir.toString()) + .toString(); + try (BigQueryConnection directConn = new BigQueryConnection(directUrl)) { + assertThat(directConn.isClosed()).isFalse(); + Assertions.assertNotNull(directConn.getWarnings()); + assertThat(directConn.getWarnings().getMessage()) + .contains("Ignoring URL/Properties LogPath"); + } + assertThat(Files.exists(blockedDirectConnDir)).isFalse(); + + // Failed connect() also restores enclosing MDC + String invalidLogLevelUrl = + getUriOAuthToken().append("ProjectId", "proj-fail").append("LogLevel", "bad").toString(); + Assertions.assertThrows( + SQLException.class, () -> bigQueryDriver.connect(invalidLogLevelUrl, new Properties())); + assertThat(BigQueryJdbcMdc.getConnectionId()).isEqualTo("enclosing-caller-conn"); + + // Omitting LogPath when allowUrlLogPath=false does NOT fall back to CWD and adds no warning + Path cwd = Paths.get("").toAbsolutePath(); + long cwdLogsBefore; + try (Stream s = Files.list(cwd)) { + cwdLogsBefore = s.filter(p -> p.getFileName().toString().startsWith("BQ-JDBC-")).count(); + } + try (Connection conn = bigQueryDriver.connect(baseLogUrl, new Properties())) { + assertThat(conn.isClosed()).isFalse(); + Assertions.assertNull(conn.getWarnings()); + } + try (Stream s = Files.list(cwd)) { + long cwdLogsAfter = + s.filter(p -> p.getFileName().toString().startsWith("BQ-JDBC-")).count(); + assertThat(cwdLogsAfter).isEqualTo(cwdLogsBefore); + } + } finally { + if (prev == null) { + System.clearProperty(propName); + } else { + System.setProperty(propName, prev); + } } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java index 2529c1bff75a..24a7f6afee83 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcBaseTest.java @@ -59,7 +59,7 @@ protected static BigQuery getBigQuery(String connectionUrl) { return (BigQuery) method.invoke(unwrapped); } } catch (Throwable e) { - // ignore for some set of tests; Proxy/TPC tests will fail if it doesn't work. + // ignore for some set of tests; Proxy/universe-domain tests will fail if it doesn't work. } return BigQueryOptions.getDefaultInstance().getService(); } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java index 1c44399c3abd..b741ade59019 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java @@ -17,6 +17,7 @@ package com.google.cloud.bigquery.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -29,17 +30,32 @@ import com.google.cloud.bigquery.FieldValue.Attribute; import com.google.cloud.bigquery.FieldValueList; import com.google.cloud.bigquery.LegacySQLTypeName; +import com.google.common.io.ByteStreams; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.sql.Statement; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import java.util.stream.Stream; import org.apache.arrow.vector.util.JsonStringArrayList; import org.apache.arrow.vector.util.JsonStringHashMap; import org.junit.jupiter.api.AfterEach; @@ -215,6 +231,7 @@ public void testResultSetLoggerTrace() { assertEquals("Hello finest trace message", record.getMessage()); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -250,6 +267,7 @@ public void testResultSetLoggerStandardMethods() { assertEquals("Fine msg", r3.getMessage()); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -287,6 +305,7 @@ public void testResultSetLoggerSupplierMethods() { assertEquals("Lazy finest RS message", record.getMessage()); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -325,6 +344,7 @@ public void testResultSetLoggerSupplierTraceMethods() { assertEquals("Lazy finest RS trace message", record.getMessage()); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -335,7 +355,10 @@ public void testResultSetLoggerCachingBehavior() { BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class); BigQueryJdbcResultSetLogger globalLogger2 = BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class); + BigQueryJdbcResultSetLogger emptyIdLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, ""); assertSame(globalLogger1, globalLogger2); + assertSame(globalLogger1, emptyIdLogger); // Connection-scoped facades are distinct lightweight objects, but they all forward to the // single registered logger for the class — that is what prevents the registration leak. BigQueryJdbcResultSetLogger connLogger1 = @@ -360,17 +383,20 @@ public void testResultSetLoggerParameterPreservation() { LogRecord record = new LogRecord(Level.INFO, "Processing job {0}"); record.setParameters(new Object[] {"job-999"}); rsLogger.log(record); + rsLogger.log(record); List records = rsHandler.getRecords(); - assertEquals(1, records.size()); - LogRecord loggedRecord = records.get(0); + assertEquals(2, records.size()); + LogRecord loggedRecord = records.get(1); Object[] params = loggedRecord.getParameters(); assertEquals(2, params.length); - assertEquals("conn-123", params[0]); + assertTrue(params[0] instanceof ConnectionLogContext); + assertEquals("conn-123", ((ConnectionLogContext) params[0]).connectionId()); assertEquals("job-999", params[1]); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -394,7 +420,9 @@ private void assertConnectionIdPropagated( capturedLogs.clear(); action.run(); assertEquals(1, capturedLogs.size()); - assertEquals(connectionId, capturedLogs.get(0).getParameters()[0]); + Object firstParam = capturedLogs.get(0).getParameters()[0]; + assertTrue(firstParam instanceof ConnectionLogContext); + assertEquals(connectionId, ((ConnectionLogContext) firstParam).connectionId()); assertTrue(assertLogContains(expectedMessage)); } finally { BigQueryJdbcRootLogger.getRootLogger().setLevel(originalRootLevel); @@ -730,6 +758,345 @@ public void testConnectionScopedResultSetLoggersDoNotRegisterChildLoggers() "Connection-scoped result-set loggers must not register child loggers on the driver root"); } + @Test + public void testGate1ShortCircuitsDisabledAndHigherThresholdConnectionsWhileFinestIsActive( + @TempDir Path tempDir) throws Exception { + Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + rootLogger.removeHandler(this.handler); + logger.removeHandler(testHandler); + logger.setLevel(null); + + String finestConn = "conn-gate1-finest"; + String infoConn = "conn-gate1-info"; + String offConn = "conn-gate1-off"; + + try { + BigQueryJdbcRootLogger.registerConnection( + finestConn, "7", tempDir.resolve("finest").toString()); + BigQueryJdbcRootLogger.registerConnection(infoConn, "3", tempDir.resolve("info").toString()); + BigQueryJdbcRootLogger.registerConnection(offConn, "0", null); + + assertFalse(BigQueryJdbcRootLogger.hasExternalHandler()); + assertEquals(Level.FINEST, rootLogger.getLevel()); + assertFalse(logger.isLoggable(null)); + + AtomicInteger supplierEvaluations = new AtomicInteger(); + BigQueryJdbcResultSetLogger globalRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryResultSetMetadata.class); + + // 1. CustomLogger + Global ResultSetLogger + MDC path + try (BigQueryJdbcMdc.MdcCloseable offMdc = BigQueryJdbcMdc.registerInstance(offConn)) { + assertFalse(logger.isLoggable(Level.SEVERE)); + assertFalse(globalRsLogger.isLoggable(Level.FINEST)); + logger.fine( + () -> { + supplierEvaluations.incrementAndGet(); + return "Should not evaluate on OFF connection"; + }); + globalRsLogger.finestTrace( + "getColumnCount", + () -> { + supplierEvaluations.incrementAndGet(); + return "Should not evaluate on global RS facade under OFF MDC"; + }); + } + try (BigQueryJdbcMdc.MdcCloseable infoMdc = BigQueryJdbcMdc.registerInstance(infoConn)) { + assertFalse(logger.isLoggable(Level.FINE)); + assertFalse(globalRsLogger.isLoggable(Level.FINE)); + assertTrue(logger.isLoggable(Level.INFO)); + assertTrue(globalRsLogger.isLoggable(Level.INFO)); + logger.fine( + () -> { + supplierEvaluations.incrementAndGet(); + return "Should not evaluate FINE on INFO connection"; + }); + } + assertEquals(0, supplierEvaluations.get()); + + // 2. Connection-scoped ResultSetLogger + child Struct/Array loggers + BigQueryJdbcResultSetLogger offRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, offConn); + BigQueryJdbcResultSetLogger offStructLogger = offRsLogger.getArrowStructLogger(); + BigQueryJdbcResultSetLogger infoRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, infoConn); + BigQueryJdbcResultSetLogger finestRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, finestConn); + + assertFalse(offRsLogger.isLoggable(null)); + assertFalse(offRsLogger.isLoggable(Level.FINEST)); + assertFalse(offStructLogger.isLoggable(Level.FINEST)); + assertFalse(infoRsLogger.isLoggable(Level.FINEST)); + assertTrue(infoRsLogger.isLoggable(Level.INFO)); + assertTrue(finestRsLogger.isLoggable(Level.FINEST)); + + offRsLogger.finestTrace( + "getInt", + () -> { + supplierEvaluations.incrementAndGet(); + return "Skipped on OFF RS"; + }); + offStructLogger.finest( + () -> { + supplierEvaluations.incrementAndGet(); + return "Skipped on OFF Struct"; + }); + infoRsLogger.finestTrace( + "getString", + () -> { + supplierEvaluations.incrementAndGet(); + return "Skipped on INFO RS"; + }); + assertEquals(0, supplierEvaluations.get()); + + // 3. Closing FINEST connection flips context to OFF_VALUE so retained ResultSet logger drops + // WARNING/SEVERE at Gate 1 even while infoConn keeps rootLogger at Level.INFO + BigQueryJdbcRootLogger.closeConnectionHandler(finestConn); + assertEquals(Level.INFO, rootLogger.getLevel()); + assertEquals(null, finestRsLogger.delegate().getLevel()); + assertFalse(finestRsLogger.isLoggable(Level.SEVERE)); + assertFalse(finestRsLogger.isLoggable(Level.WARNING)); + finestRsLogger.warning("Post-close warning %s", "skipped"); + assertEquals(0, supplierEvaluations.get()); + } finally { + BigQueryJdbcRootLogger.resetForTest(); + restoreTestHandlers(rootLogger); + } + } + + @Test + public void testGate1NestedMdcIsolationWritesToResultSetLogAndRestoresMdc(@TempDir Path tempDir) + throws Exception { + Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + rootLogger.removeHandler(this.handler); + logger.removeHandler(testHandler); + logger.setLevel(null); + + String finestConn = "conn-nested-finest"; + String offConn = "conn-nested-off"; + Path finestDir = tempDir.resolve("finest"); + Path offDir = tempDir.resolve("off"); + + try { + BigQueryJdbcRootLogger.registerConnection(finestConn, "7", finestDir.toString()); + BigQueryJdbcRootLogger.registerConnection(offConn, "0", offDir.toString()); + + BigQueryJdbcResultSetLogger finestRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, finestConn); + BigQueryJdbcResultSetLogger offRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, offConn); + + // FINEST ResultSet nested inside an OFF MDC writes to finestDir and restores MDC + try (BigQueryJdbcMdc.MdcCloseable offMdc = BigQueryJdbcMdc.registerInstance(offConn)) { + finestRsLogger.finestTrace("getInt", () -> "Nested FINEST RS marker"); + assertEquals(offConn, BigQueryJdbcMdc.getConnectionId()); + } + + // OFF ResultSet nested inside a FINEST MDC skips warning formatting and manual records + try (BigQueryJdbcMdc.MdcCloseable finestMdc = BigQueryJdbcMdc.registerInstance(finestConn)) { + offRsLogger.warning("Should not appear in finest log %s", "ever"); + offRsLogger.log(new LogRecord(Level.SEVERE, "Manual OFF record skipped")); + offRsLogger.log(null); + assertEquals(finestConn, BigQueryJdbcMdc.getConnectionId()); + } + + BigQueryJdbcRootLogger.closeConnectionHandler(finestConn); + assertFalse(Files.exists(offDir)); + + List finestFiles = new ArrayList<>(); + try (Stream s = Files.list(finestDir)) { + s.filter(p -> !p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL")) + .forEach(finestFiles::add); + } + assertEquals(1, finestFiles.size()); + String content = new String(Files.readAllBytes(finestFiles.get(0)), StandardCharsets.UTF_8); + assertTrue(content.contains("Nested FINEST RS marker")); + assertTrue(content.contains("[" + finestConn + "]")); + assertFalse(content.contains("Should not appear in finest log")); + assertFalse(content.contains("Manual OFF record skipped")); + } finally { + BigQueryJdbcRootLogger.resetForTest(); + restoreTestHandlers(rootLogger); + } + } + + @Test + public void testGate1ExternalHandlersParentDelegationAndProxyContextCaching(@TempDir Path tempDir) + throws Exception { + Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + rootLogger.removeHandler(this.handler); + logger.removeHandler(testHandler); + logger.setLevel(null); + + String finestConn = "conn-branch-finest"; + String offConn = "conn-branch-off"; + String unregisteredConn = "conn-branch-unregistered"; + + try { + BigQueryJdbcRootLogger.registerConnection( + finestConn, "7", tempDir.resolve("finest").toString()); + BigQueryJdbcRootLogger.registerConnection(offConn, "0", null); + BigQueryJdbcResultSetLogger offRsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, offConn); + + // 1. Unattributed (ctx == null) and unregistered connections defer to rootLogger + BigQueryJdbcMdc.clear(); + assertTrue(logger.isLoggable(Level.FINEST)); + try (BigQueryJdbcMdc.MdcCloseable unregisteredMdc = + BigQueryJdbcMdc.registerInstance(unregisteredConn)) { + assertTrue(logger.isLoggable(Level.FINEST)); + } + + // 2. Child logger with its own handler bypasses per-connection OFF filter + logger.addHandler(testHandler); + try (BigQueryJdbcMdc.MdcCloseable offMdc = BigQueryJdbcMdc.registerInstance(offConn)) { + assertTrue(logger.isLoggable(Level.FINE)); + } + logger.removeHandler(testHandler); + try (BigQueryJdbcMdc.MdcCloseable offMdc = BigQueryJdbcMdc.registerInstance(offConn)) { + assertFalse(logger.isLoggable(Level.FINE)); + } + + // 3. BigQueryJdbcContextProxy caches ConnectionLogContext and propagates it on invoke + BigQueryStatement mockOffStmt = mock(BigQueryStatement.class); + Statement wrappedOffStmt = + BigQueryJdbcContextProxy.wrap(mockOffStmt, Statement.class, offConn); + wrappedOffStmt.getMaxRows(); + assertFalse(Files.exists(tempDir.resolve("off"))); + + // 4. Async MdcThreadPoolExecutor submit() and execute() propagate ConnectionLogContext + ExecutorService pool = BigQueryJdbcMdc.newFixedThreadPool("gate1-test", 1); + try { + Future offCallable; + CountDownLatch offExecDone = new CountDownLatch(1); + AtomicBoolean offExecLoggable = new AtomicBoolean(true); + try (BigQueryJdbcMdc.MdcCloseable offMdc = BigQueryJdbcMdc.registerInstance(offConn)) { + offCallable = pool.submit(() -> logger.isLoggable(Level.FINE)); + pool.execute( + () -> { + offExecLoggable.set(logger.isLoggable(Level.FINE)); + offExecDone.countDown(); + }); + } + assertFalse(offCallable.get()); + assertTrue(offExecDone.await(5, TimeUnit.SECONDS)); + assertFalse(offExecLoggable.get()); + + Future finestCallable; + try (BigQueryJdbcMdc.MdcCloseable finestMdc = + BigQueryJdbcMdc.registerInstance(finestConn)) { + finestCallable = pool.submit(() -> logger.isLoggable(Level.FINEST)); + } + assertTrue(finestCallable.get()); + } finally { + pool.shutdownNow(); + } + + // 5. Enabling useParentHandlers on rootLogger treats parent delegation as an external sink + rootLogger.setUseParentHandlers(true); + assertTrue(BigQueryJdbcRootLogger.hasExternalHandler()); + assertTrue(offRsLogger.isLoggable(Level.FINEST)); + rootLogger.setUseParentHandlers(false); + assertFalse(BigQueryJdbcRootLogger.hasExternalHandler()); + assertFalse(offRsLogger.isLoggable(Level.FINEST)); + + // 6. Direct verification of scanForExternalHandler on a plain non-RootDriverLogger Logger + Logger plainLogger = new Logger("test.plain.bigquery", null) {}; + plainLogger.setUseParentHandlers(false); + plainLogger.addHandler(new OpenTelemetryJulHandler()); + assertFalse(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + TestHandler plainExternal = new TestHandler(); + plainLogger.addHandler(plainExternal); + assertTrue(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + plainLogger.removeHandler(plainExternal); + assertFalse(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + plainLogger.setUseParentHandlers(true); + assertTrue(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + + // 7. Re-attaching an external JUL handler on rootLogger restores visibility + rootLogger.addHandler(this.handler); + rootLogger.setLevel(Level.ALL); + assertTrue(BigQueryJdbcRootLogger.hasExternalHandler()); + assertTrue(offRsLogger.isLoggable(Level.FINEST)); + } finally { + BigQueryJdbcRootLogger.resetForTest(); + restoreTestHandlers(rootLogger); + } + } + + @Test + public void testIsolatedClassLoaderDoesNotRegisterDuplicateOrExternalHandlers() throws Exception { + Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + rootLogger.removeHandler(this.handler); + try { + int handlersBefore = rootLogger.getHandlers().length; + ClassLoader isolatedLoader = new IsolatedJdbcClassLoader(getClass().getClassLoader()); + Class.forName(BigQueryJdbcRootLogger.class.getName(), true, isolatedLoader); + + assertEquals(handlersBefore, rootLogger.getHandlers().length); + assertFalse(BigQueryJdbcRootLogger.hasExternalHandler()); + + Handler crossLoaderOtelHandler = + (Handler) + Class.forName(OpenTelemetryJulHandler.class.getName(), true, isolatedLoader) + .getDeclaredConstructor() + .newInstance(); + Logger plainLogger = new Logger("test.crossloader.bigquery", null) {}; + plainLogger.setUseParentHandlers(false); + plainLogger.addHandler(crossLoaderOtelHandler); + assertFalse(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + + ConsoleHandler userConsoleHandler = new ConsoleHandler(); + plainLogger.addHandler(userConsoleHandler); + assertTrue(BigQueryJdbcRootLogger.scanForExternalHandler(plainLogger)); + plainLogger.removeHandler(userConsoleHandler); + } finally { + restoreTestHandlers(rootLogger); + } + } + + private static final class IsolatedJdbcClassLoader extends ClassLoader { + IsolatedJdbcClassLoader(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.startsWith("com.google.cloud.bigquery.jdbc.")) { + return super.loadClass(name, resolve); + } + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + try (InputStream in = + getParent().getResourceAsStream(name.replace('.', '/') + ".class")) { + if (in == null) { + throw new ClassNotFoundException(name); + } + byte[] bytes = ByteStreams.toByteArray(in); + loaded = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + } + } + + private void restoreTestHandlers(Logger rootLogger) { + if (!Arrays.asList(rootLogger.getHandlers()).contains(this.handler)) { + rootLogger.addHandler(this.handler); + } + if (!Arrays.asList(logger.getHandlers()).contains(testHandler)) { + logger.addHandler(testHandler); + } + logger.setLevel(Level.ALL); + rootLogger.setLevel(Level.ALL); + } + /** * Reads the JDK-internal {@code Logger.kids} list. This field is private to {@code java.logging}, * so the surefire {@code argLine} opens {@code java.util.logging} to the test classpath. diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcLoggingBaseTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcLoggingBaseTest.java index 6ed3231eed15..13efd004b264 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcLoggingBaseTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcLoggingBaseTest.java @@ -27,7 +27,7 @@ public abstract class BigQueryJdbcLoggingBaseTest extends BigQueryJdbcBaseTest { protected List capturedLogs = new ArrayList<>(); - private Handler handler; + protected Handler handler; private Logger logger; private long threadId; private java.util.logging.Level originalLevel; @@ -61,12 +61,10 @@ public void close() throws SecurityException {} public void tearDownLogValidator() { if (logger != null && handler != null) { logger.removeHandler(handler); - logger.setLevel(originalLevel); } - try { - BigQueryJdbcRootLogger.setLevel(java.util.logging.Level.OFF, null); - } catch (Exception e) { - // Ignore + BigQueryJdbcRootLogger.resetForTest(); + if (logger != null) { + logger.setLevel(originalLevel); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdcTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdcTest.java index 1194f4e580b4..f5026cc93a69 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdcTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdcTest.java @@ -130,10 +130,19 @@ public void testThreadIsolation() throws InterruptedException { } @Test - public void testMdcCloseableClearsContext() { - try (BigQueryJdbcMdc.MdcCloseable mdc = - BigQueryJdbcMdc.registerInstance("JdbcConnection-789")) { - assertEquals("JdbcConnection-789", BigQueryJdbcMdc.getConnectionId()); + public void testMdcCloseableClearsContextAndRestoresOuterContext() { + try (BigQueryJdbcMdc.MdcCloseable outer = + BigQueryJdbcMdc.registerInstance("JdbcConnection-outer")) { + assertEquals("JdbcConnection-outer", BigQueryJdbcMdc.getConnectionId()); + try (BigQueryJdbcMdc.MdcCloseable inner = + BigQueryJdbcMdc.registerInstance("JdbcConnection-789")) { + assertEquals("JdbcConnection-789", BigQueryJdbcMdc.getConnectionId()); + } + assertEquals("JdbcConnection-outer", BigQueryJdbcMdc.getConnectionId()); + try (BigQueryJdbcMdc.MdcCloseable nullScope = BigQueryJdbcMdc.registerInstance(null)) { + assertNull(BigQueryJdbcMdc.getConnectionId()); + } + assertEquals("JdbcConnection-outer", BigQueryJdbcMdc.getConnectionId()); } assertNull(BigQueryJdbcMdc.getConnectionId()); } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtilityTest.java index 1a086782e341..23a350970c8b 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtilityTest.java @@ -20,36 +20,69 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; - +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; + +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.json.Json; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.auth.http.HttpTransportFactory; +import com.google.auth.oauth2.ExternalAccountCredentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ImpersonatedCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserAuthorizer; import com.google.auth.oauth2.UserCredentials; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; +import com.google.gson.JsonObject; +import java.awt.Desktop; +import java.awt.GraphicsEnvironment; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; +import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; public class BigQueryJdbcOAuthUtilityTest extends BigQueryJdbcBaseTest { private static final int USER_AUTH_PORT = 53737; - private static final String EXPECTED_USER_AUTH_URL = - "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=client_id&redirect_uri=http://localhost:" - + USER_AUTH_PORT - + "&scope=https://www.googleapis.com/auth/bigquery&state=test_state&access_type=offline&prompt=consent&login_hint=test_user&include_granted_scopes=true"; + private static final URI USER_AUTH_CALLBACK_URI = + URI.create("http://127.0.0.1:" + USER_AUTH_PORT); @Test public void testParseOAuthPropsWithSpecialChars() { @@ -173,7 +206,7 @@ public void testGetCredentialsForPreGeneratedToken() { } @Test - public void testGetCredentialsForPreGeneratedTokenTPC() throws IOException { + public void testGetCredentialsForPreGeneratedTokenCustomUniverseDomain() throws IOException { Map authProperties = BigQueryJdbcOAuthUtility.parseOAuthProperties( DataSource.fromUrl( @@ -240,26 +273,105 @@ public void testParseOAuthPropsForUserAuthDefault() { } @Test - public void testGenerateUserAuthURL() { - try { - HashMap authProperties = new HashMap<>(); - authProperties.put(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, "client_id"); - authProperties.put(BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, "client_secret"); - - UserAuthorizer userAuthorizer = - BigQueryJdbcOAuthUtility.getUserAuthorizer( - authProperties, new HashMap(), USER_AUTH_PORT, null, null); + public void testGenerateUserAuthURL() throws Exception { + HashMap authProperties = new HashMap<>(); + authProperties.put(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, "client_id"); + authProperties.put(BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, "client_secret"); + + UserAuthorizer userAuthorizer = + BigQueryJdbcOAuthUtility.getUserAuthorizer( + authProperties, + new HashMap(), + false, + USER_AUTH_CALLBACK_URI, + null, + null); - String userId = "test_user"; - String state = "test_state"; - URI baseURI = URI.create("http://example.com/foo"); + URL authURL = + userAuthorizer.getAuthorizationUrl( + "test_user", "test_state", URI.create("http://example.com/foo")); + Map params = parseQueryParams(authURL.toURI().getRawQuery()); + + assertThat(authURL.getProtocol()).isEqualTo("https"); + assertThat(authURL.getHost()).isEqualTo("accounts.google.com"); + assertThat(authURL.getPath()).isEqualTo("/o/oauth2/auth"); + assertThat(params.get("response_type")).isEqualTo("code"); + assertThat(params.get("client_id")).isEqualTo("client_id"); + assertThat(params.get("redirect_uri")).isEqualTo("http://127.0.0.1:" + USER_AUTH_PORT); + assertThat(params.get("scope")).isEqualTo("https://www.googleapis.com/auth/bigquery"); + assertThat(params.get("state")).isEqualTo("test_state"); + assertThat(params.get("access_type")).isEqualTo("offline"); + assertThat(params.get("prompt")).isEqualTo("consent"); + assertThat(params.get("login_hint")).isEqualTo("test_user"); + assertThat(params.get("include_granted_scopes")).isEqualTo("true"); + assertThat(params.get("code_challenge_method")).isEqualTo("S256"); + assertThat(params.get("code_challenge")).matches("^[A-Za-z0-9_-]{43}$"); + + UserAuthorizer driveScopeAuthorizer = + BigQueryJdbcOAuthUtility.getUserAuthorizer( + authProperties, Collections.emptyMap(), true, USER_AUTH_CALLBACK_URI, null, null); + URL driveAuthUrl = + driveScopeAuthorizer.getAuthorizationUrl("test_user", "test_state", URI.create("")); + Map driveParams = parseQueryParams(driveAuthUrl.toURI().getRawQuery()); + assertThat(driveParams.get("scope")) + .isEqualTo( + "https://www.googleapis.com/auth/bigquery" + + " https://www.googleapis.com/auth/drive.readonly"); + } - URL authURL = userAuthorizer.getAuthorizationUrl(userId, state, baseURI); + @Test + public void testGetUserAuthorizer_configuresRfc7636Pkce() throws Exception { + Map authProperties = defaultUserAuthProperties(); + + AtomicReference> capturedTokenParams = new AtomicReference<>(); + HttpTransportFactory transportFactory = + createMockTokenTransport(capturedTokenParams, null, null); + + UserAuthorizer userAuthorizer = + BigQueryJdbcOAuthUtility.getUserAuthorizer( + authProperties, + Collections.emptyMap(), + false, + USER_AUTH_CALLBACK_URI, + transportFactory, + null); - assertThat(authURL.toString()).isEqualTo(EXPECTED_USER_AUTH_URL); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } + URL authUrl = userAuthorizer.getAuthorizationUrl("user", "state_val", URI.create("")); + Map authParams = parseQueryParams(authUrl.toURI().getRawQuery()); + String codeChallenge = authParams.get("code_challenge"); + assertThat(authParams.get("code_challenge_method")).isEqualTo("S256"); + assertThat(codeChallenge).matches("^[A-Za-z0-9_-]{43}$"); + + UserCredentials credentials = + BigQueryJdbcOAuthUtility.getCredentialsFromCode( + userAuthorizer, "sample_code", Collections.emptyMap(), transportFactory, null); + assertThat(credentials.getAccessToken().getTokenValue()).isEqualTo("mock_access_token"); + assertThat(credentials.getUniverseDomain()).isEqualTo("googleapis.com"); + assertThat(credentials.toBuilder().getHttpTransportFactory()).isEqualTo(transportFactory); + + Map tokenParams = capturedTokenParams.get(); + assertThat(tokenParams).isNotNull(); + String codeVerifier = tokenParams.get("code_verifier"); + assertThat(codeVerifier).isNotNull(); + assertThat(codeVerifier).matches("^[A-Za-z0-9._~-]{43,128}$"); + assertThat(computeS256Challenge(codeVerifier)).isEqualTo(codeChallenge); + + UserCredentials unchangedCredentials = + BigQueryJdbcOAuthUtility.getCredentialsFromCode( + userAuthorizer, "sample_code", Collections.emptyMap(), null, null); + assertThat(unchangedCredentials.getUniverseDomain()).isEqualTo("googleapis.com"); + + UserCredentials universeOnlyCredentials = + BigQueryJdbcOAuthUtility.getCredentialsFromCode( + userAuthorizer, + "sample_code", + Collections.singletonMap( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, + "explicit-universe.example.com"), + null, + null); + assertThat(universeOnlyCredentials.getUniverseDomain()) + .isEqualTo("explicit-universe.example.com"); } @Test @@ -281,7 +393,7 @@ public void testGenerateUserAuthURLOverrideOauthEndpoint() { UserAuthorizer userAuthorizer = BigQueryJdbcOAuthUtility.getUserAuthorizer( - authProperties, overrideProperties, USER_AUTH_PORT, null, null); + authProperties, overrideProperties, false, USER_AUTH_CALLBACK_URI, null, null); assertThat(overrideTokenSeverURI).isEqualTo(userAuthorizer.toBuilder().getTokenServerUri()); } catch (URISyntaxException e) { @@ -565,4 +677,1137 @@ public void testGetPreGeneratedRefreshTokenCredentialsPropagatesHttpTransportFac assertThat(((UserCredentials) credentials).toBuilder().getHttpTransportFactory()) .isEqualTo(dummyFactory); } + + @Test + public void testOpenLoopbackServerSocket_bindsLoopbackAndFallsBackToIpv6() throws Exception { + try (ServerSocket serverSocket = BigQueryJdbcOAuthCallbackServer.openLoopbackServerSocket()) { + assertThat(serverSocket.getInetAddress().isLoopbackAddress()).isTrue(); + assertThat(serverSocket.getInetAddress().isAnyLocalAddress()).isFalse(); + } + + InetAddress ipv4Loopback = InetAddress.getByAddress(new byte[] {127, 0, 0, 1}); + InetAddress ipv6Loopback = + InetAddress.getByAddress(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}); + assertThat( + BigQueryJdbcOAuthCallbackServer.buildLoopbackCallbackUri(ipv4Loopback, USER_AUTH_PORT)) + .isEqualTo(URI.create("http://127.0.0.1:" + USER_AUTH_PORT)); + assertThat( + BigQueryJdbcOAuthCallbackServer.buildLoopbackCallbackUri(ipv6Loopback, USER_AUTH_PORT)) + .isEqualTo(URI.create("http://[::1]:" + USER_AUTH_PORT)); + + AtomicReference fallbackBoundAddress = new AtomicReference<>(); + AtomicInteger capturedBacklog = new AtomicInteger(); + try (ServerSocket unboundIpv6Socket = new ServerSocket()) { + ServerSocket fallbackResult = + BigQueryJdbcOAuthCallbackServer.openLoopbackServerSocket( + (address, backlog) -> { + if (!(address instanceof Inet6Address)) { + throw new IOException("IPv4 loopback unavailable"); + } + fallbackBoundAddress.set(address); + capturedBacklog.set(backlog); + return unboundIpv6Socket; + }); + assertThat(fallbackResult).isSameInstanceAs(unboundIpv6Socket); + assertThat(fallbackBoundAddress.get()).isEqualTo(ipv6Loopback); + assertThat(capturedBacklog.get()).isEqualTo(8); + } + + IOException ipv4Error = new IOException("IPv4 bind failed"); + IOException ipv6Error = new IOException("IPv6 bind failed"); + IOException combined = + assertThrows( + IOException.class, + () -> + BigQueryJdbcOAuthCallbackServer.openLoopbackServerSocket( + (address, backlog) -> { + throw (address instanceof Inet6Address) ? ipv6Error : ipv4Error; + })); + assertThat(combined).isSameInstanceAs(ipv4Error); + assertThat(combined.getSuppressed()).asList().containsExactly(ipv6Error); + } + + @Test + public void testUserAuthFlow_exchangesUrlEncodedCodeWithValidState() throws Exception { + Map authProperties = defaultUserAuthProperties(); + AtomicReference> capturedTokenParams = new AtomicReference<>(); + AtomicReference capturedServerSocket = new AtomicReference<>(); + AtomicBoolean closedBeforeTokenExchange = new AtomicBoolean(false); + + HttpTransportFactory transportFactory = + createMockTokenTransport( + capturedTokenParams, + null, + () -> closedBeforeTokenExchange.set(capturedServerSocket.get().isClosed())); + + AtomicReference> rawHttpResponseFuture = new AtomicReference<>(); + AtomicReference capturedState = new AtomicReference<>(); + AtomicReference capturedChallenge = new AtomicReference<>(); + + GoogleCredentials credentials = + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.singletonMap( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, + "explicit-universe.example.com"), + false, + transportFactory, + null, + capturingSocketSupplier(capturedServerSocket), + authUri -> { + Map params = parseQueryParams(authUri.getRawQuery()); + URI redirectUri = URI.create(params.get("redirect_uri")); + capturedState.set(params.get("state")); + capturedChallenge.set(params.get("code_challenge")); + rawHttpResponseFuture.set( + runAsyncClient( + () -> + sendHttpRequest( + redirectUri, + callbackGetRequest( + redirectUri, + "/?state=" + + params.get("state") + + "&code=4%2F0A+raw%2Bencoded")))); + }, + 5000, + 2000); + + assertThat(credentials).isInstanceOf(UserCredentials.class); + assertThat(credentials.getUniverseDomain()).isEqualTo("explicit-universe.example.com"); + assertThat(closedBeforeTokenExchange.get()).isTrue(); + assertThat(capturedServerSocket.get().isClosed()).isTrue(); + assertThat(capturedState.get()).matches("^[A-Za-z0-9_-]{43}$"); + assertThat(capturedTokenParams.get().get("code")).isEqualTo("4/0A+raw+encoded"); + assertThat(computeS256Challenge(capturedTokenParams.get().get("code_verifier"))) + .isEqualTo(capturedChallenge.get()); + + String rawResponse = rawHttpResponseFuture.get().get(5, TimeUnit.SECONDS); + assertValidHttpResponse(rawResponse, "HTTP/1.1 200 OK"); + assertThat(rawResponse).contains("Thank you for using JDBC Driver for Google BigQuery!"); + } + + @Test + public void testUserAuthFlow_supportsHttp10QueryVariantsAndAbortedResponseWrite() + throws Exception { + Map authProperties = defaultUserAuthProperties(); + AtomicReference> capturedTokenParams = new AtomicReference<>(); + HttpTransportFactory transportFactory = + createMockTokenTransport(capturedTokenParams, null, null); + AtomicReference capturedServerSocket = new AtomicReference<>(); + AtomicReference> clientFuture = new AtomicReference<>(); + + GoogleCredentials credentials = + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + transportFactory, + null, + capturingSocketSupplier(capturedServerSocket), + authUri -> { + Map params = parseQueryParams(authUri.getRawQuery()); + URI redirectUri = URI.create(params.get("redirect_uri")); + String rawRequest = + "GET /?flag&&state=" + params.get("state") + "&code=http10_code HTTP/1.0\n\n"; + clientFuture.set( + runAsyncClient( + () -> { + try (Socket socket = + new Socket(redirectUri.getHost(), redirectUri.getPort())) { + socket.setSoLinger(true, 0); + socket + .getOutputStream() + .write(rawRequest.getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + } + return null; + })); + }, + 5000, + 2000); + + clientFuture.get().get(5, TimeUnit.SECONDS); + assertThat(credentials).isInstanceOf(UserCredentials.class); + assertThat(credentials.getUniverseDomain()).isEqualTo("googleapis.com"); + assertThat(capturedTokenParams.get().get("code")).isEqualTo("http10_code"); + assertThat(capturedServerSocket.get().isClosed()).isTrue(); + } + + @Test + public void testParseOAuthQueryParameters_preservesLiteralPlusAndRejectsMalformedPercentEncoding() + throws Exception { + assertThat(BigQueryJdbcOAuthCallbackServer.parseOAuthQueryParameters(null)).isEmpty(); + assertThat(BigQueryJdbcOAuthCallbackServer.parseOAuthQueryParameters("")).isEmpty(); + + Map decoded = + BigQueryJdbcOAuthCallbackServer.parseOAuthQueryParameters( + "state=st+1%2B2&code=4%2F0A+raw%2Bencoded%20space"); + assertThat(decoded.get("state")).isEqualTo("st+1+2"); + assertThat(decoded.get("code")).isEqualTo("4/0A+raw+encoded space"); + + for (String malformedQuery : + new String[] { + "state=ok&code=bad_%ZZ_raw_token", + "state=ok&code=trailing_percent_%", + "bad_%2_key=raw_token" + }) { + BigQueryJdbcOAuthCallbackServer.HttpCallbackException ex = + assertThrows( + BigQueryJdbcOAuthCallbackServer.HttpCallbackException.class, + () -> BigQueryJdbcOAuthCallbackServer.parseOAuthQueryParameters(malformedQuery)); + assertThat(ex.getMessage()) + .isEqualTo("Malformed query parameter encoding in OAuth callback."); + assertThat(ex.getCause()).isNull(); + assertThat(ex.getMessage()).doesNotContain("raw_token"); + assertThat(ex.getMessage()).doesNotContain("trailing_percent"); + } + } + + @Test + public void testUserAuthCallback_rejectsInvalidStateCodeAndDuplicates() throws Exception { + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> callbackGetRequest(redirectUri, "/"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> callbackGetRequest(redirectUri, "/?"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?code=some_code&scope=bigquery"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> callbackGetRequest(redirectUri, "/?state=&code=some_code"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=wrong_state&code=some_code&scope=bigquery"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=wrong_state&error=access_denied"), + false, + "Missing or invalid state parameter in OAuth callback."); + assertTerminalCallbackAbortsImmediately( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=" + authParams.get("state")), + "Could not retrieve the authorization code from OAuth callback."); + assertTerminalCallbackAbortsImmediately( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=" + authParams.get("state") + "&code="), + "Could not retrieve the authorization code from OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest( + redirectUri, "/?state=" + authParams.get("state") + "&code=first&code=second"), + false, + "Duplicate OAuth callback parameter: code"); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest( + redirectUri, + "/?state=" + + authParams.get("state") + + "&state=" + + authParams.get("state") + + "&code=first"), + false, + "Duplicate OAuth callback parameter: state"); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest( + redirectUri, "/?state=" + authParams.get("state") + "&error=err1&error=err2"), + false, + "Duplicate OAuth callback parameter: error"); + } + + @Test + public void testUserAuthCallback_handlesAndSanitizesOAuthErrorParameter() throws Exception { + assertTerminalCallbackAbortsImmediately( + (redirectUri, authParams) -> + callbackGetRequest( + redirectUri, "/?state=" + authParams.get("state") + "&error=access_denied"), + "OAuth authorization failed: access_denied"); + assertTerminalCallbackAbortsImmediately( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=" + authParams.get("state") + "&error="), + "OAuth authorization failed: unknown_error"); + + StringBuilder longError = new StringBuilder("bad%22err%20val%0A"); + for (int i = 0; i < 70; i++) { + longError.append('x'); + } + StringBuilder expectedSanitized = new StringBuilder("bad_err_val_"); + while (expectedSanitized.length() < 64) { + expectedSanitized.append('x'); + } + assertTerminalCallbackAbortsImmediately( + (redirectUri, authParams) -> + callbackGetRequest( + redirectUri, "/?state=" + authParams.get("state") + "&error=" + longError), + "OAuth authorization failed: " + expectedSanitized); + } + + @Test + public void testUserAuthCallback_ignoresPreconnectProbesAndFaviconBeforeValidCallback() + throws Exception { + Map authProperties = defaultUserAuthProperties(); + AtomicReference> capturedTokenParams = new AtomicReference<>(); + HttpTransportFactory transportFactory = + createMockTokenTransport(capturedTokenParams, null, null); + AtomicReference> intermediateResponsesFuture = + new AtomicReference<>(); + + GoogleCredentials credentials = + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + transportFactory, + null, + BigQueryJdbcOAuthCallbackServer::openLoopbackServerSocket, + authUri -> { + Map params = parseQueryParams(authUri.getRawQuery()); + URI redirectUri = URI.create(params.get("redirect_uri")); + String host = redirectUri.getHost(); + int port = redirectUri.getPort(); + String state = params.get("state"); + intermediateResponsesFuture.set( + runAsyncClient( + () -> { + try (Socket emptyPreconnect = new Socket(host, port)) { + // Immediate clean EOF preconnect. + } + try (Socket resetPreconnect = new Socket(host, port)) { + resetPreconnect.setSoLinger(true, 0); + } + try (Socket slowDrip = new Socket(host, port)) { + slowDrip.setSoTimeout(40); + OutputStream out = slowDrip.getOutputStream(); + InputStream in = slowDrip.getInputStream(); + for (int i = 0; i < 30; i++) { + try { + out.write('G'); + out.flush(); + } catch (IOException serverClosed) { + break; + } + try { + if (in.read() == -1) { + break; + } + } catch (SocketTimeoutException continueDripping) { + // Drip the next byte until the server closes at readDeadlineNanos. + } catch (IOException serverClosed) { + break; + } + } + } + String headerLine = + "X-Extra-Padding: 0123456789abcdef0123456789abcdef0123456789abcdef\r\n"; + StringBuilder cookieHeavyFavicon = new StringBuilder(25000); + cookieHeavyFavicon + .append("GET /favicon.ico HTTP/1.1\r\nHost: ") + .append(host) + .append("\r\n"); + while (cookieHeavyFavicon.length() < 24000) { + cookieHeavyFavicon.append(headerLine); + } + cookieHeavyFavicon.append("\r\n"); + String faviconResp = + sendHttpRequest(redirectUri, cookieHeavyFavicon.toString()); + String optionsProbeResp = + sendHttpRequest( + redirectUri, + "OPTIONS / HTTP/1.1\r\nHost: " + host + ":" + port + "\r\n\r\n"); + String missingStateProbeResp = + sendHttpRequest( + redirectUri, + callbackGetRequest(redirectUri, "/?code=unverified_probe_code")); + String wrongStateErrorProbeResp = + sendHttpRequest( + redirectUri, + callbackGetRequest( + redirectUri, "/?state=wrong_state&error=access_denied")); + + int oversizedHeaderTarget = + BigQueryJdbcOAuthCallbackServer.MAX_HTTP_HEADER_BYTES + 4096; + StringBuilder largeHeaders = new StringBuilder(oversizedHeaderTarget + 256); + largeHeaders + .append("GET /?state=") + .append(state) + .append("&code=after_preconnect HTTP/1.1\r\nHost: ") + .append(host) + .append("\r\n"); + while (largeHeaders.length() < oversizedHeaderTarget) { + largeHeaders.append(headerLine); + } + largeHeaders.append("\r\n"); + String successResp = sendHttpRequest(redirectUri, largeHeaders.toString()); + return new String[] { + faviconResp, + optionsProbeResp, + missingStateProbeResp, + wrongStateErrorProbeResp, + successResp + }; + })); + }, + 5000, + 200); + + assertThat(credentials).isInstanceOf(UserCredentials.class); + String[] responses = intermediateResponsesFuture.get().get(5, TimeUnit.SECONDS); + assertValidHttpResponse(responses[0], "HTTP/1.1 404 Not Found"); + assertValidHttpResponse(responses[1], "HTTP/1.1 400 Bad Request"); + assertValidHttpResponse(responses[2], "HTTP/1.1 400 Bad Request"); + assertValidHttpResponse(responses[3], "HTTP/1.1 400 Bad Request"); + assertValidHttpResponse(responses[4], "HTTP/1.1 200 OK"); + assertThat(capturedTokenParams.get().get("code")).isEqualTo("after_preconnect"); + } + + @Test + public void testUserAuthCallback_enforcesDeadlinesAndBrowserLaunchFailureCleanup() + throws Exception { + Map authProperties = defaultUserAuthProperties(); + + AtomicReference browserErrorSocket = new AtomicReference<>(); + BigQueryJdbcRuntimeException browserLaunchEx = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + null, + null, + capturingSocketSupplier(browserErrorSocket), + authUri -> { + throw new IOException("Browser launch failed"); + }, + 1000, + 500)); + assertThat(browserLaunchEx.getCause()).isInstanceOf(IOException.class); + assertThat(browserLaunchEx.getCause().getMessage()).isEqualTo("Browser launch failed"); + assertThat(browserErrorSocket.get().isClosed()).isTrue(); + + AtomicReference eofSocket = new AtomicReference<>(); + BigQueryJdbcRuntimeException eofTimeoutEx = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + null, + null, + capturingSocketSupplier(eofSocket), + authUri -> { + URI redirectUri = + URI.create(parseQueryParams(authUri.getRawQuery()).get("redirect_uri")); + try (Socket empty = + new Socket(redirectUri.getHost(), redirectUri.getPort())) { + // Queued synchronously in backlog before overallDeadlineNanos starts. + } + }, + 120, + 60)); + assertThat(eofTimeoutEx.getCause()).isInstanceOf(SocketTimeoutException.class); + assertThat(eofTimeoutEx.getCause().getMessage()) + .isEqualTo("Timed out waiting for OAuth authorization callback."); + assertThat(eofSocket.get().isClosed()).isTrue(); + + AtomicReference stalledSocket = new AtomicReference<>(); + CountDownLatch wrotePartialBytes = new CountDownLatch(1); + CountDownLatch releaseStalledClient = new CountDownLatch(1); + AtomicReference> stalledClientFuture = new AtomicReference<>(); + try { + BigQueryJdbcRuntimeException stalledEx = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + null, + null, + capturingSocketSupplier(stalledSocket), + authUri -> { + URI redirectUri = + URI.create(parseQueryParams(authUri.getRawQuery()).get("redirect_uri")); + stalledClientFuture.set( + runAsyncClient( + () -> { + try (Socket slow = + new Socket(redirectUri.getHost(), redirectUri.getPort())) { + slow.getOutputStream() + .write( + "GET /?state=partial" + .getBytes(StandardCharsets.US_ASCII)); + slow.getOutputStream().flush(); + wrotePartialBytes.countDown(); + releaseStalledClient.await(5, TimeUnit.SECONDS); + } + return null; + })); + try { + assertThat(wrotePartialBytes.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted waiting for partial request write", e); + } + }, + 120, + 500)); + assertThat(stalledEx.getCause()).isInstanceOf(SocketTimeoutException.class); + assertThat(stalledEx.getCause().getMessage()) + .isEqualTo("Timed out waiting for OAuth authorization callback."); + assertThat(stalledSocket.get().isClosed()).isTrue(); + } finally { + releaseStalledClient.countDown(); + if (stalledClientFuture.get() != null) { + stalledClientFuture.get().get(5, TimeUnit.SECONDS); + } + } + AtomicReference rejectedThenTimedOutSocket = new AtomicReference<>(); + BigQueryJdbcRuntimeException rejectedTimeoutEx = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + null, + null, + capturingSocketSupplier(rejectedThenTimedOutSocket), + authUri -> { + URI redirectUri = + URI.create(parseQueryParams(authUri.getRawQuery()).get("redirect_uri")); + try (Socket probe = + new Socket(redirectUri.getHost(), redirectUri.getPort())) { + probe + .getOutputStream() + .write( + callbackGetRequest(redirectUri, "/?state=wrong") + .getBytes(StandardCharsets.US_ASCII)); + probe.getOutputStream().flush(); + } + }, + 250, + 250)); + assertThat(rejectedTimeoutEx.getCause()).isInstanceOf(SocketTimeoutException.class); + assertThat(rejectedTimeoutEx.getCause().getMessage()) + .isEqualTo( + "Timed out waiting for OAuth authorization callback. Last rejected callback request: " + + "Missing or invalid state parameter in OAuth callback."); + assertThat(rejectedThenTimedOutSocket.get().isClosed()).isTrue(); + } + + @Test + public void testUserAuthCallback_rejectsOversizedTruncatedAndMalformedRequestLines() + throws Exception { + StringBuilder oversizedQuery = + new StringBuilder(BigQueryJdbcOAuthCallbackServer.MAX_HTTP_REQUEST_LINE_BYTES + 256); + oversizedQuery.append("GET /?pad="); + for (int i = 0; i < BigQueryJdbcOAuthCallbackServer.MAX_HTTP_REQUEST_LINE_BYTES; i++) { + oversizedQuery.append('a'); + } + oversizedQuery.append(" HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"); + + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> oversizedQuery.toString(), + false, + "OAuth callback HTTP request line exceeded maximum length."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "G\rET /?code=abc HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", + false, + "Invalid bare CR in OAuth callback HTTP request line."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "GET /\r\n\r\n", + false, + "Invalid HTTP request line on OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "POST /?code=abc HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", + false, + "Invalid HTTP request line on OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "GET ?code=abc HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", + false, + "Invalid HTTP request line on OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "GET /?code=abc HTTP/2.0\r\nHost: 127.0.0.1\r\n\r\n", + false, + "Invalid HTTP request line on OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + "GET http://example.com/?code=abc HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", + false, + "Invalid HTTP request line on OAuth callback."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> callbackGetRequest(redirectUri, "//example.com/?code=abc"), + false, + "Unexpected URI format in OAuth callback request."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> callbackGetRequest(redirectUri, "/?code=abc#frag"), + false, + "Unexpected URI format in OAuth callback request."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> + callbackGetRequest(redirectUri, "/?state=%ZZ&code=unlogged_token_val"), + false, + "Malformed URI in OAuth callback request."); + assertUnverifiedCallbackIgnoredUntilTimeout( + (redirectUri, authParams) -> "GET /?code=incomplete", + true, + "Incomplete OAuth callback HTTP request line."); + } + + @Test + public void testUserAuthFlow_failsFastWhenDesktopBrowseUnsupported() throws Exception { + Map authProperties = defaultUserAuthProperties(); + + try (MockedStatic mockedGraphics = + Mockito.mockStatic(GraphicsEnvironment.class); + MockedStatic mockedDesktop = Mockito.mockStatic(Desktop.class)) { + Desktop desktop = Mockito.mock(Desktop.class); + + mockedGraphics.when(GraphicsEnvironment::isHeadless).thenReturn(true); + assertThat(BigQueryJdbcOAuthUtility.isDesktopBrowseSupported()).isFalse(); + + mockedGraphics.when(GraphicsEnvironment::isHeadless).thenReturn(false); + mockedDesktop.when(Desktop::isDesktopSupported).thenReturn(false); + assertThat(BigQueryJdbcOAuthUtility.isDesktopBrowseSupported()).isFalse(); + + mockedDesktop.when(Desktop::isDesktopSupported).thenReturn(true); + mockedDesktop.when(Desktop::getDesktop).thenReturn(desktop); + Mockito.when(desktop.isSupported(Desktop.Action.BROWSE)).thenReturn(false); + assertThat(BigQueryJdbcOAuthUtility.isDesktopBrowseSupported()).isFalse(); + + BigQueryJdbcRuntimeException ex = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getCredentials( + authProperties, Collections.emptyMap(), false, null, null)); + assertThat(ex.getMessage()).isEqualTo("User auth only supported in desktop environments"); + + Mockito.when(desktop.isSupported(Desktop.Action.BROWSE)).thenReturn(true); + assertThat(BigQueryJdbcOAuthUtility.isDesktopBrowseSupported()).isTrue(); + + AtomicReference> capturedTokenParams = new AtomicReference<>(); + HttpTransportFactory transportFactory = + createMockTokenTransport(capturedTokenParams, null, null); + AtomicReference capturedAuthScope = new AtomicReference<>(); + AtomicReference> callbackResponseFuture = new AtomicReference<>(); + Mockito.doAnswer( + invocation -> { + URI authUri = invocation.getArgument(0); + Map params = parseQueryParams(authUri.getRawQuery()); + capturedAuthScope.set(params.get("scope")); + URI redirectUri = URI.create(params.get("redirect_uri")); + callbackResponseFuture.set( + runAsyncClient( + () -> + sendHttpRequest( + redirectUri, + callbackGetRequest( + redirectUri, + "/?state=" + + params.get("state") + + "&code=desktop_browse_code")))); + return null; + }) + .when(desktop) + .browse(Mockito.any(URI.class)); + + GoogleCredentials credentials = + BigQueryJdbcOAuthUtility.getCredentials( + authProperties, Collections.emptyMap(), false, transportFactory, null); + assertThat(credentials).isInstanceOf(UserCredentials.class); + assertThat(credentials.getUniverseDomain()).isEqualTo("googleapis.com"); + assertThat(capturedAuthScope.get()).isEqualTo("https://www.googleapis.com/auth/bigquery"); + assertThat(capturedTokenParams.get().get("code")).isEqualTo("desktop_browse_code"); + assertValidHttpResponse( + callbackResponseFuture.get().get(5, TimeUnit.SECONDS), "HTTP/1.1 200 OK"); + + GoogleCredentials driveCredentials = + BigQueryJdbcOAuthUtility.getCredentials( + authProperties, Collections.emptyMap(), true, transportFactory, null); + assertThat(driveCredentials).isInstanceOf(UserCredentials.class); + assertThat(capturedAuthScope.get()) + .isEqualTo( + "https://www.googleapis.com/auth/bigquery" + + " https://www.googleapis.com/auth/drive.readonly"); + assertValidHttpResponse( + callbackResponseFuture.get().get(5, TimeUnit.SECONDS), "HTTP/1.1 200 OK"); + } + } + + @FunctionalInterface + private interface CallbackRequestBuilder { + String build(URI redirectUri, Map authQueryParams); + } + + private static final class SingleAcceptLoopbackServerSocket extends ServerSocket { + private boolean acceptedFirstConnection; + + private SingleAcceptLoopbackServerSocket() throws IOException { + super(0, 8, InetAddress.getByAddress(new byte[] {127, 0, 0, 1})); + } + + @Override + public Socket accept() throws IOException { + if (!acceptedFirstConnection) { + acceptedFirstConnection = true; + return super.accept(); + } + throw new SocketTimeoutException("Simulated accept timeout after first connection"); + } + } + + private static Map defaultUserAuthProperties() { + return BigQueryJdbcOAuthUtility.parseOAuthProperties( + DataSource.fromUrl(getUriOAuthUserAccount().toString()), null); + } + + private static BigQueryJdbcOAuthCallbackServer.ServerSocketSupplier capturingSocketSupplier( + AtomicReference socketRef) { + return () -> { + ServerSocket socket = BigQueryJdbcOAuthCallbackServer.openLoopbackServerSocket(); + socketRef.set(socket); + return socket; + }; + } + + private static String callbackGetRequest(URI redirectUri, String target) { + return "GET " + + target + + " HTTP/1.1\r\nHost: " + + redirectUri.getHost() + + ":" + + redirectUri.getPort() + + "\r\n\r\n"; + } + + private static String computeS256Challenge(String verifier) throws NoSuchAlgorithmException { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + MessageDigest.getInstance("SHA-256") + .digest(verifier.getBytes(StandardCharsets.US_ASCII))); + } + + private static void assertTerminalCallbackAbortsImmediately( + CallbackRequestBuilder requestBuilder, String expectedExactMessage) throws Exception { + Map authProperties = defaultUserAuthProperties(); + AtomicInteger tokenCalls = new AtomicInteger(); + HttpTransportFactory transportFactory = + createMockTokenTransport(new AtomicReference<>(), tokenCalls, null); + AtomicReference capturedSocket = new AtomicReference<>(); + AtomicReference> rawResponseFuture = new AtomicReference<>(); + + BigQueryJdbcRuntimeException ex = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + transportFactory, + null, + capturingSocketSupplier(capturedSocket), + authUri -> { + Map params = parseQueryParams(authUri.getRawQuery()); + URI redirectUri = URI.create(params.get("redirect_uri")); + String rawRequest = requestBuilder.build(redirectUri, params); + rawResponseFuture.set( + runAsyncClient(() -> sendHttpRequest(redirectUri, rawRequest))); + }, + 5000, + 2000)); + + assertThat(ex.getMessage()).isEqualTo(expectedExactMessage); + assertThat(ex.getCause()).isNull(); + assertThat(tokenCalls.get()).isEqualTo(0); + assertValidHttpResponse( + rawResponseFuture.get().get(5, TimeUnit.SECONDS), "HTTP/1.1 400 Bad Request"); + assertThat(capturedSocket.get().isClosed()).isTrue(); + } + + private static void assertUnverifiedCallbackIgnoredUntilTimeout( + CallbackRequestBuilder requestBuilder, + boolean shutdownOutputAfterWrite, + String expectedRejectedReason) + throws Exception { + Map authProperties = defaultUserAuthProperties(); + AtomicInteger tokenCalls = new AtomicInteger(); + HttpTransportFactory transportFactory = + createMockTokenTransport(new AtomicReference<>(), tokenCalls, null); + AtomicReference capturedSocket = new AtomicReference<>(); + AtomicReference> rawResponseFuture = new AtomicReference<>(); + + BigQueryJdbcRuntimeException ex = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcOAuthUtility.getGoogleUserAccountCredentials( + authProperties, + Collections.emptyMap(), + false, + transportFactory, + null, + () -> { + ServerSocket socket = new SingleAcceptLoopbackServerSocket(); + capturedSocket.set(socket); + return socket; + }, + authUri -> { + Map params = parseQueryParams(authUri.getRawQuery()); + URI redirectUri = URI.create(params.get("redirect_uri")); + String rawRequest = requestBuilder.build(redirectUri, params); + rawResponseFuture.set( + runAsyncClient( + () -> { + try (Socket socket = + new Socket(redirectUri.getHost(), redirectUri.getPort())) { + socket.setSoTimeout(3000); + OutputStream out = socket.getOutputStream(); + out.write(rawRequest.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + if (shutdownOutputAfterWrite) { + socket.shutdownOutput(); + } + return readUtf8Stream(socket.getInputStream()); + } + })); + }, + 5000, + 2000)); + + String expectedTimeoutMessage = + "Timed out waiting for OAuth authorization callback. Last rejected callback request: " + + expectedRejectedReason; + assertThat(ex.getMessage()) + .isEqualTo( + "Failed to establish connection using User Account authentication\n" + + expectedTimeoutMessage); + assertThat(ex.getCause()).isInstanceOf(SocketTimeoutException.class); + assertThat(ex.getCause().getMessage()).isEqualTo(expectedTimeoutMessage); + assertThat(tokenCalls.get()).isEqualTo(0); + assertValidHttpResponse( + rawResponseFuture.get().get(5, TimeUnit.SECONDS), "HTTP/1.1 400 Bad Request"); + assertThat(capturedSocket.get().isClosed()).isTrue(); + } + + @FunctionalInterface + private interface ThrowingSupplier { + T get() throws Exception; + } + + private static CompletableFuture runAsyncClient(ThrowingSupplier action) { + CompletableFuture future = new CompletableFuture<>(); + Thread thread = + new Thread( + () -> { + try { + future.complete(action.get()); + } catch (Throwable t) { + future.completeExceptionally(t); + } + }); + thread.setDaemon(true); + thread.start(); + return future; + } + + private static HttpTransportFactory createMockTokenTransport( + AtomicReference> capturedParams, + AtomicInteger callCount, + Runnable beforeExchangeHook) { + MockHttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest(url) { + @Override + public LowLevelHttpResponse execute() throws IOException { + if (beforeExchangeHook != null) { + beforeExchangeHook.run(); + } + if (callCount != null) { + callCount.incrementAndGet(); + } + capturedParams.set(parseQueryParams(getContentAsString())); + return new MockLowLevelHttpResponse() + .setStatusCode(200) + .setContentType(Json.MEDIA_TYPE) + .setContent( + "{\"access_token\":\"mock_access_token\"," + + "\"refresh_token\":\"mock_refresh_token\"," + + "\"expires_in\":3600," + + "\"token_type\":\"Bearer\"}"); + } + }; + } + }; + return () -> transport; + } + + private static Map parseQueryParams(String rawQuery) throws IOException { + Map params = new HashMap<>(); + if (rawQuery == null || rawQuery.isEmpty()) { + return params; + } + for (String pair : rawQuery.split("&")) { + String[] kv = pair.split("=", 2); + String key = URLDecoder.decode(kv[0], StandardCharsets.UTF_8.name()); + String value = kv.length > 1 ? URLDecoder.decode(kv[1], StandardCharsets.UTF_8.name()) : ""; + params.put(key, value); + } + return params; + } + + private static String sendHttpRequest(URI redirectUri, String rawRequest) throws IOException { + try (Socket socket = new Socket(redirectUri.getHost(), redirectUri.getPort())) { + socket.setSoTimeout(3000); + OutputStream out = socket.getOutputStream(); + out.write(rawRequest.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + return readUtf8Stream(socket.getInputStream()); + } + } + + private static String readUtf8Stream(InputStream in) throws IOException { + ByteArrayOutputStream responseBytes = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int n; + while ((n = in.read(buf)) != -1) { + responseBytes.write(buf, 0, n); + } + return new String(responseBytes.toByteArray(), StandardCharsets.UTF_8); + } + + private static void assertValidHttpResponse(String rawResponse, String expectedStatusLine) { + assertThat(rawResponse).startsWith(expectedStatusLine + "\r\n"); + int headerEnd = rawResponse.indexOf("\r\n\r\n"); + assertThat(headerEnd).isGreaterThan(0); + String headers = rawResponse.substring(0, headerEnd) + "\r\n"; + String body = rawResponse.substring(headerEnd + 4); + int expectedLength = body.getBytes(StandardCharsets.UTF_8).length; + assertThat(headers).contains("\r\nContent-Length: " + expectedLength + "\r\n"); + assertThat(headers).contains("\r\nCache-Control: no-store\r\n"); + assertThat(headers).contains("\r\nX-Content-Type-Options: nosniff\r\n"); + assertThat(headers).contains("\r\nContent-Security-Policy: default-src 'none'\r\n"); + assertThat(headers).contains("\r\nConnection: close\r\n"); + } + + @Test + public void testServiceAccountJsonNeverOverriddenByEnvOrExplicitUniverseDomain() + throws Exception { + JsonObject saJson = new JsonObject(); + saJson.addProperty("type", "service_account"); + saJson.addProperty("project_id", "custom-universe-project"); + saJson.addProperty("private_key_id", "key-id-1"); + saJson.addProperty("private_key", fake_pkcs8_key); + saJson.addProperty("client_email", "sa@custom-universe-project.iam.gserviceaccount.com"); + saJson.addProperty("client_id", "123456"); + saJson.addProperty("universe_domain", "custom-universe.example.com"); + + Path tempKeyFile = Files.createTempFile("custom-universe-sa-", ".json"); + try { + Files.write(tempKeyFile, saJson.toString().getBytes(StandardCharsets.UTF_8)); + String url = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=custom-universe-project;OAuthType=0;OAuthPvtKeyPath=" + + tempKeyFile; + DataSource ds = DataSource.fromUrl(url); + Map authProps = BigQueryJdbcOAuthUtility.parseOAuthProperties(ds, null); + + // 1. Omitted universeDomain (even when GOOGLE_CLOUD_UNIVERSE_DOMAIN is set to another domain) + // must NOT overwrite a JSON credential's parsed universe_domain. + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil + .when(BigQueryJdbcUrlUtility::getEnvUniverseDomain) + .thenReturn("other-universe.example.com"); + GoogleCredentials preserved = + BigQueryJdbcOAuthUtility.getCredentials( + authProps, Collections.emptyMap(), false, null, null); + assertEquals("custom-universe.example.com", preserved.getUniverseDomain()); + } + + // 2. Explicit universeDomain in overrideProperties also does NOT override JSON credential. + Map explicitOverrides = + Collections.singletonMap( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, + "explicit-universe.example.com"); + GoogleCredentials overridden = + BigQueryJdbcOAuthUtility.getCredentials(authProps, explicitOverrides, false, null, null); + assertEquals("custom-universe.example.com", overridden.getUniverseDomain()); + } finally { + Files.deleteIfExists(tempKeyFile); + } + } + + @Test + public void testNonJsonCredentialsIgnoreEnvUniverseDomainAndUseExplicitOnly() throws Exception { + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil + .when(BigQueryJdbcUrlUtility::getEnvUniverseDomain) + .thenReturn("custom-universe.example.com"); + + // PKCS#8 Service Account + Map saProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties( + DataSource.fromUrl(getUriOAuthServiceAccount().toString()), null); + GoogleCredentials saCreds = + BigQueryJdbcOAuthUtility.getCredentials( + saProps, Collections.emptyMap(), false, null, null); + assertEquals("googleapis.com", saCreds.getUniverseDomain()); + + // Pre-generated Access Token + Map accessProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties( + DataSource.fromUrl(getUriOAuthToken().toString()), null); + GoogleCredentials accessCreds = + BigQueryJdbcOAuthUtility.getCredentials( + accessProps, Collections.emptyMap(), false, null, null); + assertEquals("googleapis.com", accessCreds.getUniverseDomain()); + + // Pre-generated Refresh Token + Map refreshProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties( + DataSource.fromUrl( + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=MyProject;OAuthType=2;OAuthRefreshToken=rt;" + + "OAuthClientId=cid;OAuthClientSecret=csecret;"), + null); + GoogleCredentials refreshCreds = + BigQueryJdbcOAuthUtility.getCredentials( + refreshProps, Collections.emptyMap(), false, null, null); + assertEquals("googleapis.com", refreshCreds.getUniverseDomain()); + + // User Account (OAuthType=1) + Map userProps = defaultUserAuthProperties(); + HttpTransportFactory userTransport = + createMockTokenTransport(new AtomicReference<>(), null, null); + UserAuthorizer userAuthorizer = + BigQueryJdbcOAuthUtility.getUserAuthorizer( + userProps, + Collections.emptyMap(), + false, + USER_AUTH_CALLBACK_URI, + userTransport, + null); + UserCredentials userCreds = + BigQueryJdbcOAuthUtility.getCredentialsFromCode( + userAuthorizer, "auth_code", Collections.emptyMap(), userTransport, null); + assertEquals("googleapis.com", userCreds.getUniverseDomain()); + + // Explicit overrideProperties applies to non-JSON credentials + Map explicitOverrides = + Collections.singletonMap( + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, + "explicit-universe.example.com"); + assertEquals( + "explicit-universe.example.com", + BigQueryJdbcOAuthUtility.getCredentials(saProps, explicitOverrides, false, null, null) + .getUniverseDomain()); + assertEquals( + "explicit-universe.example.com", + BigQueryJdbcOAuthUtility.getCredentialsFromCode( + userAuthorizer, "auth_code", explicitOverrides, userTransport, null) + .getUniverseDomain()); + } + } + + @Test + public void testByoidPropertyCredentialsDeriveStsTokenUriFromUniverseDomain() throws Exception { + String baseByoidUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;OAuthType=4;ProjectId=p;" + + "BYOID_AudienceUri=//iam.googleapis.com/locations/global/workforcePools/pool/providers/prov;" + + "BYOID_CredentialSource={\"file\":\"/tmp/token.txt\"};"; + + // 1. Explicit universeDomain in URL with BYOID_TokenUri omitted + DataSource explicitUniverseDomainDs = + DataSource.fromUrl(baseByoidUrl + "universeDomain=custom-universe.example.com;"); + Map explicitAuthProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties(explicitUniverseDomainDs, null); + assertEquals( + "https://sts.custom-universe.example.com/v1/token", + explicitAuthProps.get(BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME)); + GoogleCredentials explicitByoidCreds = + BigQueryJdbcOAuthUtility.getCredentials( + explicitAuthProps, Collections.emptyMap(), false, null, null); + assertThat(explicitByoidCreds).isInstanceOf(ExternalAccountCredentials.class); + assertEquals( + "https://sts.custom-universe.example.com/v1/token", + ((ExternalAccountCredentials) explicitByoidCreds).getTokenUrl()); + assertEquals("custom-universe.example.com", explicitByoidCreds.getUniverseDomain()); + + // 2. GOOGLE_CLOUD_UNIVERSE_DOMAIN env var does NOT affect synthesized BYOID credentials when + // universeDomain and BYOID_TokenUri are omitted + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil + .when(BigQueryJdbcUrlUtility::getEnvUniverseDomain) + .thenReturn("env-universe.example.com"); + DataSource envUniverseDomainDs = DataSource.fromUrl(baseByoidUrl); + Map envAuthProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties(envUniverseDomainDs, null); + GoogleCredentials envByoidCreds = + BigQueryJdbcOAuthUtility.getCredentials( + envAuthProps, Collections.emptyMap(), false, null, null); + assertEquals( + "https://sts.googleapis.com/v1/token", + ((ExternalAccountCredentials) envByoidCreds).getTokenUrl()); + assertEquals("googleapis.com", envByoidCreds.getUniverseDomain()); + } + + // 3. Explicit BYOID_TokenUri in URL overrides universeDomain derivation + DataSource customTokenDs = + DataSource.fromUrl( + baseByoidUrl + + "universeDomain=custom-universe.example.com;" + + "BYOID_TokenUri=https://custom-sts.example.com/v1/token;"); + Map customTokenAuthProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties(customTokenDs, null); + assertEquals( + "https://custom-sts.example.com/v1/token", + customTokenAuthProps.get(BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME)); + GoogleCredentials customTokenCreds = + BigQueryJdbcOAuthUtility.getCredentials( + customTokenAuthProps, Collections.emptyMap(), false, null, null); + assertEquals( + "https://custom-sts.example.com/v1/token", + ((ExternalAccountCredentials) customTokenCreds).getTokenUrl()); + assertEquals("custom-universe.example.com", customTokenCreds.getUniverseDomain()); + + // 4. Default GDU (no universeDomain, no env var, no BYOID_TokenUri) resolves sts.googleapis.com + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(null); + DataSource defaultGduDs = DataSource.fromUrl(baseByoidUrl); + Map defaultGduProps = + BigQueryJdbcOAuthUtility.parseOAuthProperties(defaultGduDs, null); + GoogleCredentials defaultGduCreds = + BigQueryJdbcOAuthUtility.getCredentials( + defaultGduProps, Collections.emptyMap(), false, null, null); + assertEquals( + "https://sts.googleapis.com/v1/token", + ((ExternalAccountCredentials) defaultGduCreds).getTokenUrl()); + assertEquals("googleapis.com", defaultGduCreds.getUniverseDomain()); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java index e1577e6010fd..9241c88d3206 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java @@ -19,7 +19,9 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; +import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.logging.Logging; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Tracer; @@ -141,4 +143,36 @@ public void testGetOpenTelemetry_withUseGlobalOTel_returnsGlobal() { assertThat(result).isSameInstanceAs(GlobalOpenTelemetry.get()); } + + @Test + public void testCreateLoggingClient_propagatesUniverseDomain() throws Exception { + mockedCredentials.close(); + try { + GoogleCredentials customCreds = + GoogleCredentials.newBuilder() + .setAccessToken(new AccessToken("test-token", null)) + .setUniverseDomain("custom-universe.example.com") + .build(); + try (Logging logging = + BigQueryJdbcOpenTelemetry.createLoggingClient( + true, null, null, "test-project", customCreds, null, "custom-universe.example.com")) { + assertThat(logging).isNotNull(); + assertThat(logging.getOptions().getUniverseDomain()) + .isEqualTo("custom-universe.example.com"); + } + + GoogleCredentials defaultCreds = + GoogleCredentials.newBuilder() + .setAccessToken(new AccessToken("test-token", null)) + .build(); + try (Logging defaultLogging = + BigQueryJdbcOpenTelemetry.createLoggingClient( + true, null, null, "test-project", defaultCreds, null, null)) { + assertThat(defaultLogging).isNotNull(); + assertThat(defaultLogging.getOptions().getUniverseDomain()).isNull(); + } + } finally { + mockedCredentials = Mockito.mockStatic(GoogleCredentials.class); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLoggerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLoggerTest.java index 82ca5e003767..e8481d8cfb62 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLoggerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLoggerTest.java @@ -17,21 +17,44 @@ package com.google.cloud.bigquery.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.cloud.bigquery.jdbc.utils.TestUtilities; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Scope; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; import java.util.logging.Formatter; +import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class BigQueryJdbcRootLoggerTest { + @AfterEach + public void tearDown() { + BigQueryJdbcMdc.clear(); + BigQueryJdbcRootLogger.resetForTest(); + } + @Test public void testGetFormatterFormat() { Formatter formatter = BigQueryJdbcRootLogger.getFormatter(); @@ -95,4 +118,161 @@ public void testFormatterWithOpenTelemetrySpan() { "[trace_id=00000000000000000000000000000001 span_id=0000000000000002] ")); } } + + @Test + public void testConcurrentConnectionsIsolateLogLevelsAndDirectories(@TempDir Path tempDir) + throws Exception { + Path dirShared = tempDir.resolve("shared"); + Path dirOther = tempDir.resolve("other"); + Path dirOff = tempDir.resolve("off"); + String connFinest = "aaaa1111-0000-0000-0000-000000000001"; + String connSevere = "bbbb2222-0000-0000-0000-000000000002"; + String connInfoOther = "cccc3333-0000-0000-0000-000000000003"; + String connOff = "dddd4444-0000-0000-0000-000000000004"; + + BigQueryJdbcRootLogger.registerConnection(connSevere, "1", dirShared.toString()); + BigQueryJdbcRootLogger.registerConnection(connFinest, "7", dirShared.toString()); + BigQueryJdbcRootLogger.registerConnection(connInfoOther, "3", dirOther.toString()); + BigQueryJdbcRootLogger.registerConnection(connOff, "0", dirOff.toString()); + + assertEquals(Level.FINEST, BigQueryJdbcRootLogger.getRootLogger().getLevel()); + assertEquals(2, countManagedFileHandlers()); + + BigQueryJdbcCustomLogger customLogger = + new BigQueryJdbcCustomLogger("com.google.cloud.bigquery.jdbc.IsolationTest"); + BigQueryJdbcResultSetLogger rsFinest = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, connFinest); + BigQueryJdbcResultSetLogger rsSevere = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, connSevere); + + ExecutorService pool = BigQueryJdbcMdc.newFixedThreadPool("IsolationPool", 2); + try { + try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.registerInstance(connFinest)) { + customLogger.finest("A-finest-msg"); + pool.submit(() -> customLogger.finer("A-async-finer-msg")).get(5, TimeUnit.SECONDS); + } + try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.registerInstance(connSevere)) { + customLogger.info("B-info-should-drop"); + customLogger.severe("B-severe-msg"); + rsFinest.finestTrace("next", "A-rs-interleaved-finest"); + rsSevere.fineTrace("next", "B-rs-fine-should-drop"); + } + try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.registerInstance(connInfoOther)) { + customLogger.fine("C-fine-should-drop"); + customLogger.info("C-info-msg"); + } + try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.registerInstance(connOff)) { + customLogger.severe("D-off-should-drop"); + } + } finally { + pool.shutdownNow(); + } + + assertFalse(Files.exists(dirOff)); + String logA = readConnectionLog(dirShared, "aaaa"); + assertTrue(logA.contains("A-finest-msg") && logA.contains("A-async-finer-msg")); + assertTrue(logA.contains("A-rs-interleaved-finest")); + assertFalse(logA.contains("B-severe-msg") || logA.contains("C-info-msg")); + + String logB = readConnectionLog(dirShared, "bbbb"); + assertTrue(logB.contains("B-severe-msg")); + assertFalse(logB.contains("B-info-should-drop") || logB.contains("B-rs-fine-should-drop")); + assertFalse(logB.contains("A-finest-msg")); + + String logC = readConnectionLog(dirOther, "cccc"); + assertTrue(logC.contains("C-info-msg")); + assertFalse(logC.contains("C-fine-should-drop") || logC.contains("A-finest-msg")); + + BigQueryJdbcRootLogger.closeConnectionHandler(connSevere); + assertEquals(2, countManagedFileHandlers()); + try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.registerInstance(connFinest)) { + customLogger.finest("A-after-B-closed"); + } + assertTrue(readConnectionLog(dirShared, "aaaa").contains("A-after-B-closed")); + + BigQueryJdbcRootLogger.closeConnectionHandler(connFinest); + assertEquals(Level.INFO, BigQueryJdbcRootLogger.getRootLogger().getLevel()); + BigQueryJdbcRootLogger.closeConnectionHandler(connInfoOther); + BigQueryJdbcRootLogger.closeConnectionHandler(connOff); + assertEquals(Level.OFF, BigQueryJdbcRootLogger.getRootLogger().getLevel()); + assertEquals(0, countManagedFileHandlers()); + } + + @Test + public void testSecondConnectionWithLogLevelOffDoesNotSilenceActiveConnection( + @TempDir Path tempDir) throws Exception { + String verboseUrl = + new URIBuilder(TestUtilities.getBaseConnectionUrl()) + .append("OAuthType", 2) + .append("OAuthAccessToken", "RedactedToken") + .append("ProjectId", "test-project") + .append("LogLevel", "7") + .append("LogPath", tempDir.toString()) + .toString(); + String silentUrl = + new URIBuilder(TestUtilities.getBaseConnectionUrl()) + .append("OAuthType", 2) + .append("OAuthAccessToken", "RedactedToken") + .append("ProjectId", "test-project") + .append("LogLevel", "0") + .toString(); + + BigQueryDriver driver = new BigQueryDriver(); + try (Connection conn1 = driver.connect(verboseUrl, new Properties())) { + try (Connection conn2 = driver.connect(silentUrl, new Properties())) { + assertFalse(conn2.isClosed()); + } + conn1.getAutoCommit(); + String shortId = conn1.unwrap(BigQueryConnection.class).getConnectionId().substring(0, 4); + String log1 = readConnectionLog(tempDir, shortId); + assertTrue(log1.contains("Driver info :") && log1.contains("getAutoCommit")); + } + assertEquals(0, countManagedFileHandlers()); + } + + @Test + public void testPreConnectScopeRoutesToTargetDirectoryAndCleansUpOnFailure(@TempDir Path tempDir) + throws Exception { + Path activeDir = tempDir.resolve("active"); + Path failingDir = tempDir.resolve("failing"); + BigQueryJdbcRootLogger.registerConnection( + "eeee5555-0000-0000-0000-000000000005", "7", activeDir.toString()); + + BigQueryJdbcCustomLogger logger = + new BigQueryJdbcCustomLogger("com.google.cloud.bigquery.jdbc.PreConnectTest"); + try (BigQueryJdbcMdc.MdcCloseable pre = + BigQueryJdbcRootLogger.openPreConnectScope(Level.INFO, failingDir.toString())) { + logger.fine("preconnect-fine-should-drop"); + logger.warning("preconnect-url-warning"); + } + + assertEquals(1, countManagedFileHandlers()); + String globalFailingLog = + new String( + Files.readAllBytes(failingDir.resolve("BQ-JDBC-GLOBAL.log")), StandardCharsets.UTF_8); + assertTrue(globalFailingLog.contains("preconnect-url-warning")); + assertFalse(globalFailingLog.contains("preconnect-fine-should-drop")); + assertFalse(Files.exists(activeDir.resolve("BQ-JDBC-GLOBAL.log"))); + } + + private static int countManagedFileHandlers() { + int count = 0; + for (Handler h : BigQueryJdbcRootLogger.getRootLogger().getHandlers()) { + if (h instanceof PerConnectionFileHandler) { + count++; + } + } + return count; + } + + private static String readConnectionLog(Path dir, String shortPrefix) throws IOException { + try (Stream stream = Files.list(dir)) { + List matches = + stream + .filter(p -> p.getFileName().toString().endsWith("-" + shortPrefix + ".log")) + .collect(Collectors.toList()); + assertEquals(1, matches.size()); + return new String(Files.readAllBytes(matches.get(0)), StandardCharsets.UTF_8); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java index daf938657196..1ccbe13bbe4d 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java @@ -30,7 +30,10 @@ import java.util.Collections; import java.util.Map; import java.util.Properties; +import java.util.logging.LogRecord; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; public class BigQueryJdbcUrlUtilityTest extends BigQueryJdbcLoggingBaseTest { @@ -318,20 +321,22 @@ public void testParseDefaultDataset_threeTierPcntNamespace() { } @Test - public void testParseDefaultDataset_tpcProject() { - DatasetId datasetId = BigQueryJdbcUrlUtility.parseDefaultDataset("tpc:my-project:my_dataset"); + public void testParseDefaultDataset_universeDomainProject() { + DatasetId datasetId = + BigQueryJdbcUrlUtility.parseDefaultDataset("custom-universe:my-project:my_dataset"); assertNotNull(datasetId); assertEquals("my_dataset", datasetId.getDataset()); - assertEquals("tpc:my-project", datasetId.getProject()); + assertEquals("custom-universe:my-project", datasetId.getProject()); } @Test - public void testParseDefaultDataset_tpcProject_threeTierPcntNamespace() { + public void testParseDefaultDataset_universeDomainProject_threeTierPcntNamespace() { DatasetId datasetId = - BigQueryJdbcUrlUtility.parseDefaultDataset("tpc:my-project:my-warehouse.my_namespace"); + BigQueryJdbcUrlUtility.parseDefaultDataset( + "custom-universe:my-project:my-warehouse.my_namespace"); assertNotNull(datasetId); assertEquals("my-warehouse.my_namespace", datasetId.getDataset()); - assertEquals("tpc:my-project", datasetId.getProject()); + assertEquals("custom-universe:my-project", datasetId.getProject()); } @Test @@ -344,7 +349,7 @@ public void testParseDefaultDataset_invalidFormats() { () -> BigQueryJdbcUrlUtility.parseDefaultDataset(":my_dataset")); assertThrows( BigQueryJdbcRuntimeException.class, - () -> BigQueryJdbcUrlUtility.parseDefaultDataset("tpc:my-project:")); + () -> BigQueryJdbcUrlUtility.parseDefaultDataset("custom-universe:my-project:")); assertThrows( BigQueryJdbcRuntimeException.class, () -> BigQueryJdbcUrlUtility.parseDefaultDataset(" : ")); @@ -413,4 +418,91 @@ public void testEnableGraphMetadataProperties() { assertThat(defaultDs.getEnableGraphMetadata()) .isEqualTo(BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GRAPH_METADATA_VALUE); } + + @ParameterizedTest + @ValueSource( + strings = { + "OAuthAccessToken", + "OAuthRefreshToken", + "OAuthPvtKey", + "OAuthClientSecret", + "OAuthP12Password", + "ProxyPwd", + "ProxyUid", + "SSLTrustStorePwd", + "gcpTelemetryCredentials", + "BYOID_CredentialSource", + "CustomSecretProperty" + }) + public void testAppendPropertiesToURL_masksSensitivePropertiesAtFinest(String secretKey) { + capturedLogs.clear(); + String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; + Properties props = new Properties(); + String rawSecret = "super-secret-value-98765"; + props.setProperty(secretKey, rawSecret); + props.setProperty("ProjectId", "visible-project"); + + String updated = BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "TestCaller", props); + + assertThat(updated).contains(secretKey + "=" + rawSecret); + assertThat(assertLogContains("Appending " + secretKey + " with value ***** to URL")).isTrue(); + assertThat(assertLogContains("Appending ProjectId with value visible-project to URL")).isTrue(); + assertThat(assertLogContains(rawSecret)).isFalse(); + } + + @Test + public void testAppendPropertiesToURL_handlesNullAndNonStringProperties() { + String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; + assertThat(BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", null)) + .isEqualTo(baseUrl); + assertThat(BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", new Properties())) + .isEqualTo(baseUrl); + + Properties nonStringProps = new Properties(); + nonStringProps.put("MaxResults", 500); + nonStringProps.put("OAuthAccessToken", 123456); + capturedLogs.clear(); + + String updated = + BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", nonStringProps); + assertThat(updated).contains("MaxResults=500"); + assertThat(updated).contains("OAuthAccessToken=123456"); + assertThat(assertLogContains("Appending MaxResults with value 500 to URL")).isTrue(); + assertThat(assertLogContains("Appending OAuthAccessToken with value ***** to URL")).isTrue(); + assertThat(assertLogContains("123456")).isFalse(); + assertThat(BigQueryConnection.maskPropertyValue(null, "secret")).isEqualTo("*****"); + assertThat(BigQueryConnection.maskPropertyValue("ProjectId", null)).isNull(); + } + + @Test + public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { + assertThat(BigQueryConnection.sanitizeForLog(null)).isNull(); + String clean = "my-clean-project-123"; + assertThat(BigQueryConnection.sanitizeForLog(clean)).isSameInstanceAs(clean); + assertThat(BigQueryConnection.sanitizeForLog("proj\r\nFORGED\t\u007f")) + .isEqualTo("proj??FORGED??"); + + // SAFE_TO_LOG_PROPERTIES is case-insensitive and strips ASCII control chars (< 0x20, 0x7F) + assertThat(BigQueryConnection.maskPropertyValue("projectid", "proj\nline2")) + .isEqualTo("proj?line2"); + assertThat(BigQueryConnection.maskPropertyValue("oauthaccesstoken", "tok\nen")) + .isEqualTo("*****"); + + capturedLogs.clear(); + String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; + Properties props = new Properties(); + props.setProperty("ProjectId", "proj\r\nFAKE_LOG_ENTRY"); + props.setProperty("Custom\nKey", "secret-val"); + + String updated = BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", props); + + assertThat(updated).contains("ProjectId=proj%0D%0AFAKE_LOG_ENTRY"); + assertThat(assertLogContains("Appending ProjectId with value proj??FAKE_LOG_ENTRY to URL")) + .isTrue(); + assertThat(assertLogContains("Appending Custom?Key with value ***** to URL")).isTrue(); + for (LogRecord rec : capturedLogs) { + assertThat(rec.getMessage()).doesNotContain("\n"); + assertThat(rec.getMessage()).doesNotContain("\r"); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJsonResultSetTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJsonResultSetTest.java index c47e58112e05..a28423adcb3d 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJsonResultSetTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJsonResultSetTest.java @@ -21,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.Field.Mode; @@ -34,6 +36,8 @@ import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.jdbc.rules.TimeZoneRule; +import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import com.google.common.io.CharStreams; @@ -73,6 +77,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.MockedStatic; public class BigQueryJsonResultSetTest { @@ -914,4 +919,39 @@ public void testTimestampPicosAccessorsAcrossJvmZones(String jvmZone) throws SQL TimeZone.setDefault(originalDefault); } } + + @Test + public void testGetMetaData_recordsFeatureOncePerResultSet() throws SQLException { + // Called inside row loops by many tools; the adoption signal must be recorded once. + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + bigQueryJsonResultSet.getMetaData(); + bigQueryJsonResultSet.getMetaData(); + telemetry.verify( + () -> + TelemetryManager.recordFeatureUsage( + DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, + "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"), + times(1)); + } + } + + @Test + public void testGetMetaData_recordsEvenWhenOwningStatementIsInternal() throws SQLException { + // ResultSet.getMetaData() is only ever a user call, even on result sets produced by + // driver-internal statements (e.g. DatabaseMetaData.getExportedKeys), so it must count. + BigQueryStatement internalStatement = mock(BigQueryStatement.class); + doReturn(true).when(internalStatement).isInternal(); + BigQueryJsonResultSet internalResultSet = + BigQueryJsonResultSet.of(QUERY_SCHEMA, 1L, buffer, internalStatement, new Future[0]); + assertThat(internalResultSet.getStatement()).isNull(); + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + internalResultSet.getMetaData(); + telemetry.verify( + () -> + TelemetryManager.recordFeatureUsage( + DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, + "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"), + times(1)); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java index 03ddee8535a6..42665be737f2 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPooledConnectionTest.java @@ -20,24 +20,81 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import com.google.cloud.bigquery.BigQuery; +import com.google.cloud.bigquery.BigQueryException; +import com.google.cloud.bigquery.Job; +import com.google.cloud.bigquery.JobInfo; +import com.google.cloud.bigquery.JobStatistics.QueryStatistics.StatementType; +import com.google.cloud.bigquery.JobStatistics.SessionInfo; +import com.google.cloud.bigquery.QueryJobConfiguration; +import com.google.cloud.bigquery.Schema; +import com.google.cloud.bigquery.TableResult; +import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import java.io.IOException; -import java.sql.*; +import java.lang.reflect.Proxy; +import java.sql.CallableStatement; +import java.sql.ClientInfoStatus; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.Savepoint; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; public class BigQueryPooledConnectionTest { private BigQueryConnection bigQueryConnection; private static final Long LISTENER_POOL_SIZE = 10L; + private static final Long CONNECTION_POOL_SIZE = 10L; + + private static URIBuilder sessionUri() { + return BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "test-project") + .append("EnableSession", 1); + } @BeforeEach public void setUp() throws IOException, SQLException { @@ -91,24 +148,24 @@ public void testReuseConnectionAfterClose() throws SQLException { public void testAddConnectionListener() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); - TestConnectionListener listner = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listner); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); - assertTrue(pooledConnection.isListenerPooled(listner)); + assertTrue(pooledConnection.isListenerPooled(listener)); } @Test public void testRemoveConnectionListener() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); - TestConnectionListener listner = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listner); - assertEquals(0, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); - assertTrue(pooledConnection.isListenerPooled(listner)); - pooledConnection.removeConnectionEventListener(listner); - assertFalse(pooledConnection.isListenerPooled(listner)); + assertTrue(pooledConnection.isListenerPooled(listener)); + pooledConnection.removeConnectionEventListener(listener); + assertFalse(pooledConnection.isListenerPooled(listener)); } @Test @@ -121,21 +178,25 @@ public void testConnectionHandleClosedByConnection() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - TestConnectionListener listner = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listner); - assertEquals(0, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); connection.close(); assertFalse(pooledConnection.inUse()); - assertEquals(1, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + assertTrue(pooledConnection.isListenerPooled(listener)); - assertTrue(pooledConnection.isListenerPooled(listner)); + // Repeated close on the logical handle is a no-op and must not fire duplicate events. + connection.close(); + assertEquals(1, listener.getConnectionClosedCount()); } @Test - public void testConnectionHandleClosedByPooledConnection() throws SQLException { + public void testPhysicalClose_closesUnderlyingConnectionWithoutFiringClosedEvent() + throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); assertFalse(pooledConnection.inUse()); @@ -144,17 +205,21 @@ public void testConnectionHandleClosedByPooledConnection() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - TestConnectionListener listner = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listner); - assertEquals(0, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); pooledConnection.close(); assertFalse(pooledConnection.inUse()); - assertEquals(1, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + assertTrue(connection.isClosed()); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + assertFalse(pooledConnection.isListenerPooled(listener)); + verify(bigQueryConnection, times(1)).close(); - assertTrue(pooledConnection.isListenerPooled(listner)); + // Idempotent physical close and post-close checkout rejection. + pooledConnection.close(); + verify(bigQueryConnection, times(1)).close(); + assertThrows(BigQueryJdbcException.class, pooledConnection::getConnection); } @Test @@ -167,17 +232,19 @@ public void testFireConnectionError() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - TestConnectionListener listner = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listner); - assertEquals(0, listner.getConnectionClosedCount()); - assertEquals(0, listner.getConnectionErrorCount()); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); pooledConnection.fireConnectionError(new SQLException("test")); assertFalse(pooledConnection.inUse()); - assertEquals(0, listner.getConnectionClosedCount()); - assertEquals(1, listner.getConnectionErrorCount()); - - assertFalse(pooledConnection.isListenerPooled(listner)); + assertTrue(connection.isClosed()); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(1, listener.getConnectionErrorCount()); + assertFalse(pooledConnection.isListenerPooled(listener)); + verify(bigQueryConnection).close(); + assertThrows(BigQueryJdbcException.class, pooledConnection::getConnection); } @Test @@ -194,4 +261,1260 @@ public void testPooledGetMetaData_delegatesWithoutRecordingTelemetry() throws SQ never()); } } + + @Test + public void testLogicalClose_rollsBackActiveTransactionWithoutStartingNewOne() throws Exception { + try (BigQueryConnection realConn = new BigQueryConnection(sessionUri().toString())) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("driver_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + Connection handle = pooledConnection.getConnection(); + handle.setAutoCommit(false); + assertTrue(realConn.isTransactionStarted()); + assertFalse(realConn.getAutoCommit()); + + handle.close(); + + assertFalse(realConn.isTransactionStarted()); + assertTrue(realConn.getAutoCommit()); + assertNull(realConn.getSessionInfoConnectionProperty()); + + ArgumentCaptor jobCaptor = ArgumentCaptor.forClass(JobInfo.class); + verify(mockBigQuery, times(1)).create(jobCaptor.capture()); + QueryJobConfiguration rollbackConfig = jobCaptor.getValue().getConfiguration(); + assertEquals("ROLLBACK TRANSACTION;", rollbackConfig.getQuery()); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, atLeastOnce()).query(queryCaptor.capture()); + List executedQueries = queryCaptor.getAllValues(); + long beginCount = + executedQueries.stream() + .filter(cfg -> "BEGIN TRANSACTION;".equals(cfg.getQuery())) + .count(); + assertEquals(1L, beginCount, "Rollback on logical close must not start a second transaction"); + assertTrue( + executedQueries.stream() + .anyMatch(cfg -> "CALL BQ.ABORT_SESSION();".equals(cfg.getQuery()))); + assertFalse( + executedQueries.stream().anyMatch(cfg -> "COMMIT TRANSACTION;".equals(cfg.getQuery()))); + } + } + + @Test + public void testLogicalClose_abortsDriverCreatedSessionAndPreservesQueryProperties() + throws Exception { + String url = sessionUri().append("QueryProperties", "time_zone=America/Los_Angeles").toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenReturn(mock(TableResult.class)); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + Connection handle = pooledConnection.getConnection(); + + // Simulate a non-transactional query establishing a driver-managed session. + realConn.markSessionCreatedByDriver(); + realConn.initSessionInfo("driver_query_session_1"); + assertEquals( + "driver_query_session_1", realConn.getSessionInfoConnectionProperty().getValue()); + assertTrue(realConn.isSessionCreatedByDriver()); + + handle.close(); + + assertNull(realConn.getSessionInfoConnectionProperty()); + assertFalse(realConn.isSessionCreatedByDriver()); + assertTrue( + realConn.getQueryProperties().stream() + .anyMatch( + cp -> + "time_zone".equals(cp.getKey()) + && "America/Los_Angeles".equals(cp.getValue()))); + assertFalse( + realConn.getQueryProperties().stream() + .anyMatch(cp -> "session_id".equalsIgnoreCase(cp.getKey()))); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery).query(queryCaptor.capture()); + assertEquals("CALL BQ.ABORT_SESSION();", queryCaptor.getValue().getQuery()); + } + } + + @Test + public void testLogicalClose_preservesUserConfiguredSessionIdWhileRollingBackTransaction() + throws Exception { + String url = + sessionUri().append("QueryProperties", "session_id=caller_owned_session_77").toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("caller_owned_session_77"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + Connection handle = pooledConnection.getConnection(); + handle.setAutoCommit(false); + + handle.close(); + + assertFalse(realConn.isTransactionStarted()); + assertTrue(realConn.getAutoCommit()); + assertFalse(realConn.isSessionCreatedByDriver()); + assertNotNull(realConn.getSessionInfoConnectionProperty()); + assertEquals( + "caller_owned_session_77", realConn.getSessionInfoConnectionProperty().getValue()); + + ArgumentCaptor queryCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery, atLeastOnce()).query(queryCaptor.capture()); + assertFalse( + queryCaptor.getAllValues().stream() + .anyMatch(cfg -> "CALL BQ.ABORT_SESSION();".equals(cfg.getQuery()))); + } + } + + @Test + public void testLogicalClose_resetsClientInfoWarningsHoldabilityAndClosesOpenStatements() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + int defaultHoldability = realConn.getHoldability(); + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + Connection handle = pooledConnection.getConnection(); + + Statement stmt = handle.createStatement(); + PreparedStatement pstmt = handle.prepareStatement("SELECT 1"); + CallableStatement cstmt = handle.prepareCall("{call test_proc()}"); + assertTrue(Proxy.isProxyClass(stmt.getClass())); + assertTrue(Proxy.isProxyClass(handle.getMetaData().getClass())); + + handle.setClientInfo("ApplicationName", "BillingReport"); + realConn.sqlWarnings.add(new SQLWarning("sample warning")); + realConn.holdability = ResultSet.HOLD_CURSORS_OVER_COMMIT; + + assertFalse(stmt.isClosed()); + assertFalse(pstmt.isClosed()); + assertFalse(cstmt.isClosed()); + assertEquals(3, realConn.openStatements.size()); + + handle.close(); + + assertTrue(stmt.isClosed()); + assertTrue(pstmt.isClosed()); + assertTrue(cstmt.isClosed()); + assertTrue(realConn.openStatements.isEmpty()); + assertThrows(SQLException.class, () -> stmt.executeQuery("SELECT 1")); + assertTrue(realConn.getClientInfo().isEmpty()); + assertNull(realConn.getWarnings()); + assertEquals(defaultHoldability, realConn.getHoldability()); + } + } + + @Test + public void testClosedWrapper_rejectsSubsequentOperations() throws SQLException { + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); + Connection handle = pooledConnection.getConnection(); + assertTrue(handle.isWrapperFor(Connection.class)); + assertFalse(handle.isWrapperFor(null)); + assertSame(handle, handle.unwrap(Connection.class)); + assertThrows(BigQueryJdbcException.class, () -> handle.unwrap(null)); + + handle.close(); + + assertTrue(handle.isClosed()); + assertFalse(handle.isValid(5)); + assertThrows(BigQueryJdbcException.class, () -> handle.isValid(-1)); + assertFalse(handle.isWrapperFor(BigQueryConnection.class)); + + Properties props = new Properties(); + props.setProperty("ApplicationName", "TestSuite"); + Savepoint savepoint = mock(Savepoint.class); + Executor executor = Runnable::run; + + assertThrows(BigQueryJdbcException.class, handle::createStatement); + assertThrows( + BigQueryJdbcException.class, + () -> handle.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + assertThrows( + BigQueryJdbcException.class, + () -> + handle.createStatement( + ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, + ResultSet.CLOSE_CURSORS_AT_COMMIT)); + assertThrows(BigQueryJdbcException.class, () -> handle.prepareStatement("SELECT 1")); + assertThrows( + BigQueryJdbcException.class, + () -> + handle.prepareStatement( + "SELECT 1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + assertThrows( + BigQueryJdbcException.class, + () -> + handle.prepareStatement( + "SELECT 1", + ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, + ResultSet.CLOSE_CURSORS_AT_COMMIT)); + assertThrows( + BigQueryJdbcException.class, + () -> handle.prepareStatement("SELECT 1", Statement.NO_GENERATED_KEYS)); + assertThrows( + BigQueryJdbcException.class, () -> handle.prepareStatement("SELECT 1", new int[] {1})); + assertThrows( + BigQueryJdbcException.class, + () -> handle.prepareStatement("SELECT 1", new String[] {"col"})); + assertThrows(BigQueryJdbcException.class, () -> handle.prepareCall("{call p()}")); + assertThrows( + BigQueryJdbcException.class, + () -> + handle.prepareCall( + "{call p()}", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)); + assertThrows( + BigQueryJdbcException.class, + () -> + handle.prepareCall( + "{call p()}", + ResultSet.TYPE_FORWARD_ONLY, + ResultSet.CONCUR_READ_ONLY, + ResultSet.CLOSE_CURSORS_AT_COMMIT)); + assertThrows(BigQueryJdbcException.class, () -> handle.nativeSQL("SELECT 1")); + assertThrows(BigQueryJdbcException.class, () -> handle.setAutoCommit(false)); + assertThrows(BigQueryJdbcException.class, handle::getAutoCommit); + assertThrows(BigQueryJdbcException.class, handle::commit); + assertThrows(BigQueryJdbcException.class, handle::rollback); + assertThrows(BigQueryJdbcException.class, () -> handle.rollback(savepoint)); + assertThrows(BigQueryJdbcException.class, handle::getMetaData); + assertThrows(BigQueryJdbcException.class, () -> handle.setReadOnly(true)); + assertThrows(BigQueryJdbcException.class, handle::isReadOnly); + assertThrows(BigQueryJdbcException.class, () -> handle.setCatalog("cat")); + assertThrows(BigQueryJdbcException.class, handle::getCatalog); + assertThrows( + BigQueryJdbcException.class, + () -> handle.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE)); + assertThrows(BigQueryJdbcException.class, handle::getTransactionIsolation); + assertThrows(BigQueryJdbcException.class, handle::getWarnings); + assertThrows(BigQueryJdbcException.class, handle::clearWarnings); + assertThrows(BigQueryJdbcException.class, handle::getTypeMap); + assertThrows(BigQueryJdbcException.class, () -> handle.setTypeMap(Collections.emptyMap())); + assertThrows( + BigQueryJdbcException.class, + () -> handle.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT)); + assertThrows(BigQueryJdbcException.class, handle::getHoldability); + assertThrows(BigQueryJdbcException.class, handle::setSavepoint); + assertThrows(BigQueryJdbcException.class, () -> handle.setSavepoint("sp")); + assertThrows(BigQueryJdbcException.class, () -> handle.releaseSavepoint(savepoint)); + assertThrows(BigQueryJdbcException.class, handle::createClob); + assertThrows(BigQueryJdbcException.class, handle::createBlob); + assertThrows(BigQueryJdbcException.class, handle::createNClob); + assertThrows(BigQueryJdbcException.class, handle::createSQLXML); + SQLClientInfoException singleClientInfoEx = + assertThrows(SQLClientInfoException.class, () -> handle.setClientInfo("k", "v")); + assertEquals( + ClientInfoStatus.REASON_UNKNOWN, singleClientInfoEx.getFailedProperties().get("k")); + SQLClientInfoException bulkClientInfoEx = + assertThrows(SQLClientInfoException.class, () -> handle.setClientInfo(props)); + assertEquals( + ClientInfoStatus.REASON_UNKNOWN, + bulkClientInfoEx.getFailedProperties().get("ApplicationName")); + assertThrows(BigQueryJdbcException.class, () -> handle.getClientInfo("k")); + assertThrows(BigQueryJdbcException.class, handle::getClientInfo); + assertThrows(BigQueryJdbcException.class, () -> handle.createArrayOf("STRING", new Object[0])); + assertThrows(BigQueryJdbcException.class, () -> handle.createStruct("STRUCT", new Object[0])); + assertThrows(BigQueryJdbcException.class, () -> handle.unwrap(BigQueryConnection.class)); + assertThrows(BigQueryJdbcException.class, () -> handle.setSchema("ds")); + assertThrows(BigQueryJdbcException.class, handle::getSchema); + assertThrows(BigQueryJdbcException.class, () -> handle.setNetworkTimeout(executor, 100)); + assertThrows(BigQueryJdbcException.class, handle::getNetworkTimeout); + + verify(bigQueryConnection, never()).createStatement(); + verify(bigQueryConnection, never()).commit(); + verify(bigQueryConnection, never()).isValid(5); + } + + @Test + public void testGetConnectionWhileInUse_invalidatesPreviousWrapperAndResetsState() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + + Connection firstHandle = pooledConnection.getConnection(); + Statement firstStmt = firstHandle.createStatement(); + firstHandle.setClientInfo("ApplicationName", "FirstCaller"); + + Connection secondHandle = pooledConnection.getConnection(); + assertTrue(firstHandle.isClosed()); + assertTrue(firstStmt.isClosed()); + assertThrows(BigQueryJdbcException.class, firstHandle::createStatement); + assertEquals( + 0, + listener.getConnectionClosedCount(), + "Implicit handle reclaim per JDBC 4.3 must not fire connectionClosed"); + + assertFalse(secondHandle.isClosed()); + assertNull(secondHandle.getClientInfo("ApplicationName")); + + // Closing the already-invalidated first handle must not close or return secondHandle. + firstHandle.close(); + assertFalse(secondHandle.isClosed()); + assertTrue(pooledConnection.inUse()); + assertEquals(0, listener.getConnectionClosedCount()); + + secondHandle.close(); + assertEquals(1, listener.getConnectionClosedCount()); + } + } + + @Test + public void testLogicalCloseResetFailure_firesConnectionErrorAndClosesPhysicalConnection() + throws Exception { + try (BigQueryConnection realConn = new BigQueryConnection(sessionUri().toString())) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("driver_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + when(mockBigQuery.query(any(QueryJobConfiguration.class))).thenReturn(beginResult); + when(mockBigQuery.create(any(JobInfo.class))) + .thenThrow(new BigQueryException(500, "rollback backend error")); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + TestConnectionListener eventListener = new TestConnectionListener(); + PooledConnectionListener poolListener = new PooledConnectionListener(CONNECTION_POOL_SIZE); + pooledConnection.addConnectionEventListener(eventListener); + pooledConnection.addConnectionEventListener(poolListener); + + Connection handle = pooledConnection.getConnection(); + handle.setAutoCommit(false); + + assertThrows(SQLException.class, handle::close); + + assertTrue(handle.isClosed()); + assertFalse(pooledConnection.inUse()); + assertEquals(0, eventListener.getConnectionClosedCount()); + assertEquals(1, eventListener.getConnectionErrorCount()); + assertTrue(poolListener.isConnectionPoolEmpty()); + assertTrue(realConn.isClosed()); + verify(mockBigQuery, times(1)).create(any(JobInfo.class)); + assertThrows(BigQueryJdbcException.class, pooledConnection::getConnection); + } + } + + @Test + public void testGetConnectionWhileInUseResetFailure_firesErrorAndClosesPhysical() + throws SQLException { + doThrow(new IllegalStateException("unexpected runtime reset failure")) + .when(bigQueryConnection) + .resetForReuse(); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + + Connection firstHandle = pooledConnection.getConnection(); + BigQueryJdbcException thrown = + assertThrows(BigQueryJdbcException.class, pooledConnection::getConnection); + assertTrue(thrown.getCause() instanceof IllegalStateException); + assertTrue(firstHandle.isClosed()); + assertEquals(1, listener.getConnectionErrorCount()); + verify(bigQueryConnection).close(); + } + + @Test + public void testAbort_handlesNullExecutorOpenHandleAndAlreadyClosedHandle() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + Executor directExecutor = Runnable::run; + + // 1. abort() on an already-closed handle is a no-op and must not close a reused checkout. + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + Connection handle1 = pooledConnection.getConnection(); + assertThrows(BigQueryJdbcException.class, () -> handle1.abort(null)); + handle1.close(); + + Connection handle2 = pooledConnection.getConnection(); + handle1.abort(directExecutor); + assertFalse(realConn.isClosed()); + assertFalse(handle2.isClosed()); + handle2.close(); + } + + // 2. abort() on a live handle closes the physical connection before notifying error listeners. + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + AtomicReference physicalClosedDuringCallback = new AtomicReference<>(false); + pooledConnection.addConnectionEventListener( + new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) {} + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + physicalClosedDuringCallback.set(realConn.isClosed()); + } + }); + + Connection liveHandle = pooledConnection.getConnection(); + liveHandle.abort(directExecutor); + assertTrue(liveHandle.isClosed()); + assertTrue(realConn.isClosed()); + assertTrue(physicalClosedDuringCallback.get()); + assertThrows(BigQueryJdbcException.class, pooledConnection::getConnection); + } + } + + @FunctionalInterface + private interface SqlCallable { + T call() throws SQLException; + } + + @Test + public void testConcurrentCloseDuringStatementCreation_closesNewStatementAndThrows() + throws Exception { + for (int variant = 0; variant < 3; variant++) { + BigQueryConnection mockConn = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(mockConn).getListenerPoolSize(); + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(mockConn); + Connection handle = pooledConnection.getConnection(); + CountDownLatch enteredCreate = new CountDownLatch(1); + CountDownLatch releaseCreate = new CountDownLatch(1); + + if (variant == 0) { + Statement createdStmt = mock(Statement.class); + when(mockConn.createStatement()) + .thenAnswer( + invocation -> { + enteredCreate.countDown(); + assertTrue(releaseCreate.await(5, TimeUnit.SECONDS)); + return createdStmt; + }); + assertTwoThreadCloseDuringCreate( + handle, enteredCreate, releaseCreate, createdStmt, handle::createStatement); + } else if (variant == 1) { + PreparedStatement createdPstmt = mock(PreparedStatement.class); + when(mockConn.prepareStatement("SELECT 1")) + .thenAnswer( + invocation -> { + enteredCreate.countDown(); + assertTrue(releaseCreate.await(5, TimeUnit.SECONDS)); + return createdPstmt; + }); + assertTwoThreadCloseDuringCreate( + handle, + enteredCreate, + releaseCreate, + createdPstmt, + () -> handle.prepareStatement("SELECT 1")); + } else { + CallableStatement createdCstmt = mock(CallableStatement.class); + when(mockConn.prepareCall("{call p()}")) + .thenAnswer( + invocation -> { + enteredCreate.countDown(); + assertTrue(releaseCreate.await(5, TimeUnit.SECONDS)); + return createdCstmt; + }); + assertTwoThreadCloseDuringCreate( + handle, + enteredCreate, + releaseCreate, + createdCstmt, + () -> handle.prepareCall("{call p()}")); + } + } + } + + private static void assertTwoThreadCloseDuringCreate( + Connection handle, + CountDownLatch enteredCreate, + CountDownLatch releaseCreate, + Statement createdStmt, + SqlCallable operation) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future opFuture = + executor.submit( + () -> { + assertThrows(BigQueryJdbcException.class, operation::call); + return null; + }); + assertTrue(enteredCreate.await(5, TimeUnit.SECONDS)); + AtomicReference closeThread = new AtomicReference<>(); + CountDownLatch closeStarted = new CountDownLatch(1); + Future closeFuture = + executor.submit( + () -> { + closeThread.set(Thread.currentThread()); + closeStarted.countDown(); + handle.close(); + return null; + }); + awaitThreadWaiting(closeThread, closeStarted); + releaseCreate.countDown(); + opFuture.get(5, TimeUnit.SECONDS); + closeFuture.get(5, TimeUnit.SECONDS); + verify(createdStmt).close(); + } finally { + executor.shutdownNow(); + } + } + + @Test + public void testListenerCapacityExceededAndPostCloseRegistration() throws SQLException { + doReturn(1L).when(bigQueryConnection).getListenerPoolSize(); + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); + TestConnectionListener first = new TestConnectionListener(); + TestConnectionListener second = new TestConnectionListener(); + + pooledConnection.addConnectionEventListener(first); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> pooledConnection.addConnectionEventListener(second)); + + pooledConnection.close(); + pooledConnection.addConnectionEventListener(second); + assertFalse(pooledConnection.isListenerPooled(second)); + } + + private static void awaitThreadWaiting( + AtomicReference threadRef, CountDownLatch startedLatch) throws InterruptedException { + assertTrue(startedLatch.await(5, TimeUnit.SECONDS)); + Thread worker = threadRef.get(); + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!isThreadWaitingOnLock(worker.getState()) && System.nanoTime() < deadlineNanos) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1)); + } + assertTrue( + isThreadWaitingOnLock(worker.getState()), + "Expected worker thread to be waiting on lock, observed: " + worker.getState()); + } + + private static boolean isThreadWaitingOnLock(Thread.State state) { + return state == Thread.State.BLOCKED + || state == Thread.State.WAITING + || state == Thread.State.TIMED_WAITING; + } + + @Test + public void testConcurrentCloseAndGetConnectionReclaim_serializesResetAndProtectsNewHandle() + throws Exception { + CountDownLatch enteredFirstReset = new CountDownLatch(1); + CountDownLatch allowFirstResetToFinish = new CountDownLatch(1); + AtomicInteger activeResets = new AtomicInteger(0); + AtomicInteger totalResets = new AtomicInteger(0); + AtomicBoolean overlappingResetDetected = new AtomicBoolean(false); + AtomicReference publishedHandle2 = new AtomicReference<>(); + AtomicBoolean resetRanAfterHandle2Published = new AtomicBoolean(false); + + doAnswer( + invocation -> { + if (activeResets.incrementAndGet() > 1) { + overlappingResetDetected.set(true); + } + try { + int callNum = totalResets.incrementAndGet(); + if (callNum == 1) { + enteredFirstReset.countDown(); + assertTrue(allowFirstResetToFinish.await(5, TimeUnit.SECONDS)); + } + if (publishedHandle2.get() != null) { + resetRanAfterHandle2Published.set(true); + } + return null; + } finally { + activeResets.decrementAndGet(); + } + }) + .when(bigQueryConnection) + .resetForReuse(); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); + Connection handle1 = pooledConnection.getConnection(); + BigQueryPooledConnection.PooledConnectionInvocationHandler handle1Handler = + pooledConnection.getActiveHandleForTesting(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + // Thread A reclaims the open handle via getConnection() and blocks inside resetForReuse(). + Future reclaimFuture = executor.submit(pooledConnection::getConnection); + assertTrue(enteredFirstReset.await(5, TimeUnit.SECONDS)); + + // Thread B simulates a caller that passed closed.compareAndSet(false, true) just before + // reclaim and now contends on physicalLock inside connectionHandleClosed(handle1). + CountDownLatch staleCloseStarted = new CountDownLatch(1); + AtomicReference staleCloseThread = new AtomicReference<>(); + Future closeStaleHandleFuture = + executor.submit( + () -> { + staleCloseThread.set(Thread.currentThread()); + staleCloseStarted.countDown(); + pooledConnection.connectionHandleClosed(handle1Handler); + return null; + }); + awaitThreadWaiting(staleCloseThread, staleCloseStarted); + + allowFirstResetToFinish.countDown(); + Connection handle2 = reclaimFuture.get(5, TimeUnit.SECONDS); + publishedHandle2.set(handle2); + closeStaleHandleFuture.get(5, TimeUnit.SECONDS); + + // Direct stale abortHandle after reclaim must also be a no-op and leave handle2 intact (M07). + pooledConnection.abortHandle(handle1Handler, Runnable::run); + verify(bigQueryConnection, never()).abort(any(Executor.class)); + + assertFalse(overlappingResetDetected.get(), "resetForReuse() calls must be serialized"); + assertFalse( + resetRanAfterHandle2Published.get(), + "Stale handle close must not run resetForReuse() underneath active handle2"); + assertEquals(1, totalResets.get()); + assertFalse(handle2.isClosed()); + assertTrue(pooledConnection.inUse()); + + // Scenario 2: handle2.close() blocks inside resetForReuse() while a concurrent + // getConnection() waits on physicalLock, verifying serialized handoff without double-reset. + CountDownLatch enteredSecondReset = new CountDownLatch(1); + CountDownLatch allowSecondResetToFinish = new CountDownLatch(1); + doAnswer( + invocation -> { + if (activeResets.incrementAndGet() > 1) { + overlappingResetDetected.set(true); + } + try { + totalResets.incrementAndGet(); + enteredSecondReset.countDown(); + assertTrue(allowSecondResetToFinish.await(5, TimeUnit.SECONDS)); + return null; + } finally { + activeResets.decrementAndGet(); + } + }) + .when(bigQueryConnection) + .resetForReuse(); + + Future closeHandle2Future = + executor.submit( + () -> { + handle2.close(); + return null; + }); + assertTrue(enteredSecondReset.await(5, TimeUnit.SECONDS)); + + CountDownLatch checkoutStarted = new CountDownLatch(1); + AtomicReference checkoutThread = new AtomicReference<>(); + Future nextCheckoutFuture = + executor.submit( + () -> { + checkoutThread.set(Thread.currentThread()); + checkoutStarted.countDown(); + return pooledConnection.getConnection(); + }); + awaitThreadWaiting(checkoutThread, checkoutStarted); + assertFalse(nextCheckoutFuture.isDone(), "getConnection() must wait for in-flight reset"); + + allowSecondResetToFinish.countDown(); + closeHandle2Future.get(5, TimeUnit.SECONDS); + Connection handle3 = nextCheckoutFuture.get(5, TimeUnit.SECONDS); + + assertFalse(overlappingResetDetected.get()); + assertEquals(2, totalResets.get()); + assertFalse(handle3.isClosed()); + assertTrue(pooledConnection.inUse()); + } finally { + executor.shutdownNow(); + } + } + + @Test + public void testConcurrentPhysicalCloseDuringReset_suppressesReturnEventAndRejectsCheckout() + throws SQLException { + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(bigQueryConnection); + TestConnectionListener listener = new TestConnectionListener(); + pc1.addConnectionEventListener(listener); + Connection handle = pc1.getConnection(); + doAnswer( + invocation -> { + pc1.close(); + return null; + }) + .when(bigQueryConnection) + .resetForReuse(); + + handle.close(); + assertEquals(0, listener.getConnectionClosedCount()); + assertFalse(pc1.inUse()); + + BigQueryConnection bqConn2 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn2).getListenerPoolSize(); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(bqConn2); + pc2.getConnection(); + doAnswer( + invocation -> { + pc2.close(); + return null; + }) + .when(bqConn2) + .resetForReuse(); + + assertThrows(BigQueryJdbcException.class, pc2::getConnection); + } + + @Test + public void testAbort_propagatesDelegateFailureAndSuppressesCloseException() throws SQLException { + BigQueryConnection failingConn = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(failingConn).getListenerPoolSize(); + SQLException abortFailure = new SQLException("abort failed"); + SQLException closeFailure = new SQLException("close failed"); + doThrow(abortFailure).when(failingConn).abort(any(Executor.class)); + doThrow(closeFailure).when(failingConn).close(); + + BigQueryPooledConnection pc = new BigQueryPooledConnection(failingConn); + AtomicReference capturedError = new AtomicReference<>(); + pc.addConnectionEventListener( + new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) {} + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + capturedError.set(event.getSQLException()); + } + }); + + Connection handle = pc.getConnection(); + SQLException thrown = assertThrows(SQLException.class, () -> handle.abort(Runnable::run)); + assertSame(abortFailure, thrown); + assertNotNull(capturedError.get()); + assertEquals(2, capturedError.get().getSuppressed().length); + } + + @Test + public void testChildObjectsReturnLogicalHandleAndGuardRetainedMetaData() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "test-project") + .append("UseStatelessQueryMode", 1) + .toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + TableResult queryResult = mock(TableResult.class); + when(queryResult.getSchema()).thenReturn(Schema.of()); + when(queryResult.getStatementType()).thenReturn(StatementType.SELECT); + when(queryResult.iterateAll()).thenReturn(Collections.emptyList()); + when(queryResult.getValues()).thenReturn(Collections.emptyList()); + when(mockBigQuery.queryWithTimeout(any(QueryJobConfiguration.class), any(), any())) + .thenReturn(queryResult); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + + Connection handle1 = pooledConnection.getConnection(); + Statement stmt = handle1.createStatement(); + PreparedStatement pstmt = handle1.prepareStatement("SELECT 1"); + CallableStatement cstmt = handle1.prepareCall("{call p()}"); + DatabaseMetaData metaData = handle1.getMetaData(); + ResultSet rs = stmt.executeQuery("SELECT 1"); + + assertSame(handle1, stmt.getConnection()); + assertSame(handle1, pstmt.getConnection()); + assertSame(handle1, cstmt.getConnection()); + assertSame(stmt, rs.getStatement()); + assertSame(handle1, rs.getStatement().getConnection()); + assertSame(handle1, metaData.getConnection()); + + // Closing through rs.getStatement().getConnection().close() must close the logical handle + // and fire connectionClosed, leaving the underlying physical connection open for reuse. + rs.getStatement().getConnection().close(); + assertTrue(handle1.isClosed()); + assertFalse(realConn.isClosed()); + assertFalse(pooledConnection.inUse()); + assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + assertThrows(BigQueryJdbcException.class, stmt::getConnection); + + // A DatabaseMetaData retained past handle1.close() must not operate on handle2's checkout. + Connection handle2 = pooledConnection.getConnection(); + assertThrows(BigQueryJdbcException.class, metaData::getConnection); + assertThrows(BigQueryJdbcException.class, metaData::getDatabaseProductName); + assertFalse(handle2.isClosed()); + handle2.close(); + } + } + + @Test + public void testOutOfBandPhysicalClose_firesConnectionErrorOnHandleCloseAndCheckout() + throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + // Case 1: Physical connection closed out-of-band while logical handle is checked out. + BigQueryConnection realConn1 = new BigQueryConnection(url); + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(realConn1); + TestConnectionListener listener1 = new TestConnectionListener(); + PooledConnectionListener poolListener1 = new PooledConnectionListener(CONNECTION_POOL_SIZE); + pc1.addConnectionEventListener(listener1); + pc1.addConnectionEventListener(poolListener1); + + Connection handle1 = pc1.getConnection(); + handle1.unwrap(BigQueryConnection.class).close(); + assertTrue(realConn1.isClosed()); + + handle1.close(); + assertFalse(pc1.inUse()); + assertEquals(0, listener1.getConnectionClosedCount()); + assertEquals(1, listener1.getConnectionErrorCount()); + assertTrue(poolListener1.isConnectionPoolEmpty()); + assertThrows(BigQueryJdbcException.class, pc1::getConnection); + + // Case 2: Physical connection closed out-of-band while holder is idle, then getConnection(). + BigQueryConnection realConn2 = new BigQueryConnection(url); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(realConn2); + TestConnectionListener listener2 = new TestConnectionListener(); + pc2.addConnectionEventListener(listener2); + realConn2.close(); + + assertThrows(BigQueryJdbcException.class, pc2::getConnection); + assertEquals(0, listener2.getConnectionClosedCount()); + assertEquals(1, listener2.getConnectionErrorCount()); + } + + @Test + public void testConcurrentSetAutoCommitAndClose_waitsForInFlightRpcAndRollsBackTransaction() + throws Exception { + try (BigQueryConnection realConn = new BigQueryConnection(sessionUri().toString())) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + + CountDownLatch enteredBeginRpc = new CountDownLatch(1); + CountDownLatch releaseBeginRpc = new CountDownLatch(1); + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("raced_tx_session"); + TableResult beginResult = mock(TableResult.class); + when(beginResult.getSessionInfo()).thenReturn(sessionInfo); + + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenAnswer( + invocation -> { + QueryJobConfiguration cfg = invocation.getArgument(0); + if ("BEGIN TRANSACTION;".equals(cfg.getQuery())) { + enteredBeginRpc.countDown(); + assertTrue(releaseBeginRpc.await(5, TimeUnit.SECONDS)); + return beginResult; + } + return mock(TableResult.class); + }); + + Job rollbackJob = mock(Job.class); + when(mockBigQuery.create(any(JobInfo.class))).thenReturn(rollbackJob); + when(rollbackJob.waitFor()).thenReturn(rollbackJob); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + Connection handle1 = pooledConnection.getConnection(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future autoCommitFuture = + executor.submit( + () -> { + assertThrows(BigQueryJdbcException.class, () -> handle1.setAutoCommit(false)); + return null; + }); + assertTrue(enteredBeginRpc.await(5, TimeUnit.SECONDS)); + + AtomicReference closeThread = new AtomicReference<>(); + CountDownLatch closeStarted = new CountDownLatch(1); + Future closeFuture = + executor.submit( + () -> { + closeThread.set(Thread.currentThread()); + closeStarted.countDown(); + handle1.close(); + return null; + }); + awaitThreadWaiting(closeThread, closeStarted); + assertFalse(closeFuture.isDone(), "close() must wait for in-flight setAutoCommit RPC"); + + releaseBeginRpc.countDown(); + autoCommitFuture.get(5, TimeUnit.SECONDS); + closeFuture.get(5, TimeUnit.SECONDS); + + assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + + Connection handle2 = pooledConnection.getConnection(); + assertTrue(handle2.getAutoCommit()); + assertFalse(realConn.isTransactionStarted()); + assertNull(realConn.getSessionInfoConnectionProperty()); + handle2.close(); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + public void testPhysicalCloseAndErrorWaitForInFlightResetOnPhysicalLock() throws Exception { + for (boolean triggerError : new boolean[] {false, true}) { + BigQueryConnection mockConn = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(mockConn).getListenerPoolSize(); + CountDownLatch enteredReset = new CountDownLatch(1); + CountDownLatch releaseReset = new CountDownLatch(1); + AtomicBoolean resetInFlight = new AtomicBoolean(false); + AtomicBoolean closeOverlappedReset = new AtomicBoolean(false); + + doAnswer( + invocation -> { + resetInFlight.set(true); + enteredReset.countDown(); + try { + assertTrue(releaseReset.await(5, TimeUnit.SECONDS)); + return null; + } finally { + resetInFlight.set(false); + } + }) + .when(mockConn) + .resetForReuse(); + doAnswer( + invocation -> { + if (resetInFlight.get()) { + closeOverlappedReset.set(true); + } + return null; + }) + .when(mockConn) + .close(); + + BigQueryPooledConnection pc = new BigQueryPooledConnection(mockConn); + Connection handle = pc.getConnection(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future resetFuture = + executor.submit( + () -> { + handle.close(); + return null; + }); + assertTrue(enteredReset.await(5, TimeUnit.SECONDS)); + + AtomicReference teardownThread = new AtomicReference<>(); + CountDownLatch teardownStarted = new CountDownLatch(1); + Future teardownFuture = + executor.submit( + () -> { + teardownThread.set(Thread.currentThread()); + teardownStarted.countDown(); + if (triggerError) { + pc.fireConnectionError(new SQLException("forced error")); + } else { + pc.close(); + } + return null; + }); + awaitThreadWaiting(teardownThread, teardownStarted); + verify(mockConn, never()).close(); + + releaseReset.countDown(); + resetFuture.get(5, TimeUnit.SECONDS); + teardownFuture.get(5, TimeUnit.SECONDS); + + assertFalse(closeOverlappedReset.get()); + verify(mockConn, times(1)).close(); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + public void testListenerExceptionsAreIsolatedOnCloseAndError() throws SQLException { + ConnectionEventListener throwingListener = + new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + throw new IllegalStateException("listener close failure"); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + throw new IllegalStateException("listener error failure"); + } + }; + + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(bigQueryConnection); + TestConnectionListener healthy1 = new TestConnectionListener(); + pc1.addConnectionEventListener(throwingListener); + pc1.addConnectionEventListener(healthy1); + + Connection handle1 = pc1.getConnection(); + handle1.close(); + assertEquals(1, healthy1.getConnectionClosedCount()); + + BigQueryConnection failingResetConn = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(failingResetConn).getListenerPoolSize(); + SQLException resetEx = new SQLException("reset failed"); + doThrow(resetEx).when(failingResetConn).resetForReuse(); + + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(failingResetConn); + TestConnectionListener healthy2 = new TestConnectionListener(); + pc2.addConnectionEventListener(throwingListener); + pc2.addConnectionEventListener(healthy2); + + Connection handle2 = pc2.getConnection(); + SQLException surfaced = assertThrows(SQLException.class, handle2::close); + assertSame(resetEx, surfaced); + assertEquals(1, healthy2.getConnectionErrorCount()); + } + + @Test + public void testAbortUsesExecutorAsynchronouslyAndPreemptsBlockedReset() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + // 1. Deferred executor receives the physical close task while abort() returns immediately. + BigQueryConnection realConn = new BigQueryConnection(url); + BigQueryPooledConnection pc = new BigQueryPooledConnection(realConn); + TestConnectionListener listener = new TestConnectionListener(); + pc.addConnectionEventListener(listener); + + Connection handle = pc.getConnection(); + Statement stmt = handle.createStatement(); + DatabaseMetaData metaData = handle.getMetaData(); + List deferredTasks = new ArrayList<>(); + handle.abort(deferredTasks::add); + + assertTrue(handle.isClosed()); + assertTrue(realConn.isClosed()); + assertEquals(1, listener.getConnectionErrorCount()); + assertEquals(1, deferredTasks.size()); + assertFalse(stmt.isClosed()); + assertThrows(BigQueryJdbcException.class, stmt::getConnection); + assertThrows(BigQueryJdbcException.class, metaData::getConnection); + + deferredTasks.get(0).run(); + assertTrue(stmt.isClosed()); + + // 2. abort() while handle.close() is blocked inside resetForReuse() preempts the hung reset. + BigQueryConnection hungResetConn = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(hungResetConn).getListenerPoolSize(); + CountDownLatch enteredReset = new CountDownLatch(1); + CountDownLatch releaseReset = new CountDownLatch(1); + doAnswer( + invocation -> { + enteredReset.countDown(); + assertTrue(releaseReset.await(5, TimeUnit.SECONDS)); + return null; + }) + .when(hungResetConn) + .resetForReuse(); + + BigQueryPooledConnection pcHung = new BigQueryPooledConnection(hungResetConn); + TestConnectionListener hungListener = new TestConnectionListener(); + pcHung.addConnectionEventListener(hungListener); + Connection hungHandle = pcHung.getConnection(); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future closeFuture = + executor.submit( + () -> { + hungHandle.close(); + return null; + }); + assertTrue(enteredReset.await(5, TimeUnit.SECONDS)); + + List abortTasks = new ArrayList<>(); + hungHandle.abort(abortTasks::add); + assertEquals(1, hungListener.getConnectionErrorCount()); + assertEquals(0, hungListener.getConnectionClosedCount()); + verify(hungResetConn).abort(any(Executor.class)); + + releaseReset.countDown(); + closeFuture.get(5, TimeUnit.SECONDS); + assertEquals(0, hungListener.getConnectionClosedCount()); + } finally { + executor.shutdownNow(); + } + + // 3. Rejecting Executor passed to abort() rolls back and runs synchronous fallback close. + BigQueryConnection rejectConn = new BigQueryConnection(url); + BigQueryPooledConnection pcReject = new BigQueryPooledConnection(rejectConn); + TestConnectionListener rejectListener = new TestConnectionListener(); + pcReject.addConnectionEventListener(rejectListener); + Connection rejectHandle = pcReject.getConnection(); + Statement rejectStmt = rejectHandle.createStatement(); + + assertThrows( + RejectedExecutionException.class, + () -> + rejectHandle.abort( + task -> { + throw new RejectedExecutionException("abort pool shut down"); + })); + assertTrue(rejectHandle.isClosed()); + assertTrue(rejectConn.isClosed()); + assertTrue(rejectStmt.isClosed()); + assertEquals(1, rejectListener.getConnectionErrorCount()); + } + + @Test + public void testConcurrentStatementExecuteAndHandleClose_waitsForInFlightQueryAndAbortsSession() + throws Exception { + String url = sessionUri().append("UseStatelessQueryMode", 1).toString(); + try (BigQueryConnection realConn = new BigQueryConnection(url)) { + BigQuery mockBigQuery = mock(BigQuery.class); + realConn.bigQuery = mockBigQuery; + + CountDownLatch enteredQueryRpc = new CountDownLatch(1); + CountDownLatch releaseQueryRpc = new CountDownLatch(1); + SessionInfo sessionInfo = mock(SessionInfo.class); + when(sessionInfo.getSessionId()).thenReturn("raced_stmt_session"); + TableResult queryResult = mock(TableResult.class); + when(queryResult.getSchema()).thenReturn(Schema.of()); + when(queryResult.getStatementType()).thenReturn(StatementType.SELECT); + when(queryResult.iterateAll()).thenReturn(Collections.emptyList()); + when(queryResult.getValues()).thenReturn(Collections.emptyList()); + when(queryResult.getSessionInfo()).thenReturn(sessionInfo); + + when(mockBigQuery.queryWithTimeout(any(QueryJobConfiguration.class), any(), any())) + .thenAnswer( + invocation -> { + enteredQueryRpc.countDown(); + assertTrue(releaseQueryRpc.await(5, TimeUnit.SECONDS)); + return queryResult; + }); + when(mockBigQuery.query(any(QueryJobConfiguration.class))) + .thenReturn(mock(TableResult.class)); + + BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(realConn); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + Connection handle1 = pooledConnection.getConnection(); + Statement stmt1 = handle1.createStatement(); + + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future queryFuture = + executor.submit( + () -> { + assertThrows(BigQueryJdbcException.class, () -> stmt1.executeQuery("SELECT 1")); + return null; + }); + assertTrue(enteredQueryRpc.await(5, TimeUnit.SECONDS)); + + AtomicReference closeThread = new AtomicReference<>(); + CountDownLatch closeStarted = new CountDownLatch(1); + Future closeFuture = + executor.submit( + () -> { + closeThread.set(Thread.currentThread()); + closeStarted.countDown(); + handle1.close(); + return null; + }); + awaitThreadWaiting(closeThread, closeStarted); + assertFalse(closeFuture.isDone(), "close() must wait for in-flight Statement RPC"); + + releaseQueryRpc.countDown(); + queryFuture.get(5, TimeUnit.SECONDS); + closeFuture.get(5, TimeUnit.SECONDS); + + assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + assertTrue(stmt1.isClosed()); + + Connection handle2 = pooledConnection.getConnection(); + assertNull(realConn.getSessionInfoConnectionProperty()); + assertFalse(realConn.isSessionCreatedByDriver()); + handle2.close(); + + ArgumentCaptor abortCaptor = + ArgumentCaptor.forClass(QueryJobConfiguration.class); + verify(mockBigQuery).query(abortCaptor.capture()); + assertEquals("CALL BQ.ABORT_SESSION();", abortCaptor.getValue().getQuery()); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + public void testPooledOperationsPreserveOuterThreadMdcContext() throws Exception { + String url = + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "test-project").toString(); + AtomicReference mdcDuringClosedCallback = new AtomicReference<>(); + AtomicReference mdcDuringErrorCallback = new AtomicReference<>(); + ConnectionEventListener mdcCapturingListener = + new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + mdcDuringClosedCallback.set(BigQueryJdbcMdc.getConnectionId()); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + mdcDuringErrorCallback.set(BigQueryJdbcMdc.getConnectionId()); + } + }; + + try (BigQueryJdbcMdc.MdcCloseable outerMdc = + BigQueryJdbcMdc.registerInstance("outer-caller-conn")) { + BigQueryConnection realConn1 = new BigQueryConnection(url); + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(realConn1); + + pc1.addConnectionEventListener(mdcCapturingListener); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + + Connection handle1 = pc1.getConnection(); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + + handle1.close(); + assertEquals("outer-caller-conn", mdcDuringClosedCallback.get()); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + + pc1.close(); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + + BigQueryConnection realConn2 = new BigQueryConnection(url); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(realConn2); + pc2.addConnectionEventListener(mdcCapturingListener); + Connection handle2 = pc2.getConnection(); + pc2.fireConnectionError(new SQLException("forced error")); + assertTrue(handle2.isClosed()); + assertEquals("outer-caller-conn", mdcDuringErrorCallback.get()); + assertEquals("outer-caller-conn", BigQueryJdbcMdc.getConnectionId()); + } + assertNull(BigQueryJdbcMdc.getConnectionId()); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatementSettersTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatementSettersTest.java index b8f0c863660e..cb32bc0d69d3 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatementSettersTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryPreparedStatementSettersTest.java @@ -24,14 +24,23 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.api.gax.grpc.GrpcStatusCode; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.FieldList; @@ -42,6 +51,9 @@ import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature; +import com.google.cloud.bigquery.jdbc.telemetry.v1.QueryApiType; +import com.google.cloud.bigquery.jdbc.telemetry.v1.StatementExecution; +import com.google.cloud.bigquery.jdbc.telemetry.v1.Status; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; import com.google.gson.Gson; import com.google.gson.JsonNull; @@ -68,6 +80,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; public class BigQueryPreparedStatementSettersTest { @@ -544,16 +557,140 @@ public void testSetObjectLocalDateTime_zeroSecondsStillHasFullDigits() throws SQ } @Test - public void testPrimitiveSetters_recordParameterBindingFeature() throws SQLException { - // These setters use the (int, Object, Class) overload of BigQueryParameterHandler, which - // previously did not record DRIVER_FEATURE_PARAMETER_BINDING. One record per binding. + public void testSetters_recordParameterBindingFeatureOncePerStatement() throws SQLException { + // DRIVER_FEATURE_PARAMETER_BINDING is an adoption signal: one record per prepared statement, + // regardless of how many setX calls are made or which handler overload they use. try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { preparedStatement.setInt(1, 42); preparedStatement.setLong(2, 42L); preparedStatement.setString(3, "x"); + preparedStatement.setNull(4, Types.VARCHAR); telemetry.verify( () -> TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_PARAMETER_BINDING), - times(3)); + times(1)); + } + } + + @Test + public void testExecuteBatch_success_recordsBatchOperationsOnce() throws SQLException { + // Standard (non-Write-API) batch path. Stub the query run so no BigQuery client is needed. + BigQueryPreparedStatement spy = spy(preparedStatement); + doReturn(null).when(spy).getStandardBatchJobConfiguration(anyString()); + doNothing().when(spy).runQuery(anyString(), any()); + doReturn(-1).when(spy).getUpdateCount(); + spy.setInt(1, 1); + spy.addBatch(); + + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + spy.executeBatch(); + telemetry.verify( + () -> TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS), + times(1)); + } + } + + @Test + public void testExecuteBatch_failure_doesNotRecordBatchOperations() throws SQLException { + // Regression guard: BATCH_OPERATIONS is success-only; the failure is already captured by + // the StatementExecution status, so recording the feature here would double-report it. + BigQueryPreparedStatement spy = spy(preparedStatement); + doReturn(null).when(spy).getStandardBatchJobConfiguration(anyString()); + doThrow(new BigQueryJdbcException("simulated batch failure")) + .when(spy) + .runQuery(anyString(), any()); + spy.setInt(1, 1); + spy.addBatch(); + + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + assertThrows(BigQueryJdbcException.class, spy::executeBatch); + telemetry.verify( + () -> TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS), + never()); + } + } + + @Test + public void testExecuteBatch_writeApiFailure_recordsErrorStatusAndNoBatchFeature() + throws SQLException { + // Write API branch. When bulkInsertWithWriteAPI throws an unchecked ApiException, executeBatch + // must wrap it in BigQueryJdbcException (JDBC 4.3), record STATUS_ERROR with the HTTP status + // code, and not count as a BATCH_OPERATIONS feature use. + BigQueryPreparedStatement spy = spy(preparedStatement); + doReturn(true).when(spy).useWriteAPI(); + ApiException apiException = + ApiExceptionFactory.createException( + "write failed", null, GrpcStatusCode.of(io.grpc.Status.Code.PERMISSION_DENIED), false); + when(connection.getBigQueryWriteClient()).thenThrow(apiException); + spy.setInt(1, 1); + spy.addBatch(); + + try (MockedStatic telemetry = + mockStatic(TelemetryManager.class, CALLS_REAL_METHODS)) { + assertThrows(BigQueryJdbcException.class, spy::executeBatch); + ArgumentCaptor execution = + ArgumentCaptor.forClass(StatementExecution.Builder.class); + telemetry.verify( + () -> TelemetryManager.recordStatementExecution(execution.capture(), anyLong()), + times(1)); + assertEquals(Status.STATUS_ERROR, execution.getValue().getStatus()); + assertEquals(403, execution.getValue().getErrorCode()); + assertEquals(QueryApiType.QUERY_API_TYPE_WRITE_API, execution.getValue().getQueryApiType()); + telemetry.verify( + () -> TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS), + never()); + } + } + + @Test + public void testExecuteBatch_internalStatement_recordsNothing() throws SQLException { + BigQueryPreparedStatement spy = + spy(new BigQueryPreparedStatement(connection, "SELECT ?", false, false)); + doReturn(null).when(spy).getStandardBatchJobConfiguration(anyString()); + doNothing().when(spy).runQuery(anyString(), any()); + doReturn(-1).when(spy).getUpdateCount(); + spy.setInt(1, 1); + spy.addBatch(); + + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + spy.executeBatch(); + telemetry.verifyNoInteractions(); + } + } + + @Test + public void testGetMetaData_recordsResultSetMetadataRetrievalOncePerStatement() + throws SQLException { + preparedStatement.resultSchema = Schema.of(Field.of("c", StandardSQLTypeName.INT64)); + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + preparedStatement.getMetaData(); + preparedStatement.getMetaData(); + telemetry.verify( + () -> + TelemetryManager.recordFeatureUsage( + DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL, + "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL"), + times(1)); + } + } + + @Test + public void testGetMetaData_noResultSchema_returnsNullAndRecordsNothing() throws SQLException { + // JDBC: null for a statement that produces no result set. No metadata, no record. + preparedStatement.resultSchema = null; + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + assertNull(preparedStatement.getMetaData()); + telemetry.verifyNoInteractions(); + } + } + + @Test + public void testGetMetaData_internalStatement_recordsNothing() throws SQLException { + BigQueryPreparedStatement internal = + new BigQueryPreparedStatement(connection, "SELECT ?", false, false); + internal.resultSchema = Schema.of(Field.of("c", StandardSQLTypeName.INT64)); + try (MockedStatic telemetry = mockStatic(TelemetryManager.class)) { + assertNotNull(internal.getMetaData()); + telemetry.verifyNoInteractions(); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java index 793feb22ee64..52a99e212f22 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java @@ -26,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -1901,7 +1902,53 @@ public void testClose_doesNotRecordStatementCancelFeature() throws SQLException @Test public void testCancel_recordsStatementCancelFeatureOnce() throws SQLException { assertFeatureRecorded( - () -> bigQueryStatement.cancel(), DriverFeature.DRIVER_FEATURE_STATEMENT_CANCEL, 1); + () -> { + bigQueryStatement.cancel(); + bigQueryStatement.cancel(); + }, + DriverFeature.DRIVER_FEATURE_STATEMENT_CANCEL, + 1); + } + + @Test + public void testInternalStatement_recordsNoTelemetryForExecutionOrCancel() throws Exception { + // Statements the driver creates for itself (isValid, metadata queries) must not be reported + // as user activity: no StatementExecution, no feature usage. + TableResult tableResultMock = setupMockQueryResults(null, StatementType.SELECT, null); + BigQueryStatement internalStatement = new BigQueryStatement(bigQueryConnection, false); + BigQueryStatement internalSpy = Mockito.spy(internalStatement); + doReturn(mock(BigQueryJsonResultSet.class)) + .when(internalSpy) + .processJsonResultSet(eq(tableResultMock), any()); + + // CALLS_REAL_METHODS keeps TelemetryManager's pure helpers (toStatementType etc.) working; + // the record* methods are no-ops without an initialized instance but are still counted. + try (MockedStatic telemetry = + Mockito.mockStatic(TelemetryManager.class, Mockito.CALLS_REAL_METHODS)) { + internalSpy.executeQuery("SELECT 1"); + internalSpy.cancel(); + telemetry.verify( + () -> TelemetryManager.recordStatementExecution(any(), anyLong()), Mockito.never()); + telemetry.verify(() -> TelemetryManager.recordFeatureUsage(any()), Mockito.never()); + telemetry.verify(() -> TelemetryManager.recordFeatureUsage(any(), any()), Mockito.never()); + } + } + + @Test + public void testUserStatement_recordsExecution() throws Exception { + // Control for the test above: the same flow on a regular statement does reach the batcher. + TableResult tableResultMock = setupMockQueryResults(null, StatementType.SELECT, null); + BigQueryStatement userSpy = Mockito.spy(new BigQueryStatement(bigQueryConnection)); + doReturn(mock(BigQueryJsonResultSet.class)) + .when(userSpy) + .processJsonResultSet(eq(tableResultMock), any()); + + try (MockedStatic telemetry = + Mockito.mockStatic(TelemetryManager.class, Mockito.CALLS_REAL_METHODS)) { + userSpy.executeQuery("SELECT 1"); + telemetry.verify( + () -> TelemetryManager.recordStatementExecution(any(), anyLong()), Mockito.times(1)); + } } /** Runs {@code action} and asserts how many times {@code feature} was recorded by it. */ diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtilityTest.java index 7a27e6112ef2..6904e0de4b00 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryTemporalUtilityTest.java @@ -22,6 +22,7 @@ import static com.google.cloud.bigquery.jdbc.utils.TestUtilities.rangeField; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.FieldValue; @@ -31,12 +32,14 @@ import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; +import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.Calendar; +import java.util.Collections; import java.util.TimeZone; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -388,6 +391,77 @@ public void testParseEpochDecimalToInstantInvalid() { () -> BigQueryTemporalUtility.parseEpochDecimalToInstant("invalid_epoch")); } + @ParameterizedTest + @ValueSource( + strings = { + "1e100000000", + "-1e100000000", + "1e2147483647", + "-1e2147483647", + "1e2147483648", + "-1e2147483648", + "1e18", + "-1e18", + "5e16", + "-5e16" + }) + public void testExtremePositiveExponentEpochDecimalsFailFast(String input) { + assertTimeoutPreemptively( + Duration.ofSeconds(1), + () -> { + assertThrows( + BigQueryJdbcException.class, + () -> + BigQueryTypeRegistry.convert( + input, StandardSQLTypeName.STRING, Timestamp.class, null)); + assertThrows( + BigQueryJdbcException.class, + () -> BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal(input, false)); + assertThrows( + BigQueryJdbcException.class, + () -> BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal(input, true)); + }); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0e100000000", + "-0e100000000", + "1e-100000000", + "-1e-100000000", + "12345678901234567890e-100000000", + "-12345678901234567890e-100000000" + }) + public void testExtremeSubUnitAndZeroExponentsTruncateInConstantTime(String input) + throws Exception { + assertTimeoutPreemptively( + Duration.ofSeconds(1), + () -> { + assertThat(BigQueryTemporalUtility.parseEpochDecimalToInstant(input)) + .isEqualTo(Instant.EPOCH); + assertThat(BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal(input, false)) + .isEqualTo("1970-01-01 00:00:00.000000"); + assertThat(BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal(input, true)) + .isEqualTo("1970-01-01 00:00:00.000000000000"); + }); + } + + @Test + public void testOverlongEpochDecimalStringRejectedFast() { + String overlong = String.join("", Collections.nCopies(200, "0")) + ".5"; + assertTimeoutPreemptively( + Duration.ofSeconds(1), + () -> { + assertThrows( + NumberFormatException.class, + () -> BigQueryTemporalUtility.parseEpochDecimalToInstant(overlong)); + assertThrows( + BigQueryJdbcException.class, + () -> BigQueryTemporalUtility.formatTimestampStringFromEpochDecimal(overlong, false)); + }); + } + @Test public void testFormatTimestampStringFromEpochDecimalWithPicosEnabled() throws BigQueryJdbcException { diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java index f6b82211c142..6cccb0e19b7f 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java @@ -18,14 +18,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import java.sql.SQLException; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; public class DataSourceTest { @@ -83,4 +87,53 @@ public void testMetadataFetchThreadCountValidation() { .contains( "Invalid value for MetaDataFetchThreadCount. It must be greater than or equal to 1")); } + + @Test + public void testUniverseDomainAndByoidTokenUriResolution() { + try (MockedStatic urlUtil = + mockStatic(BigQueryJdbcUrlUtility.class, CALLS_REAL_METHODS)) { + // 1. Neither URL/setter nor GOOGLE_CLOUD_UNIVERSE_DOMAIN is set -> null universeDomain + urlUtil.when(BigQueryJdbcUrlUtility::getEnvUniverseDomain).thenReturn(null); + DataSource ds = new DataSource(); + assertNull(ds.getUniverseDomain()); + assertNull(ds.resolveUniverseDomain()); + assertEquals("https://sts.googleapis.com/v1/token", ds.getByoidTokenUri()); + + // 2. GOOGLE_CLOUD_UNIVERSE_DOMAIN is set, explicit universeDomain is omitted: + // getUniverseDomain() stays null (preserving setter symmetry), resolveUniverseDomain() uses + // env + urlUtil + .when(BigQueryJdbcUrlUtility::getEnvUniverseDomain) + .thenReturn("custom-universe.example.com"); + assertNull(ds.getUniverseDomain()); + assertEquals("custom-universe.example.com", ds.resolveUniverseDomain()); + assertEquals("https://sts.googleapis.com/v1/token", ds.getByoidTokenUri()); + + // 3. Explicit universeDomain takes precedence over GOOGLE_CLOUD_UNIVERSE_DOMAIN + ds.setUniverseDomain("explicit-universe.example.com"); + assertEquals("explicit-universe.example.com", ds.getUniverseDomain()); + assertEquals("explicit-universe.example.com", ds.resolveUniverseDomain()); + assertEquals("https://sts.explicit-universe.example.com/v1/token", ds.getByoidTokenUri()); + + // 4. Explicit BYOID_TokenUri takes precedence over universeDomain derivation + ds.setByoidTokenUri("https://custom-sts.internal/v1/token"); + assertEquals("https://custom-sts.internal/v1/token", ds.getByoidTokenUri()); + } + } + + @Test + public void testNormalizeUniverseDomain() { + assertNull(BigQueryJdbcUrlUtility.normalizeUniverseDomain(null)); + assertNull(BigQueryJdbcUrlUtility.normalizeUniverseDomain("")); + assertNull(BigQueryJdbcUrlUtility.normalizeUniverseDomain(" ")); + assertEquals( + "custom-universe.example.com", + BigQueryJdbcUrlUtility.normalizeUniverseDomain(" custom-universe.example.com ")); + assertNull(BigQueryJdbcUrlUtility.resolveEnvUniverseDomain(null)); + assertEquals("googleapis.com", BigQueryJdbcUrlUtility.resolveEnvUniverseDomain("")); + assertEquals("googleapis.com", BigQueryJdbcUrlUtility.resolveEnvUniverseDomain(" ")); + assertEquals( + "custom-universe.example.com", + BigQueryJdbcUrlUtility.resolveEnvUniverseDomain(" custom-universe.example.com ")); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java index e923dd011778..bde45856b895 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java @@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.google.cloud.logging.LogEntry; @@ -31,6 +32,8 @@ import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import java.util.List; +import java.util.logging.Level; +import java.util.logging.LogRecord; import java.util.logging.Logger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -58,6 +61,9 @@ public void tearDown() { BigQueryJdbcOpenTelemetry.unregisterConnection("test-uuid"); BigQueryJdbcOpenTelemetry.unregisterConnection("wrong-uuid"); BigQueryJdbcOpenTelemetry.unregisterConnection("gcp-uuid"); + BigQueryJdbcOpenTelemetry.unregisterConnection("severe-only-uuid"); + BigQueryJdbcMdc.clear(); + BigQueryJdbcRootLogger.resetForTest(); logger.setLevel(originalLevel); } @@ -120,15 +126,85 @@ public void testPublishToGcp() { try (Scope scope = baggage.makeCurrent(); BigQueryJdbcMdc.MdcCloseable mdcScope = BigQueryJdbcMdc.registerInstance("gcp-uuid")) { logger.info("Test message"); + logger.log(new LogRecord(Level.INFO, null)); } ArgumentCaptor> captor = ArgumentCaptor.forClass(Iterable.class); - verify(loggingClient).write(captor.capture()); + verify(loggingClient, times(2)).write(captor.capture()); - Iterable entries = captor.getValue(); - LogEntry entry = entries.iterator().next(); + List> allWrites = captor.getAllValues(); + LogEntry entry = allWrites.get(0).iterator().next(); + LogEntry nullEntry = allWrites.get(1).iterator().next(); assertEquals("Test message", ((Payload.StringPayload) entry.getPayload()).getData()); assertEquals(com.google.cloud.logging.Severity.INFO, entry.getSeverity()); + assertEquals("", ((Payload.StringPayload) nullEntry.getPayload()).getData()); + } + + @Test + public void testResultSetLoggerRoutingAndMessageFormatting() { + BigQueryJdbcOpenTelemetry.registerConnection( + "test-uuid", otelTesting.getOpenTelemetry(), null, false); + BigQueryJdbcMdc.clear(); + + BigQueryJdbcResultSetLogger rsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, "test-uuid"); + rsLogger.fineTrace("getObject", "Column 'user_id' has unparsed {json}"); + + LogRecord parameterized = new LogRecord(Level.INFO, "Processing job {0}"); + parameterized.setParameters(new Object[] {"job-999"}); + rsLogger.log(parameterized); + + Baggage baggage = + Baggage.builder() + .put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, "test-uuid") + .build(); + try (Scope scope = baggage.makeCurrent()) { + LogRecord retryStyle = new LogRecord(Level.INFO, "Retrying 'getQueryResults'"); + retryStyle.setParameters(new Object[] {"attempt=1"}); + logger.log(retryStyle); + + LogRecord directPositional = new LogRecord(Level.INFO, "Direct {0} ok"); + directPositional.setParameters(new Object[] {"param0"}); + logger.log(directPositional); + + LogRecord malformedPattern = new LogRecord(Level.INFO, "Broken {0"); + malformedPattern.setParameters(new Object[] {"param0"}); + logger.log(malformedPattern); + + LogRecord nullMessage = new LogRecord(Level.INFO, null); + logger.log(nullMessage); + } + + List logs = otelTesting.getLogRecords(); + assertEquals(6, logs.size()); + assertEquals("Column 'user_id' has unparsed {json}", logs.get(0).getBody().asString()); + assertEquals("Processing job job-999", logs.get(1).getBody().asString()); + assertEquals("Retrying 'getQueryResults'", logs.get(2).getBody().asString()); + assertEquals("Direct param0 ok", logs.get(3).getBody().asString()); + assertEquals("Broken {0", logs.get(4).getBody().asString()); + assertTrue(logs.get(5).getBody().asString().isEmpty()); + } + + @Test + public void testPerConnectionLogLevelFilteringWhenSiblingConnectionIsVerbose() { + BigQueryJdbcRootLogger.registerConnection("verbose-sibling", "6", null); + BigQueryJdbcRootLogger.registerConnection("severe-only-uuid", "1", null); + BigQueryJdbcOpenTelemetry.registerConnection( + "severe-only-uuid", otelTesting.getOpenTelemetry(), null, false); + + Baggage baggage = + Baggage.builder() + .put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, "severe-only-uuid") + .build(); + try (Scope scope = baggage.makeCurrent(); + BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance("severe-only-uuid")) { + logger.info("info-should-be-filtered"); + logger.severe("severe-should-export"); + } + + List logs = otelTesting.getLogRecords(); + assertEquals(1, logs.size()); + assertEquals("severe-should-export", logs.get(0).getBody().asString()); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index cbc4dec030c8..df5184be419f 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java @@ -16,24 +16,50 @@ package com.google.cloud.bigquery.jdbc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.mock; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.FieldList; +import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; +import com.google.cloud.bigquery.jdbc.utils.TestUtilities; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.ErrorManager; +import java.util.logging.Formatter; +import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -78,7 +104,7 @@ private Optional findLogFile(String suffix) throws IOException { @Test public void testInitialization() throws IOException { Path defaultLog = tempDir.resolve("BQ-JDBC-GLOBAL.log"); - assertTrue(Files.exists(defaultLog)); + assertFalse(Files.exists(defaultLog)); } @Test @@ -221,4 +247,720 @@ public void testResultSetExceptionLogRouting() throws Exception { rootLogger.removeHandler(handler); } } + + private static boolean isPosix() { + return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + } + + private static ErrorManager silentErrorManager() { + return new ErrorManager() { + @Override + public synchronized void error(String msg, Exception ex, int code) {} + }; + } + + @Test + public void testPosixOwnerOnlyPermissionsOnCreatedDirsAndFiles() throws IOException { + assumeTrue(isPosix(), "POSIX permissions required"); + Path nestedDir = tempDir.resolve("nested").resolve("logs"); + PerConnectionFileHandler nestedHandler = + new PerConnectionFileHandler(nestedDir.toString(), Level.INFO); + try { + nestedHandler.publish(new LogRecord(Level.INFO, "global perm check")); + BigQueryJdbcMdc.registerInstance("BQ-JDBC-perm1234"); + nestedHandler.publish(new LogRecord(Level.INFO, "perm check")); + + Set expectedDir = PosixFilePermissions.fromString("rwx------"); + Set expectedFile = PosixFilePermissions.fromString("rw-------"); + assertEquals( + expectedDir, + Files.getPosixFilePermissions(nestedDir.getParent(), LinkOption.NOFOLLOW_LINKS)); + assertEquals( + expectedDir, Files.getPosixFilePermissions(nestedDir, LinkOption.NOFOLLOW_LINKS)); + assertEquals( + expectedFile, + Files.getPosixFilePermissions( + nestedDir.resolve("BQ-JDBC-GLOBAL.log"), LinkOption.NOFOLLOW_LINKS)); + try (Stream stream = Files.list(nestedDir)) { + List connFiles = + stream + .filter(p -> p.getFileName().toString().endsWith("-perm.log")) + .collect(Collectors.toList()); + assertEquals(1, connFiles.size()); + assertEquals( + expectedFile, + Files.getPosixFilePermissions(connFiles.get(0), LinkOption.NOFOLLOW_LINKS)); + } + } finally { + nestedHandler.close(); + } + } + + @Test + public void testCreateDirectoryUnderSharedNonSymlinkAncestor() throws IOException { + assumeTrue(isPosix(), "POSIX permissions required"); + Path sharedParent = tempDir.resolve("shared-parent"); + Files.createDirectory(sharedParent); + Files.setPosixFilePermissions(sharedParent, PosixFilePermissions.fromString("rwxr-xr-x")); + + Path leafDir = sharedParent.resolve("driver-logs"); + PerConnectionFileHandler subHandler = + new PerConnectionFileHandler(leafDir.toString(), Level.INFO); + try { + subHandler.publish(new LogRecord(Level.INFO, "global init")); + assertEquals( + PosixFilePermissions.fromString("rwx------"), + Files.getPosixFilePermissions(leafDir, LinkOption.NOFOLLOW_LINKS)); + assertEquals( + PosixFilePermissions.fromString("rwxr-xr-x"), + Files.getPosixFilePermissions(sharedParent, LinkOption.NOFOLLOW_LINKS)); + assertTrue(Files.exists(leafDir.resolve("BQ-JDBC-GLOBAL.log"), LinkOption.NOFOLLOW_LINKS)); + } finally { + subHandler.close(); + } + } + + @Test + public void testExistingDirectoryKeeps0755Permissions() throws IOException { + assumeTrue(isPosix(), "POSIX permissions required"); + Path existingDir = tempDir.resolve("existing-0755"); + Files.createDirectory(existingDir); + Set mode0755 = PosixFilePermissions.fromString("rwxr-xr-x"); + Files.setPosixFilePermissions(existingDir, mode0755); + + PerConnectionFileHandler existingDirHandler = + new PerConnectionFileHandler(existingDir.toString(), Level.INFO); + try { + existingDirHandler.publish(new LogRecord(Level.INFO, "preserve mode check")); + assertEquals(mode0755, Files.getPosixFilePermissions(existingDir, LinkOption.NOFOLLOW_LINKS)); + } finally { + existingDirHandler.close(); + } + } + + @Test + public void testSymbolicLinksAndNonRegularPathsAreRejected() throws IOException { + assumeTrue(isPosix(), "Symbolic link creation required"); + Path victimFile = tempDir.resolve("victim-secret.txt"); + Files.write(victimFile, "TOP-SECRET".getBytes(StandardCharsets.UTF_8)); + + Path realTargetDir = tempDir.resolve("real-dir"); + Files.createDirectory(realTargetDir); + Path symlinkLeafDir = tempDir.resolve("symlink-dir"); + Files.createSymbolicLink(symlinkLeafDir, realTargetDir); + + PerConnectionFileHandler symlinkDirHandler = + new PerConnectionFileHandler(symlinkLeafDir.toString(), Level.INFO); + symlinkDirHandler.setErrorManager(silentErrorManager()); + try { + symlinkDirHandler.publish(new LogRecord(Level.INFO, "must not write")); + assertFalse(Files.exists(realTargetDir.resolve("BQ-JDBC-GLOBAL.log"))); + } finally { + symlinkDirHandler.close(); + } + + Path symlinkGlobalDir = tempDir.resolve("symlink-global-dir"); + Files.createDirectory(symlinkGlobalDir); + Files.createSymbolicLink(symlinkGlobalDir.resolve("BQ-JDBC-GLOBAL.log"), victimFile); + PerConnectionFileHandler symlinkGlobalHandler = + new PerConnectionFileHandler(symlinkGlobalDir.toString(), Level.INFO); + symlinkGlobalHandler.setErrorManager(silentErrorManager()); + try { + symlinkGlobalHandler.publish(new LogRecord(Level.INFO, "must not clobber victim")); + assertEquals( + "TOP-SECRET", new String(Files.readAllBytes(victimFile), StandardCharsets.UTF_8)); + try (Stream stream = Files.list(symlinkGlobalDir)) { + assertTrue( + stream.anyMatch(p -> p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL-")), + "Handler should fall back to unique global log when primary is a symlink"); + } + } finally { + symlinkGlobalHandler.close(); + } + } + + @Test + public void testPercentTokensCollisionSuffixesAndNoLockFiles() throws IOException { + Path literalPercentDir = tempDir.resolve("logs-%t-%h-%g-%u"); + PerConnectionFileHandler pctHandler = + new PerConnectionFileHandler(literalPercentDir.toString(), Level.INFO); + try { + BigQueryJdbcMdc.registerInstance("BQ-JDBC-abcd-1111"); + pctHandler.publish(new LogRecord(Level.INFO, "conn one")); + BigQueryJdbcMdc.registerInstance("BQ-JDBC-abcd-2222"); + pctHandler.publish(new LogRecord(Level.INFO, "conn two")); + + assertTrue(Files.isDirectory(literalPercentDir, LinkOption.NOFOLLOW_LINKS)); + try (Stream stream = Files.list(literalPercentDir)) { + List files = stream.collect(Collectors.toList()); + assertFalse( + files.stream().anyMatch(p -> p.getFileName().toString().endsWith(".lck")), + "No JUL .lck sidecar files should be created"); + long abcdFiles = + files.stream().filter(p -> p.getFileName().toString().endsWith("-abcd.log")).count(); + assertEquals(2L, abcdFiles, "Colliding 4-char connection prefixes must get distinct files"); + } + } finally { + pctHandler.close(); + } + } + + @Test + public void testConcurrentGlobalHandlerContentionFallsBackToUniqueGlobalLog() throws IOException { + Path contendedDir = tempDir.resolve("contended-global"); + PerConnectionFileHandler first = + new PerConnectionFileHandler(contendedDir.toString(), Level.INFO); + PerConnectionFileHandler second = + new PerConnectionFileHandler(contendedDir.toString(), Level.INFO); + try { + first.publish(new LogRecord(Level.INFO, "first-owner-msg")); + for (int i = 0; i < 5; i++) { + PerConnectionFileHandler noGlobalRecords = + new PerConnectionFileHandler(contendedDir.toString(), Level.INFO); + noGlobalRecords.close(); + } + second.publish(new LogRecord(Level.INFO, "second-contender-msg")); + + String primaryContent = + new String( + Files.readAllBytes(contendedDir.resolve("BQ-JDBC-GLOBAL.log")), + StandardCharsets.UTF_8); + assertTrue(primaryContent.contains("first-owner-msg")); + assertFalse(primaryContent.contains("second-contender-msg")); + + try (Stream stream = Files.list(contendedDir)) { + List fallbacks = + stream + .filter(p -> p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL-")) + .collect(Collectors.toList()); + assertEquals(1, fallbacks.size()); + String fallbackContent = + new String(Files.readAllBytes(fallbacks.get(0)), StandardCharsets.UTF_8); + assertTrue(fallbackContent.contains("second-contender-msg")); + } + } finally { + second.close(); + first.close(); + } + } + + @Test + public void testForeignOwnedGlobalLogFallsBackAndHardLinkIsRejected() throws IOException { + assumeTrue(isPosix(), "POSIX links and ownership required"); + Path dir = tempDir.resolve("foreign-uid-dir"); + Files.createDirectory( + dir, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); + Path primaryGlobal = dir.resolve("BQ-JDBC-GLOBAL.log"); + Files.write(primaryGlobal, "FOREIGN-DATA".getBytes(StandardCharsets.UTF_8)); + + PerConnectionFileHandler.overrideUidForTesting = 999_999_999; + try { + // Directory itself is also checked against effective UID; when foreign-owned, directory is + // rejected cleanly without clobbering primaryGlobal. + PerConnectionFileHandler rejectedDirHandler = + new PerConnectionFileHandler(dir.toString(), Level.INFO); + rejectedDirHandler.setErrorManager(silentErrorManager()); + try { + rejectedDirHandler.publish(new LogRecord(Level.INFO, "should not write")); + assertEquals( + "FOREIGN-DATA", new String(Files.readAllBytes(primaryGlobal), StandardCharsets.UTF_8)); + } finally { + rejectedDirHandler.close(); + } + } finally { + PerConnectionFileHandler.overrideUidForTesting = null; + } + + // Hard-linked global file (nlink == 2) must not be written to in-place; falls back cleanly. + Path hardLinkDir = tempDir.resolve("hardlink-dir"); + Files.createDirectory(hardLinkDir); + Path target = tempDir.resolve("hardlink-target.txt"); + Files.write(target, "ORIGINAL".getBytes(StandardCharsets.UTF_8)); + Files.createLink(hardLinkDir.resolve("BQ-JDBC-GLOBAL.log"), target); + + PerConnectionFileHandler hardLinkHandler = + new PerConnectionFileHandler(hardLinkDir.toString(), Level.INFO); + try { + hardLinkHandler.publish(new LogRecord(Level.INFO, "isolated-from-hardlink")); + assertEquals("ORIGINAL", new String(Files.readAllBytes(target), StandardCharsets.UTF_8)); + try (Stream stream = Files.list(hardLinkDir)) { + assertTrue(stream.anyMatch(p -> p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL-"))); + } + } finally { + hardLinkHandler.close(); + } + } + + @Test + public void testInterruptedPublishPreservesInterruptFlagAndKeepsChannelAlive() + throws IOException { + BigQueryJdbcMdc.registerInstance("BQ-JDBC-intr1234"); + Thread.currentThread().interrupt(); + try { + handler.publish(new LogRecord(Level.INFO, "message while interrupted")); + assertTrue( + Thread.currentThread().isInterrupted(), + "Caller thread interrupt status must be preserved"); + } finally { + Thread.interrupted(); // clear interrupt flag for subsequent assertions + } + + handler.publish(new LogRecord(Level.INFO, "message after interrupt")); + Optional connLog = findLogFile("-intr.log"); + assertTrue(connLog.isPresent()); + String content = new String(Files.readAllBytes(connLog.get()), StandardCharsets.UTF_8); + assertTrue(content.contains("message while interrupted")); + assertTrue(content.contains("message after interrupt")); + } + + private static Optional findLogFileInDir(Path dir, String suffix) throws IOException { + try (Stream stream = Files.list(dir)) { + return stream + .filter( + p -> + p.getFileName().toString().startsWith("BQ-JDBC-") + && p.getFileName().toString().endsWith(suffix)) + .findFirst(); + } + } + + @Test + public void testResolveMaxLogFileBytesSystemPropertyValidation() { + assertEquals(1024L * 1024L * 1024L, PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES); + String prop = PerConnectionFileHandler.MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY; + String prev = System.getProperty(prop); + try { + System.setProperty(prop, "3000000000"); + assertEquals(3_000_000_000L, PerConnectionFileHandler.resolveMaxLogFileBytes()); + System.setProperty(prop, "-5"); + assertEquals( + PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES, + PerConnectionFileHandler.resolveMaxLogFileBytes()); + System.setProperty(prop, "512MB"); + assertEquals( + PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES, + PerConnectionFileHandler.resolveMaxLogFileBytes()); + // Repeated identical bad value does not re-emit ErrorManager warning + assertEquals( + PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES, + PerConnectionFileHandler.resolveMaxLogFileBytes()); + } finally { + if (prev == null) { + System.clearProperty(prop); + } else { + System.setProperty(prop, prev); + } + } + } + + @Test + public void testBackupFileRotationAndParameterContextRouting() throws IOException { + Path boundedDir = tempDir.resolve("bounded"); + long maxBytes = 1024L; + PerConnectionFileHandler defaultMaxHandler = + new PerConnectionFileHandler(tempDir.resolve("def_max").toString(), Level.INFO, 0L); + defaultMaxHandler.close(); + + ConnectionLogContext connCtx = + new ConnectionLogContext("rotc-uuid", ConnectionLogContext.ALL_VALUE); + assertEquals(ConnectionLogContext.ALL_VALUE, connCtx.levelValue()); + connCtx.setLevelValue(ConnectionLogContext.OFF_VALUE); + assertEquals(ConnectionLogContext.OFF_VALUE, connCtx.levelValue()); + assertEquals("rotc-uuid", connCtx.toString()); + assertNull(ConnectionLogContext.extractFromParameters(null)); + + PerConnectionFileHandler boundedHandler = + new PerConnectionFileHandler(boundedDir.toString(), Level.FINEST, maxBytes); + try { + for (int i = 0; i < 40; i++) { + boundedHandler.publish( + new LogRecord(Level.INFO, "Padding log line to exceed 1 KiB limit #" + i)); + } + BigQueryJdbcMdc.clear(); + for (int i = 0; i < 15; i++) { + LogRecord ctxRec = new LogRecord(Level.INFO, "Per-conn rotation line #" + i); + ctxRec.setParameters(new Object[] {connCtx}); + boundedHandler.publish(ctxRec); + } + LogRecord retryRecord = new LogRecord(Level.FINEST, "Retrying RPC"); + retryRecord.setParameters(new Object[] {"BigQuery retried method: getQueryResults"}); + boundedHandler.publish(retryRecord); + assertTrue(BigQueryJdbcRootLogger.getFormatter().format(retryRecord).contains("[NO_CONN]")); + } finally { + boundedHandler.close(); + } + + Path boundedGlobal = boundedDir.resolve("BQ-JDBC-GLOBAL.log"); + Path boundedBackup = boundedDir.resolve("BQ-JDBC-GLOBAL.1.log"); + assertTrue(Files.size(boundedGlobal) > 0 && Files.size(boundedGlobal) <= maxBytes); + assertTrue(Files.size(boundedBackup) > 0 && Files.size(boundedBackup) <= maxBytes); + assertFalse(Files.exists(boundedDir.resolve("BQ-JDBC-GLOBAL.2.log"))); + assertTrue(findLogFileInDir(boundedDir, "-rotc.log").isPresent()); + assertTrue(findLogFileInDir(boundedDir, "-rotc.1.log").isPresent()); + assertFalse(findLogFileInDir(boundedDir, "-BigQ.log").isPresent()); + + if (isPosix()) { + Set expected0600 = PosixFilePermissions.fromString("rw-------"); + assertEquals( + expected0600, Files.getPosixFilePermissions(boundedBackup, LinkOption.NOFOLLOW_LINKS)); + assertEquals( + expected0600, Files.getPosixFilePermissions(boundedGlobal, LinkOption.NOFOLLOW_LINKS)); + assertEquals( + expected0600, + Files.getPosixFilePermissions( + findLogFileInDir(boundedDir, "-rotc.1.log").get(), LinkOption.NOFOLLOW_LINKS)); + } + } + + @Test + public void testRotationDeletesSymlinkBackupAndReplacesExistingBackup() throws IOException { + assumeTrue(isPosix(), "POSIX symbolic links required"); + long maxBytes = 1024L; + Path symDir = tempDir.resolve("sym_rot"); + Files.createDirectories(symDir); + Path untouchedTarget = tempDir.resolve("untouched.txt"); + Files.write(untouchedTarget, "safe".getBytes(StandardCharsets.UTF_8)); + Files.createSymbolicLink(symDir.resolve("BQ-JDBC-GLOBAL.1.log"), untouchedTarget); + PerConnectionFileHandler symRotHandler = + new PerConnectionFileHandler(symDir.toString(), Level.INFO, maxBytes); + symRotHandler.setErrorManager(silentErrorManager()); + try { + for (int i = 0; i < 12; i++) { + symRotHandler.publish(new LogRecord(Level.INFO, "Symlink backup rotation line #" + i)); + } + assertEquals("safe", new String(Files.readAllBytes(untouchedTarget), StandardCharsets.UTF_8)); + assertFalse(Files.isSymbolicLink(symDir.resolve("BQ-JDBC-GLOBAL.1.log"))); + + // Simulated UID mismatch on existing .1.log still rotates cleanly via atomic move + PerConnectionFileHandler.overrideUidForTesting = 888_888_888; + try { + for (int i = 0; i < 12; i++) { + symRotHandler.publish(new LogRecord(Level.INFO, "Foreign backup rotation line #" + i)); + } + } finally { + PerConnectionFileHandler.overrideUidForTesting = null; + } + assertTrue(Files.exists(symDir.resolve("BQ-JDBC-GLOBAL.1.log"), LinkOption.NOFOLLOW_LINKS)); + assertTrue( + new String( + Files.readAllBytes(symDir.resolve("BQ-JDBC-GLOBAL.log")), StandardCharsets.UTF_8) + .contains("rotation line #11")); + } finally { + symRotHandler.close(); + } + } + + @Test + public void testBlockedBackupDirectoryTruncatesWithMarkerAndWritesLargeChunks() + throws IOException { + long maxBytes = 1024L; + Path fallbackDir = tempDir.resolve("fallback_rot"); + Files.createDirectories(fallbackDir.resolve("BQ-JDBC-GLOBAL.1.log")); + PerConnectionFileHandler fallbackHandler = + new PerConnectionFileHandler(fallbackDir.toString(), Level.INFO, maxBytes); + fallbackHandler.setErrorManager(silentErrorManager()); + try { + for (int i = 0; i < 20; i++) { + fallbackHandler.publish( + new LogRecord(Level.INFO, "Fallback line exceeding 1 KiB cap #" + i)); + } + } finally { + fallbackHandler.close(); + } + Path fallbackGlobal = fallbackDir.resolve("BQ-JDBC-GLOBAL.log"); + assertTrue(Files.size(fallbackGlobal) > 0 && Files.size(fallbackGlobal) <= maxBytes); + String truncatedContent = + new String(Files.readAllBytes(fallbackGlobal), StandardCharsets.UTF_8); + assertTrue(truncatedContent.contains("[LOG TRUNCATED: backup rotation failed (IOException)]")); + assertTrue(truncatedContent.contains("cap #19")); + + // Large payload (> 8 KiB) exercises 8 KiB chunked ByteBuffer writes without data loss + Path chunkDir = tempDir.resolve("chunk_write"); + PerConnectionFileHandler chunkHandler = + new PerConnectionFileHandler(chunkDir.toString(), Level.INFO); + try { + StringBuilder largePayload = new StringBuilder(20_000); + for (int i = 0; i < 2_000; i++) { + largePayload.append("0123456789"); + } + chunkHandler.publish(new LogRecord(Level.INFO, largePayload.toString())); + String written = + new String( + Files.readAllBytes(chunkDir.resolve("BQ-JDBC-GLOBAL.log")), StandardCharsets.UTF_8); + assertTrue(written.contains(largePayload.toString())); + // Exercise DeduplicatingErrorManager on repeated vs distinct error keys + ErrorManager em = chunkHandler.getErrorManager(); + assertNotNull(em); + em.error("test-dedup-msg", null, ErrorManager.WRITE_FAILURE); + em.error("test-dedup-msg", null, ErrorManager.WRITE_FAILURE); + } finally { + chunkHandler.close(); + } + } + + @Test + public void testConcurrentCloseAndPublishLeavesNoOpenConnectionFiles() throws Exception { + Path raceDir = tempDir.resolve("race"); + for (int round = 0; round < 15; round++) { + PerConnectionFileHandler raceHandler = + new PerConnectionFileHandler( + raceDir.resolve("r" + round).toString(), Level.INFO, 0L, true); + String connId = "race-" + round; + raceHandler.registerConnection(connId, Level.INFO); + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(3); + Runnable publishLoop = + () -> { + try (BigQueryJdbcMdc.MdcCloseable m = BigQueryJdbcMdc.registerInstance(connId)) { + start.await(); + for (int i = 0; i < 10; i++) { + raceHandler.publish(new LogRecord(Level.INFO, "race msg " + i)); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }; + try { + Future pubTask1 = pool.submit(publishLoop); + Future pubTask2 = pool.submit(publishLoop); + final int r = round; + Future closeTask = + pool.submit( + () -> { + try { + start.await(); + if (r % 2 == 0) { + raceHandler.closeHandler(connId); + } else { + raceHandler.close(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + start.countDown(); + pubTask1.get(5, TimeUnit.SECONDS); + pubTask2.get(5, TimeUnit.SECONDS); + closeTask.get(5, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + Path roundDir = raceDir.resolve("r" + round); + try (Stream before = Files.list(roundDir)) { + long countAfterClose = before.count(); + try (BigQueryJdbcMdc.MdcCloseable m = BigQueryJdbcMdc.registerInstance(connId)) { + raceHandler.publish(new LogRecord(Level.INFO, "post-close")); + } + try (Stream after = Files.list(roundDir)) { + assertEquals(countAfterClose, after.count()); + } + } finally { + raceHandler.close(); + } + } + } + + @Test + public void testPostCloseResultSetAndStringParamsDoNotResurrectHandlers() throws Exception { + Path leakDir = tempDir.resolve("no_leak"); + String connId = "dead-conn-uuid"; + try { + BigQueryJdbcRootLogger.registerConnection(connId, "7", leakDir.toString()); + ConnectionLogContext activeCtx = BigQueryJdbcRootLogger.getConnectionContext(connId); + assertNotNull(activeCtx); + assertTrue(BigQueryJdbcRootLogger.isConnectionActive(connId)); + + BigQueryStatement mockStmt = mock(BigQueryStatement.class); + mockStmt.connectionId = connId; + Schema schema = Schema.of(FieldList.of(Field.of("col", StandardSQLTypeName.INT64))); + BigQueryJsonResultSet rs = + BigQueryJsonResultSet.of(schema, 0, null, mockStmt, new Future[0]); + BigQueryJdbcResultSetLogger activeStructLogger = rs.LOG.getArrowStructLogger(); + + rs.LOG.finestTrace("beforeClose", "Before close trace"); + Optional initialLog = findLogFileInDir(leakDir, "-dead.log"); + assertTrue(initialLog.isPresent()); + + rs.close(); + BigQueryJdbcRootLogger.closeConnectionHandler(connId); + assertFalse(BigQueryJdbcRootLogger.isConnectionActive(connId)); + assertEquals(ConnectionLogContext.OFF_VALUE, activeCtx.levelValue()); + Files.delete(initialLog.get()); + + assertThrows(SQLException.class, () -> rs.getShort(1)); + assertThrows(SQLException.class, () -> rs.findColumn(null)); + activeStructLogger.finestTrace("getAttributes"); + BigQueryJdbcResultSetLogger.getLogger(BigQueryArrowStruct.class, connId) + .finestTrace("getAttributes"); + + assertFalse(findLogFileInDir(leakDir, "-dead.log").isPresent()); + + Formatter formatter = BigQueryJdbcRootLogger.getFormatter(); + LogRecord retryRecord = new LogRecord(Level.FINEST, "Retrying RPC"); + retryRecord.setParameters(new Object[] {"BigQuery retried method: getQueryResults"}); + assertTrue(formatter.format(retryRecord).contains("[NO_CONN]")); + } finally { + BigQueryJdbcRootLogger.resetForTest(); + } + } + + @Test + public void testFailedConnectionConstructorCleansUpActiveRegistration() { + Path failLogDir = tempDir.resolve("failed_conn_logs"); + int baselineActive = BigQueryJdbcRootLogger.activeConnectionCount(); + String invalidAuthUrl = + new URIBuilder(TestUtilities.getBaseConnectionUrl()) + .append("ProjectId", "test-proj") + .append("OAuthType", 99) + .append("LogLevel", 6) + .append("LogPath", failLogDir.toString()) + .toString(); + + try { + assertThrows(RuntimeException.class, () -> new BigQueryConnection(invalidAuthUrl)); + assertEquals(baselineActive, BigQueryJdbcRootLogger.activeConnectionCount()); + } finally { + BigQueryJdbcRootLogger.resetForTest(); + } + } + + @Test + public void testUnclosedGarbageCollectedConnectionsReclaimLogHandlersAndSlots() throws Exception { + Path leakedLogDir = tempDir.resolve("leaked_conn_logs"); + BigQueryJdbcRootLogger.resetForTest(); + int leakedCount = 20; + String url = + new URIBuilder(TestUtilities.getBaseConnectionUrl()) + .append("OAuthType", 2) + .append("OAuthAccessToken", "RedactedToken") + .append("ProjectId", "test-proj") + .append("LogLevel", 7) + .append("LogPath", leakedLogDir.toString()) + .toString(); + + try { + List leakedIds = allocateAndDropLeakedConnections(url, leakedCount); + assertEquals(leakedCount, leakedIds.size()); + + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos + && (BigQueryJdbcRootLogger.activeConnectionCount() > 0 + || countManagedRootFileHandlers() > 0)) { + System.gc(); + Thread.sleep(50L); + } + + assertEquals(0, BigQueryJdbcRootLogger.activeConnectionCount()); + assertEquals(0, countManagedRootFileHandlers()); + assertEquals(Level.OFF, BigQueryJdbcRootLogger.getRootLogger().getLevel()); + for (String id : leakedIds) { + assertFalse(BigQueryJdbcRootLogger.isConnectionActive(id)); + } + + // Verify BQ-JDBC-GLOBAL.log channel and sentinel lock were closed and released upon GC + try (Stream before = Files.list(leakedLogDir)) { + long fallbackBefore = + before.filter(p -> p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL-")).count(); + assertEquals(0L, fallbackBefore); + } + PerConnectionFileHandler verifyReleased = + new PerConnectionFileHandler(leakedLogDir.toString(), Level.INFO); + try { + verifyReleased.publish(new LogRecord(Level.INFO, "verify-primary-reacquired")); + try (Stream after = Files.list(leakedLogDir)) { + long fallbackAfter = + after.filter(p -> p.getFileName().toString().startsWith("BQ-JDBC-GLOBAL-")).count(); + assertEquals(0L, fallbackAfter); + } + } finally { + verifyReleased.close(); + } + } finally { + BigQueryJdbcRootLogger.resetForTest(); + } + } + + @Test + public void testClosedWriterOnRotationFailureEvictsAndRecovers() throws IOException { + Path recoverDir = tempDir.resolve("recover_rot"); + PerConnectionFileHandler recoverHandler = + new PerConnectionFileHandler(recoverDir.toString(), Level.INFO, 512L, true); + recoverHandler.setErrorManager(silentErrorManager()); + String connId = "BQ-JDBC-rcvr1234"; + recoverHandler.registerConnection(connId, Level.INFO); + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connId)) { + recoverHandler.publish(new LogRecord(Level.INFO, "initial-record")); + Optional firstFile = findLogFileInDir(recoverDir, "-rcvr.log"); + assertTrue(firstFile.isPresent()); + + Files.delete(firstFile.get()); + Files.delete(recoverDir); + + for (int i = 0; i < 10; i++) { + recoverHandler.publish( + new LogRecord(Level.INFO, "Trigger rotation while directory is missing #" + i)); + } + + Files.createDirectories(recoverDir); + recoverHandler.publish(new LogRecord(Level.INFO, "recovered-after-dir-restored")); + + Optional reopenedFile = findLogFileInDir(recoverDir, "-rcvr.log"); + assertTrue(reopenedFile.isPresent()); + assertTrue( + new String(Files.readAllBytes(reopenedFile.get()), StandardCharsets.UTF_8) + .contains("recovered-after-dir-restored")); + } finally { + recoverHandler.close(); + } + } + + @Test + public void testFailedLogOpenUsesRetryBackoff() throws IOException { + Path unusableDir = tempDir.resolve("backoff_dir"); + AtomicInteger openCalls = new AtomicInteger(); + PerConnectionFileHandler backoffHandler = + new PerConnectionFileHandler(unusableDir.toString(), Level.INFO, 0L, true) { + @Override + ChannelLogWriter createLogWriter( + String id, Path logDir, Level writerLevel, long limitBytes) { + openCalls.incrementAndGet(); + return null; + } + }; + backoffHandler.setErrorManager(silentErrorManager()); + String connId = "BQ-JDBC-bkof1234"; + backoffHandler.registerConnection(connId, Level.INFO); + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connId)) { + for (int i = 0; i < 50; i++) { + backoffHandler.publish(new LogRecord(Level.INFO, "record-" + i)); + } + // 1 attempt for connection slot + 1 fallback attempt for defaultWriter across all 50 records + assertEquals(2, openCalls.get()); + } finally { + backoffHandler.close(); + } + } + + private static List allocateAndDropLeakedConnections(String url, int count) + throws SQLException { + BigQueryDriver driver = new BigQueryDriver(); + List ids = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + Connection leaked = driver.connect(url, new Properties()); + ids.add(leaked.unwrap(BigQueryConnection.class).getConnectionId()); + } + assertEquals(count, BigQueryJdbcRootLogger.activeConnectionCount()); + assertEquals(1, countManagedRootFileHandlers()); + return ids; + } + + private static int countManagedRootFileHandlers() { + int count = 0; + for (Handler h : BigQueryJdbcRootLogger.getRootLogger().getHandlers()) { + if (h instanceof PerConnectionFileHandler) { + count++; + } + } + return count; + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java index 26e618ac86d7..a486d28ecd7b 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java @@ -17,43 +17,404 @@ package com.google.cloud.bigquery.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.jdbc.utils.TestUtilities.TestConnectionListener; +import java.sql.Connection; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; import javax.sql.PooledConnection; import org.junit.jupiter.api.Test; public class PooledConnectionDataSourceTest { private static final Long LISTENER_POOL_SIZE = 20L; private static final Long CONNECTION_POOL_SIZE = 20L; - private static final Long DEFAULT_LISTENER_POOL_SIZE = 10L; - private static final Long DEFAULT_CONNECTION_POOL_SIZE = 10L; + + private static String buildTestUrl(long connectionPoolSize, long listenerPoolSize) { + return BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "test-project") + .append("ConnectionPoolSize", connectionPoolSize) + .append("ListenerPoolSize", listenerPoolSize) + .toString(); + } @Test public void testGetPooledConnection() throws SQLException { - String connectionUrl = - "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;OAuthType=3;ProjectId=testProject;ConnectionPoolSize=20;ListenerPoolSize=20;"; - - BigQueryConnection bqConnection = mock(BigQueryConnection.class); - doReturn(connectionUrl).when(bqConnection).getConnectionUrl(); - doReturn(LISTENER_POOL_SIZE).when(bqConnection).getListenerPoolSize(); - doReturn(CONNECTION_POOL_SIZE).when(bqConnection).getConnectionPoolSize(); - PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); - pooledDataSource.setConnection(bqConnection); + pooledDataSource.setURL(buildTestUrl(CONNECTION_POOL_SIZE, LISTENER_POOL_SIZE)); pooledDataSource.setListenerPoolSize(LISTENER_POOL_SIZE); pooledDataSource.setConnectionPoolSize(CONNECTION_POOL_SIZE); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - assertTrue(pooledConnection instanceof BigQueryPooledConnection); - BigQueryPooledConnection bqPooledConnection = (BigQueryPooledConnection) pooledConnection; - assertEquals(LISTENER_POOL_SIZE, bqPooledConnection.getListenerPoolSize()); - assertNotNull(pooledDataSource.getConnectionPoolManager()); - assertEquals( - CONNECTION_POOL_SIZE, pooledDataSource.getConnectionPoolManager().getConnectionPoolSize()); + try { + assertNotNull(pooledConnection); + assertTrue(pooledConnection instanceof BigQueryPooledConnection); + BigQueryPooledConnection bqPooledConnection = (BigQueryPooledConnection) pooledConnection; + assertEquals(LISTENER_POOL_SIZE, bqPooledConnection.getListenerPoolSize()); + assertNotNull(pooledDataSource.getConnectionPoolManager()); + assertEquals( + CONNECTION_POOL_SIZE, + pooledDataSource.getConnectionPoolManager().getConnectionPoolSize()); + } finally { + pooledConnection.close(); + } + } + + @Test + public void testGetPooledConnectionWithCredentials_throwsUnsupportedOperationException() { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(CONNECTION_POOL_SIZE, LISTENER_POOL_SIZE)); + + assertThrows( + UnsupportedOperationException.class, + () -> pooledDataSource.getPooledConnection("user", "password")); + } + + @Test + public void testGetPooledConnection_honorsUrlConfiguredPoolSize() throws SQLException { + PooledConnectionDataSource urlOnlyDataSource = new PooledConnectionDataSource(); + urlOnlyDataSource.setURL(buildTestUrl(5L, 7L)); + + PooledConnection pooledConnection = urlOnlyDataSource.getPooledConnection(); + try { + assertEquals(5L, urlOnlyDataSource.getConnectionPoolManager().getConnectionPoolSize()); + assertEquals(7L, ((BigQueryPooledConnection) pooledConnection).getListenerPoolSize()); + } finally { + pooledConnection.close(); + } + } + + @Test + public void testOverlappingCheckouts_useDistinctPhysicalConnections() throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + + PooledConnection pc1 = pooledDataSource.getPooledConnection(); + PooledConnection pc2 = pooledDataSource.getPooledConnection(); + try (Connection c1 = pc1.getConnection(); + Connection c2 = pc2.getConnection()) { + assertNotSame(pc1, pc2); + BigQueryConnection physical1 = c1.unwrap(BigQueryConnection.class); + BigQueryConnection physical2 = c2.unwrap(BigQueryConnection.class); + assertNotSame(physical1, physical2); + assertFalse(physical1.isClosed()); + assertFalse(physical2.isClosed()); + } finally { + pc1.close(); + pc2.close(); + } + } + + @Test + public void + testReuseAfterLogicalClose_reusesPhysicalInFreshPooledConnectionAndRetiresStaleHolder() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + + PooledConnection pc1 = pooledDataSource.getPooledConnection(); + Connection c1 = pc1.getConnection(); + BigQueryConnection physical1 = c1.unwrap(BigQueryConnection.class); + c1.close(); + + PooledConnectionListener poolManager = pooledDataSource.getConnectionPoolManager(); + assertEquals(1, poolManager.getConnectionPoolCurrentCapacity()); + + PooledConnection pcReused = pooledDataSource.getPooledConnection(); + assertNotSame(pc1, pcReused); + assertTrue(poolManager.isConnectionPoolEmpty()); + + // A stale reference to pc1 retained by the prior caller cannot reclaim or close physical1 + // (M02). + BigQueryJdbcException retiredEx = assertThrows(BigQueryJdbcException.class, pc1::getConnection); + assertTrue(retiredEx.getMessage().contains("retired")); + + Connection cReused = pcReused.getConnection(); + assertSame(physical1, cReused.unwrap(BigQueryConnection.class)); + pc1.close(); + assertFalse(physical1.isClosed(), "Closing retired holder must not close recycled physical"); + assertFalse(cReused.isClosed()); + + PooledConnection pcConcurrent = pooledDataSource.getPooledConnection(); + try (Connection cConcurrent = pcConcurrent.getConnection()) { + assertNotSame(pcReused, pcConcurrent); + assertNotSame(physical1, cConcurrent.unwrap(BigQueryConnection.class)); + } finally { + cReused.close(); + pcReused.close(); + pcConcurrent.close(); + } + } + + @Test + public void testCheckoutSkipsDirectlyReacquiredEntry_preservesActivePhysicalConnection() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + + PooledConnection pcInUse = pooledDataSource.getPooledConnection(); + BigQueryConnection physical1; + try (Connection c1 = pcInUse.getConnection()) { + physical1 = c1.unwrap(BigQueryConnection.class); + } + Connection directHandle = pcInUse.getConnection(); + + PooledConnection pcNext = pooledDataSource.getPooledConnection(); + BigQueryConnection physical2; + try (Connection cNext = pcNext.getConnection()) { + physical2 = cNext.unwrap(BigQueryConnection.class); + assertNotSame(physical1, physical2); + assertTrue(pooledDataSource.getConnectionPoolManager().isConnectionPoolEmpty()); + } finally { + pcNext.close(); + } + + assertTrue(physical2.isClosed()); + assertFalse(physical1.isClosed()); + assertFalse(directHandle.isClosed()); + directHandle.close(); + pcInUse.close(); + } + + @Test + public void testCheckoutSkipsExternallyManagedEntry_preservesExternalPoolOwnership() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + + PooledConnection pcExternal = pooledDataSource.getPooledConnection(); + pcExternal.addConnectionEventListener(new TestConnectionListener()); + BigQueryConnection externalPhysical; + try (Connection cExternal = pcExternal.getConnection()) { + externalPhysical = cExternal.unwrap(BigQueryConnection.class); + } + + PooledConnection pcNext = pooledDataSource.getPooledConnection(); + BigQueryConnection nextPhysical; + try (Connection cNext = pcNext.getConnection()) { + nextPhysical = cNext.unwrap(BigQueryConnection.class); + assertNotSame(externalPhysical, nextPhysical); + } finally { + pcNext.close(); + } + + assertTrue(nextPhysical.isClosed()); + assertFalse(externalPhysical.isClosed()); + try (Connection cExternalReused = pcExternal.getConnection()) { + assertSame(externalPhysical, cExternalReused.unwrap(BigQueryConnection.class)); + } finally { + pcExternal.close(); + } + } + + @Test + public void testCheckoutAfterIdlePhysicalClose_createsFreshOpenPhysicalConnection() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + + PooledConnection pcClosed = pooledDataSource.getPooledConnection(); + BigQueryConnection closedPhysical; + try (Connection cClosed = pcClosed.getConnection()) { + closedPhysical = cClosed.unwrap(BigQueryConnection.class); + } + pcClosed.close(); + assertTrue(closedPhysical.isClosed()); + assertTrue(pooledDataSource.getConnectionPoolManager().isConnectionPoolEmpty()); + + PooledConnection pcNext = pooledDataSource.getPooledConnection(); + try (Connection cNext = pcNext.getConnection()) { + BigQueryConnection nextPhysical = cNext.unwrap(BigQueryConnection.class); + assertNotSame(closedPhysical, nextPhysical); + assertFalse(nextPhysical.isClosed()); + } finally { + pcNext.close(); + } + } + + @Test + public void testConcurrentCheckoutsAndReturns_threadSafeAndBounded() throws Exception { + final long poolSize = 4L; + final int threadCount = 12; + final int iterationsPerThread = 15; + + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(poolSize, 10L)); + + Set activePhysicalConnections = ConcurrentHashMap.newKeySet(); + Set allObservedPhysicalConnections = ConcurrentHashMap.newKeySet(); + Set observedPooledConnections = ConcurrentHashMap.newKeySet(); + CountDownLatch startLatch = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(threadCount); + List> futures = new ArrayList<>(); + + try { + for (int i = 0; i < threadCount; i++) { + futures.add( + executor.submit( + () -> { + startLatch.await(); + for (int iter = 0; iter < iterationsPerThread; iter++) { + PooledConnection pc = pooledDataSource.getPooledConnection(); + assertNotNull(pc); + observedPooledConnections.add(pc); + try (Connection conn = pc.getConnection()) { + BigQueryConnection physical = conn.unwrap(BigQueryConnection.class); + allObservedPhysicalConnections.add(physical); + assertTrue( + activePhysicalConnections.add(physical), + "Physical connection must not be shared across concurrent checkouts"); + try { + conn.setClientInfo("worker", Thread.currentThread().getName()); + LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(250)); + assertEquals( + Thread.currentThread().getName(), conn.getClientInfo("worker")); + } finally { + activePhysicalConnections.remove(physical); + } + } + } + return null; + })); + } + + startLatch.countDown(); + for (Future future : futures) { + future.get(30, TimeUnit.SECONDS); + } + + PooledConnectionListener poolManager = pooledDataSource.getConnectionPoolManager(); + assertNotNull(poolManager); + int retainedIdle = poolManager.getConnectionPoolCurrentCapacity(); + assertTrue(retainedIdle <= (int) poolSize); + long closedOverflowCount = + allObservedPhysicalConnections.stream().filter(BigQueryConnection::isClosed).count(); + assertEquals(allObservedPhysicalConnections.size() - retainedIdle, closedOverflowCount); + } finally { + executor.shutdownNow(); + for (PooledConnection pc : observedPooledConnections) { + pc.close(); + } + while (pooledDataSource.getConnectionPoolManager() != null + && !pooledDataSource.getConnectionPoolManager().isConnectionPoolEmpty()) { + PooledConnection idle = pooledDataSource.getPooledConnection(); + idle.close(); + } + } + } + + @Test + public void testExternalManagerEvictionSequenceAndSingleSlotListenerCapacity() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + // ListenerPoolSize=1 must remain available to an external pool manager (R16). + pooledDataSource.setURL(buildTestUrl(4L, 1L)); + + PooledConnection pcExternal = pooledDataSource.getPooledConnection(); + TestConnectionListener externalListener = new TestConnectionListener(); + pcExternal.addConnectionEventListener(externalListener); + + BigQueryConnection externalPhysical; + try (Connection cExternal = pcExternal.getConnection()) { + externalPhysical = cExternal.unwrap(BigQueryConnection.class); + } + assertEquals(1, externalListener.getConnectionClosedCount()); + assertTrue( + pooledDataSource.getConnectionPoolManager().isConnectionPoolEmpty(), + "Externally managed holder must not double-populate the internal idle pool"); + + // External manager retirement sequence: removeConnectionEventListener(this) followed by close() + // must never allow a concurrent getPooledConnection() to hijack externalPhysical (m-4). + pcExternal.removeConnectionEventListener(externalListener); + PooledConnection pcConcurrent = pooledDataSource.getPooledConnection(); + pcExternal.close(); + + assertTrue(externalPhysical.isClosed()); + try (Connection cConcurrent = pcConcurrent.getConnection()) { + BigQueryConnection concurrentPhysical = cConcurrent.unwrap(BigQueryConnection.class); + assertNotSame(externalPhysical, concurrentPhysical); + assertFalse(concurrentPhysical.isClosed()); + } finally { + pcConcurrent.close(); + } + } + + @Test + public void testClaimPhysicalForReuse_rejectsInUseClosedAndRetiredHolders() throws SQLException { + PooledConnectionListener poolManager = new PooledConnectionListener(4L); + + BigQueryConnection mockPhysical1 = mock(BigQueryConnection.class); + doReturn(10L).when(mockPhysical1).getListenerPoolSize(); + BigQueryPooledConnection pcInUse = new BigQueryPooledConnection(mockPhysical1); + pcInUse.registerInternalPoolListener(poolManager); + Connection activeHandle = pcInUse.getConnection(); + + assertNull(pcInUse.claimPhysicalForReuse(poolManager)); + assertTrue(pcInUse.inUse()); + activeHandle.close(); + + assertSame(mockPhysical1, pcInUse.claimPhysicalForReuse(poolManager)); + assertNull(pcInUse.claimPhysicalForReuse(poolManager)); + + BigQueryConnection mockPhysical2 = mock(BigQueryConnection.class); + doReturn(10L).when(mockPhysical2).getListenerPoolSize(); + BigQueryPooledConnection pcClosed = new BigQueryPooledConnection(mockPhysical2); + pcClosed.registerInternalPoolListener(poolManager); + pcClosed.close(); + assertNull(pcClosed.claimPhysicalForReuse(poolManager)); + } + + @Test + public void testStandalonePooledConnectionListenerOnDataSourceConnection_closesOverflowIdle() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + PooledConnectionListener standaloneListener = new PooledConnectionListener(1L); + + PooledConnection pc1 = pooledDataSource.getPooledConnection(); + PooledConnection pc2 = pooledDataSource.getPooledConnection(); + pc1.addConnectionEventListener(standaloneListener); + pc2.addConnectionEventListener(standaloneListener); + + try { + BigQueryConnection physical1; + BigQueryConnection physical2; + Connection c1 = pc1.getConnection(); + Connection c2 = pc2.getConnection(); + physical1 = c1.unwrap(BigQueryConnection.class); + physical2 = c2.unwrap(BigQueryConnection.class); + + c1.close(); + assertEquals(1, standaloneListener.getConnectionPoolCurrentCapacity()); + assertTrue(pooledDataSource.getConnectionPoolManager().isConnectionPoolEmpty()); + assertFalse(physical1.isClosed()); + + // Returning pc2 when standaloneListener is at capacity (1) must close physical2 (R1-5). + c2.close(); + assertEquals(1, standaloneListener.getConnectionPoolCurrentCapacity()); + assertTrue(physical2.isClosed()); + assertFalse(physical1.isClosed()); + } finally { + pc1.close(); + pc2.close(); + } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionListenerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionListenerTest.java index 8e8884435940..0d0eb1104186 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionListenerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionListenerTest.java @@ -20,19 +20,26 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import com.google.cloud.bigquery.jdbc.utils.TestUtilities.TestConnectionListener; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; +import javax.sql.ConnectionEvent; +import javax.sql.PooledConnection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class PooledConnectionListenerTest { private BigQueryConnection bigQueryConnection; - private static final Long LISTENER_POOL_SIZE = 10L; + private static final Long LISTENER_POOL_SIZE = 7L; private static final Long CONNECTION_POOL_SIZE = 10L; @BeforeEach @@ -46,7 +53,7 @@ public void setUp() throws IOException, SQLException { @Test public void testAddConnectionListener() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -57,7 +64,7 @@ public void testAddConnectionListener() throws SQLException { @Test public void testRemoveConnectionListener() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -77,7 +84,7 @@ public void testConnectionHandleClosedByConnection() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -91,7 +98,8 @@ public void testConnectionHandleClosedByConnection() throws SQLException { } @Test - public void testConnectionHandleClosedByPooledConnection() throws SQLException { + public void testPooledConnectionClose_closesPhysicalConnectionWithoutRequeuing() + throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); assertFalse(pooledConnection.inUse()); Connection connection = pooledConnection.getConnection(); @@ -99,7 +107,7 @@ public void testConnectionHandleClosedByPooledConnection() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -107,9 +115,11 @@ public void testConnectionHandleClosedByPooledConnection() throws SQLException { pooledConnection.close(); assertFalse(pooledConnection.inUse()); - assertFalse(listener.isConnectionPoolEmpty()); - assertEquals(1, listener.getConnectionPoolCurrentCapacity()); - assertTrue(pooledConnection.isListenerPooled(listener)); + assertTrue(connection.isClosed()); + assertTrue(listener.isConnectionPoolEmpty()); + assertEquals(0, listener.getConnectionPoolCurrentCapacity()); + assertFalse(pooledConnection.isListenerPooled(listener)); + verify(bigQueryConnection).close(); } @Test @@ -121,7 +131,7 @@ public void testFireConnectionError() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -142,7 +152,7 @@ public void testGetConnectionWhenPoolEmpty() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -152,7 +162,7 @@ public void testGetConnectionWhenPoolEmpty() throws SQLException { } @Test - public void testGetConnectionWhenPoolNonEmpty() throws SQLException { + public void testGetConnectionWhenPoolNonEmpty_removesCheckedOutConnection() throws SQLException { BigQueryPooledConnection pooledConnection = new BigQueryPooledConnection(bigQueryConnection); assertFalse(pooledConnection.inUse()); Connection connection = pooledConnection.getConnection(); @@ -160,7 +170,7 @@ public void testGetConnectionWhenPoolNonEmpty() throws SQLException { assertFalse(connection.isClosed()); assertTrue(pooledConnection.inUse()); - PooledConnectionListener listener = new PooledConnectionListener(LISTENER_POOL_SIZE); + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); assertEquals(CONNECTION_POOL_SIZE, listener.getConnectionPoolSize()); assertEquals(LISTENER_POOL_SIZE, pooledConnection.getListenerPoolSize()); pooledConnection.addConnectionEventListener(listener); @@ -171,6 +181,193 @@ public void testGetConnectionWhenPoolNonEmpty() throws SQLException { assertFalse(listener.isConnectionPoolEmpty()); assertTrue(pooledConnection.isListenerPooled(listener)); - assertNotNull(listener.getPooledConnection()); + PooledConnection checkedOut = listener.getPooledConnection(); + assertSame(pooledConnection, checkedOut); + assertTrue(listener.isConnectionPoolEmpty()); + assertEquals(0, listener.getConnectionPoolCurrentCapacity()); + assertNull(listener.getPooledConnection()); + } + + @Test + public void testReturnWhenPoolAtCapacity_closesExcessWhenSoleListener() throws SQLException { + PooledConnectionListener listener = new PooledConnectionListener(1L); + + BigQueryConnection bqConn1 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn1).getListenerPoolSize(); + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(bqConn1); + pc1.addConnectionEventListener(listener); + + BigQueryConnection bqConn2 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn2).getListenerPoolSize(); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(bqConn2); + pc2.addConnectionEventListener(listener); + + Connection c1 = pc1.getConnection(); + Connection c2 = pc2.getConnection(); + + c1.close(); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + verify(bqConn1, never()).close(); + + c2.close(); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + verify(bqConn2).close(); + } + + @Test + public void testReturnWhenPoolAtCapacity_prunesStaleInUseEntryBeforeRejecting() + throws SQLException { + PooledConnectionListener listener = new PooledConnectionListener(1L); + + BigQueryConnection bqConn1 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn1).getListenerPoolSize(); + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(bqConn1); + pc1.addConnectionEventListener(listener); + + BigQueryConnection bqConn2 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn2).getListenerPoolSize(); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(bqConn2); + pc2.addConnectionEventListener(listener); + + pc1.getConnection().close(); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + + // Re-acquiring pc1 directly makes its pooled entry stale (inUse == true). + Connection directConn1 = pc1.getConnection(); + Connection c2 = pc2.getConnection(); + c2.close(); + + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + verify(bqConn2, never()).close(); + assertSame(pc2, listener.getPooledConnection()); + directConn1.close(); + } + + @Test + public void testReturnWhenPoolAtCapacity_keepsPhysicalOpenWhenExternalListenerPresent() + throws SQLException { + PooledConnectionListener listener = new PooledConnectionListener(1L); + TestConnectionListener externalListener = new TestConnectionListener(); + + BigQueryConnection bqConn1 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn1).getListenerPoolSize(); + BigQueryPooledConnection pc1 = new BigQueryPooledConnection(bqConn1); + pc1.addConnectionEventListener(listener); + + BigQueryConnection bqConn2 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn2).getListenerPoolSize(); + BigQueryPooledConnection pc2 = new BigQueryPooledConnection(bqConn2); + pc2.addConnectionEventListener(listener); + pc2.addConnectionEventListener(externalListener); + + Connection c1 = pc1.getConnection(); + Connection c2 = pc2.getConnection(); + + c1.close(); + c2.close(); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + assertEquals(1, externalListener.getConnectionClosedCount()); + verify(bqConn2, never()).close(); + } + + @Test + public void testNullZeroAndLargePoolSize_handledSafely() throws SQLException { + PooledConnectionListener defaultListener = new PooledConnectionListener(null); + assertEquals( + BigQueryJdbcUrlUtility.DEFAULT_CONNECTION_POOL_SIZE_VALUE, + defaultListener.getConnectionPoolSize()); + assertTrue(defaultListener.isConnectionPoolEmpty()); + + // ConnectionPoolSize=0 preserves unbounded idle deque capacity (M15) and LIFO checkout order. + PooledConnectionListener unboundedListener = new PooledConnectionListener(0L); + assertEquals(0L, unboundedListener.getConnectionPoolSize()); + BigQueryPooledConnection firstReturned = null; + BigQueryPooledConnection lastReturned = null; + for (int i = 0; i < 12; i++) { + BigQueryConnection mockPhysical = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(mockPhysical).getListenerPoolSize(); + BigQueryPooledConnection pc = new BigQueryPooledConnection(mockPhysical); + pc.addConnectionEventListener(unboundedListener); + Connection conn = pc.getConnection(); + conn.close(); + verify(mockPhysical, never()).close(); + if (i == 0) { + firstReturned = pc; + } + if (i == 11) { + lastReturned = pc; + } + } + assertEquals(12, unboundedListener.getConnectionPoolCurrentCapacity()); + assertSame(lastReturned, unboundedListener.getPooledConnection()); + for (int i = 0; i < 10; i++) { + assertNotNull(unboundedListener.getPooledConnection()); + } + assertSame(firstReturned, unboundedListener.getPooledConnection()); + assertTrue(unboundedListener.isConnectionPoolEmpty()); + + PooledConnectionListener largeListener = new PooledConnectionListener(Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, largeListener.getConnectionPoolSize()); + assertEquals(Integer.MAX_VALUE, BigQueryPooledConnection.clampCapacity(Long.MAX_VALUE)); + } + + @Test + public void testAddConnection_guardsNullInUseClosedAndDuplicates() throws SQLException { + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); + assertFalse(listener.addConnection(null)); + assertFalse(listener.addConnection(mock(PooledConnection.class))); + + BigQueryPooledConnection pc = new BigQueryPooledConnection(bigQueryConnection); + Connection conn = pc.getConnection(); + assertFalse(listener.addConnection(pc), "In-use PooledConnection must not be pooled"); + + conn.close(); + assertTrue(listener.addConnection(pc)); + assertTrue( + listener.addConnection(pc), "Duplicate addConnection returns true without duplicating"); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + + pc.close(); + listener.removeConnection(pc); + assertFalse( + listener.addConnection(pc), "Physically closed PooledConnection must not be pooled"); + } + + @Test + public void testGetPooledConnection_skipsClosedAndInUseEntries() throws SQLException { + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); + + BigQueryConnection bqConn1 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn1).getListenerPoolSize(); + BigQueryPooledConnection pcClosed = new BigQueryPooledConnection(bqConn1); + assertTrue(listener.addConnection(pcClosed)); + pcClosed.close(); + + BigQueryConnection bqConn2 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn2).getListenerPoolSize(); + BigQueryPooledConnection pcInUse = new BigQueryPooledConnection(bqConn2); + assertTrue(listener.addConnection(pcInUse)); + Connection activeHandle = pcInUse.getConnection(); + + BigQueryConnection bqConn3 = mock(BigQueryConnection.class); + doReturn(LISTENER_POOL_SIZE).when(bqConn3).getListenerPoolSize(); + BigQueryPooledConnection pcIdle = new BigQueryPooledConnection(bqConn3); + assertTrue(listener.addConnection(pcIdle)); + + assertEquals(3, listener.getConnectionPoolCurrentCapacity()); + assertSame(pcIdle, listener.getPooledConnection()); + assertNull(listener.getPooledConnection()); + activeHandle.close(); + } + + @Test + public void testInvalidEventSource_throwsIllegalArgumentException() { + PooledConnectionListener listener = new PooledConnectionListener(CONNECTION_POOL_SIZE); + PooledConnection foreignPooledConnection = mock(PooledConnection.class); + ConnectionEvent invalidEvent = new ConnectionEvent(foreignPooledConnection); + + assertThrows(IllegalArgumentException.class, () -> listener.connectionClosed(invalidEvent)); + assertThrows( + IllegalArgumentException.class, () -> listener.connectionErrorOccurred(invalidEvent)); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITAuthTests.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITAuthTests.java index 0ee751b4fce1..543b1dc6c921 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITAuthTests.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITAuthTests.java @@ -251,7 +251,7 @@ public void testValidExternalAccountAuthenticationRawJson() throws SQLException "https://www.googleapis.com/auth/bigquery, false" }) @Tag("advanced") - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidPreGeneratedAccessTokenAuthentication(String scope, boolean isReadOnly) throws Exception { final JsonObject authJson = getAuthJson(); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITBigQueryJDBCTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITBigQueryJDBCTest.java index 21906893c7c3..6c87483799b6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITBigQueryJDBCTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITBigQueryJDBCTest.java @@ -114,7 +114,7 @@ public static void afterClass() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidAllDataTypesSerializationFromSelectQueryArrowDataset() throws SQLException { String DATASET = "JDBC_INTEGRATION_DATASET"; String TABLE_NAME = "JDBC_INTEGRATION_ARROW_TEST_TABLE"; @@ -188,7 +188,7 @@ public void testSmallSelectAndVerifyResults() throws SQLException { @Test // reads without using ReadAPI and makes sure that they are in order, which implies threads worked // correctly - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIterateOrderJsonMultiThread_NoReadApi() throws SQLException { int expectedCnt = 10000; String query = String.format(BASE_QUERY, expectedCnt); @@ -207,7 +207,7 @@ public void testIterateOrderJsonMultiThread_NoReadApi() throws SQLException { @Test // reads using ReadAPI and makes sure that they are in order, which implies threads worked // correctly - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIterateOrderArrowMultiThread() throws SQLException { int expectedCnt = 200000; String longQuery = String.format(BASE_QUERY, expectedCnt); @@ -366,7 +366,7 @@ public void testDefaultDatasetWithProject() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testLocation() throws SQLException { String connection_uri = ITBigQueryJDBCTest.connection_uri + "LOCATION=EU"; @@ -393,7 +393,7 @@ public void testLocation() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIncorrectLocation() throws SQLException { String connection_uri = ITBigQueryJDBCTest.connection_uri + "LOCATION=europe-west3"; @@ -1378,7 +1378,7 @@ public void testAllValidStatementTypesForAddBatch() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testUnsupportedHTAPIFallbacksToStandardQueriesWithRange() throws SQLException { String selectQuery = "select * from `DATATYPERANGETEST.RangeIntervalTestTable` LIMIT 5000;"; String connection_uri = @@ -1403,7 +1403,7 @@ public void testUnsupportedHTAPIFallbacksToStandardQueriesWithRange() throws SQL } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIntervalDataTypeWithArrowResultSet() throws SQLException { String selectQuery = "select * from `DATATYPERANGETEST.RangeIntervalTestTable` order by intColumn limit 5000;"; @@ -1429,7 +1429,7 @@ public void testIntervalDataTypeWithArrowResultSet() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIntervalDataTypeWithJsonResultSet() throws SQLException { String selectQuery = "select * from `DATATYPERANGETEST.RangeIntervalTestTable` order by intColumn limit 10 ;"; @@ -1455,7 +1455,7 @@ public void testIntervalDataTypeWithJsonResultSet() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidLEPEndpointQuery() throws SQLException { String DATASET = "JDBC_REGIONAL_DATASET"; String TABLE_NAME = "REGIONAL_TABLE"; @@ -1488,7 +1488,7 @@ public void testValidEndpointWithInvalidBQPortThrows() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testLEPEndpointDataNotFoundThrows() throws SQLException { String DATASET = "JDBC_REGIONAL_DATASET"; String TABLE_NAME = "REGIONAL_TABLE"; @@ -1505,7 +1505,7 @@ public void testLEPEndpointDataNotFoundThrows() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidREPEndpointQuery() throws SQLException { String DATASET = "JDBC_REGIONAL_DATASET"; String TABLE_NAME = "REGIONAL_TABLE"; @@ -1840,7 +1840,7 @@ public void testPreparedStatementDateTimeValues() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidDestinationTableSavesQueriesWithLegacySQL() throws SQLException { // setup String connection_uri = @@ -1885,7 +1885,7 @@ public void testNonEnabledUseLegacySQLThrowsSyntaxError() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testUseLegacySQLWithLargeResultsNotAllowedQueries() throws SQLException { // setup String connection_uri = @@ -1904,7 +1904,7 @@ public void testUseLegacySQLWithLargeResultsNotAllowedQueries() throws SQLExcept } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidDestinationTableSavesQueriesWithStandardSQL() throws SQLException { // setup String connection_uri = @@ -1934,7 +1934,7 @@ public void testValidDestinationTableSavesQueriesWithStandardSQL() throws SQLExc } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDestinationTableAndDestinationDatasetThatDoesNotExistsCreates() throws SQLException { // setup @@ -1969,7 +1969,7 @@ public void testDestinationTableAndDestinationDatasetThatDoesNotExistsCreates() } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testUseLegacySQLWithLargeResultsAllowedWithNoDestinationTableDefaults() throws SQLException { // setup @@ -1989,7 +1989,7 @@ public void testUseLegacySQLWithLargeResultsAllowedWithNoDestinationTableDefault } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDestinationTableWithMissingDestinationDatasetDefaults() throws SQLException { // setup String connection_uri = @@ -2121,7 +2121,7 @@ public void testRangeDataTypeWithJsonResultSet() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testRangeDataTypeWithArrowResultSet() throws SQLException { String selectQuery = "select * from `DATATYPERANGETEST.RangeIntervalTestTable` order by intColumn limit 5000;"; @@ -2245,7 +2245,7 @@ public void testQueryPropertyTimeZoneQueries() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testQueryPropertySessionIdSetsStatementSession() throws SQLException, InterruptedException { String sessionId = getSessionId(); @@ -2272,7 +2272,7 @@ public void testQueryPropertySessionIdSetsStatementSession() } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testEncryptedTableWithKmsQueries() throws SQLException { // setup org.junit.jupiter.api.Assumptions.assumeTrue( @@ -2295,7 +2295,7 @@ public void testEncryptedTableWithKmsQueries() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testIncorrectKmsThrows() throws SQLException { org.junit.jupiter.api.Assumptions.assumeTrue( System.getenv("KMS_RESOURCE_PATH") != null, "KMS_RESOURCE_PATH is missing"); @@ -2314,7 +2314,7 @@ public void testIncorrectKmsThrows() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testQueryPropertyServiceAccountFollowsIamPermission() throws SQLException { final String SERVICE_ACCOUNT_EMAIL = requireEnvVar("SA_EMAIL"); String connection_uri = @@ -2336,7 +2336,7 @@ public void testQueryPropertyServiceAccountFollowsIamPermission() throws SQLExce } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidLegacySQLStatement() throws SQLException { String legacyJoinQuery = "SELECT\n" diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITConnectionPoolingTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITConnectionPoolingTest.java index ce78b834574f..cc1d71ccbcb3 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITConnectionPoolingTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITConnectionPoolingTest.java @@ -19,19 +19,27 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.cloud.ServiceOptions; +import com.google.cloud.bigquery.QueryJobConfiguration; import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import com.google.cloud.bigquery.jdbc.BigQueryConnection; import com.google.cloud.bigquery.jdbc.PooledConnectionDataSource; import com.google.cloud.bigquery.jdbc.PooledConnectionListener; import com.google.cloud.bigquery.jdbc.utils.TestUtilities.TestConnectionListener; import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import javax.sql.PooledConnection; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -50,6 +58,7 @@ public void testPooledConnectionDataSourceSuccess() throws SQLException { PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); assertNotNull(pooledConnection); + pooledConnection.close(); } @Test @@ -76,11 +85,15 @@ public void testPooledConnectionAddConnectionListener() throws SQLException { pooledDataSource.setURL(connectionUrl); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - TestConnectionListener listener = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listener); - assertEquals(0, listener.getConnectionClosedCount()); - assertEquals(0, listener.getConnectionErrorCount()); + try { + assertNotNull(pooledConnection); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + } finally { + pooledConnection.close(); + } } @Test @@ -91,11 +104,15 @@ public void testPooledConnectionRemoveConnectionListener() throws SQLException { pooledDataSource.setURL(connectionUrl); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - TestConnectionListener listener = new TestConnectionListener(); - pooledConnection.removeConnectionEventListener(listener); - assertEquals(0, listener.getConnectionClosedCount()); - assertEquals(0, listener.getConnectionErrorCount()); + try { + assertNotNull(pooledConnection); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.removeConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + } finally { + pooledConnection.close(); + } } @Test @@ -106,19 +123,23 @@ public void testPooledConnectionConnectionClosed() throws SQLException { pooledDataSource.setURL(connectionUrl); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - TestConnectionListener listener = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listener); - assertEquals(0, listener.getConnectionClosedCount()); - assertEquals(0, listener.getConnectionErrorCount()); - - Connection connection = pooledConnection.getConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); - - connection.close(); - assertEquals(1, listener.getConnectionClosedCount()); - assertEquals(0, listener.getConnectionErrorCount()); + try { + assertNotNull(pooledConnection); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + + Connection connection = pooledConnection.getConnection(); + assertNotNull(connection); + assertFalse(connection.isClosed()); + + connection.close(); + assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + } finally { + pooledConnection.close(); + } } @Test @@ -136,36 +157,39 @@ public void testPooledConnectionClose() throws SQLException { assertEquals(0, listener.getConnectionErrorCount()); pooledConnection.close(); - assertEquals(1, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionClosedCount()); assertEquals(0, listener.getConnectionErrorCount()); } @Test - public void testPooledConnectionConnectionError() throws SQLException { + public void testPooledConnectionConnectionError() throws Exception { String connectionUrl = ITBase.connectionUrl + "ConnectionPoolSize=20;" + "ListenerPoolSize=20;"; PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); pooledDataSource.setURL(connectionUrl); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - TestConnectionListener listener = new TestConnectionListener(); - pooledConnection.addConnectionEventListener(listener); - assertEquals(0, listener.getConnectionClosedCount()); - assertEquals(0, listener.getConnectionErrorCount()); - - Connection connection = pooledConnection.getConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); - ExecutorService executor = Executors.newFixedThreadPool(3); - connection.abort(executor); - assertEquals(0, listener.getConnectionClosedCount()); - assertEquals(1, listener.getConnectionErrorCount()); - - executor.shutdown(); - connection.close(); - pooledConnection.close(); + try { + assertNotNull(pooledConnection); + TestConnectionListener listener = new TestConnectionListener(); + pooledConnection.addConnectionEventListener(listener); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(0, listener.getConnectionErrorCount()); + + Connection connection = pooledConnection.getConnection(); + assertNotNull(connection); + assertFalse(connection.isClosed()); + + connection.abort(executor); + assertEquals(0, listener.getConnectionClosedCount()); + assertEquals(1, listener.getConnectionErrorCount()); + connection.close(); + } finally { + executor.shutdown(); + assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS)); + pooledConnection.close(); + } } @Test @@ -237,37 +261,40 @@ public void testPooledConnectionListenerClosePooledConnection() throws SQLExcept assertTrue(listener.isConnectionPoolEmpty()); pooledConnection.close(); - assertFalse(listener.isConnectionPoolEmpty()); + assertTrue(listener.isConnectionPoolEmpty()); } @Test - public void testPooledConnectionListenerConnectionError() throws SQLException { + public void testPooledConnectionListenerConnectionError() throws Exception { String connectionUrl = ITBase.connectionUrl + "ConnectionPoolSize=20;" + "ListenerPoolSize=20;"; PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); pooledDataSource.setURL(connectionUrl); PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); - assertNotNull(pooledConnection); - PooledConnectionListener listener = new PooledConnectionListener(DEFAULT_CONN_POOL_SIZE); - pooledConnection.addConnectionEventListener(listener); - assertTrue(listener.isConnectionPoolEmpty()); - - Connection connection = pooledConnection.getConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); - ExecutorService executor = Executors.newFixedThreadPool(3); - connection.abort(executor); - assertTrue(listener.isConnectionPoolEmpty()); - - executor.shutdown(); - connection.close(); - pooledConnection.close(); + try { + assertNotNull(pooledConnection); + PooledConnectionListener listener = new PooledConnectionListener(DEFAULT_CONN_POOL_SIZE); + pooledConnection.addConnectionEventListener(listener); + assertTrue(listener.isConnectionPoolEmpty()); + + Connection connection = pooledConnection.getConnection(); + assertNotNull(connection); + assertFalse(connection.isClosed()); + + connection.abort(executor); + assertTrue(listener.isConnectionPoolEmpty()); + connection.close(); + } finally { + executor.shutdown(); + assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS)); + pooledConnection.close(); + } } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testExecuteQueryWithConnectionPoolingEnabledDefaultPoolSize() throws SQLException { String connectionURL = ITBase.connectionUrl; @@ -275,59 +302,172 @@ public void testExecuteQueryWithConnectionPoolingEnabledDefaultPoolSize() throws } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testExecuteQueryWithConnectionPoolingEnabledCustomPoolSize() throws SQLException { String connectionURL = ITBase.connectionUrl + "ConnectionPoolSize=" + CUSTOM_CONN_POOL_SIZE + ";"; assertConnectionPoolingResults(connectionURL, CUSTOM_CONN_POOL_SIZE); } + @Test + @Tag("disable_universe_domain") + public void testConcurrentCheckoutsExecuteQueriesIndependently() throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(ITBase.connectionUrl + "ConnectionPoolSize=4;"); + + PooledConnection pc1 = null; + PooledConnection pc2 = null; + try { + pc1 = pooledDataSource.getPooledConnection(); + pc2 = pooledDataSource.getPooledConnection(); + Connection conn1 = pc1.getConnection(); + Connection conn2 = pc2.getConnection(); + assertNotSame(conn1.unwrap(BigQueryConnection.class), conn2.unwrap(BigQueryConnection.class)); + + // Keep stmt2 open across conn1.close() so any shared-physical statement reset would fail. + try (Statement stmt2 = conn2.createStatement()) { + try (Statement stmt1 = conn1.createStatement()) { + ITBase.validateStatement(stmt1, 10); + ITBase.validateStatement(stmt2, 20); + } + + conn1.close(); + assertTrue(conn1.isClosed()); + assertThrows(SQLException.class, conn1::createStatement); + + assertFalse(conn2.isClosed()); + assertFalse(stmt2.isClosed()); + ITBase.validateStatement(stmt2, 15); + } + conn2.close(); + } finally { + try { + if (pc1 != null) { + pc1.close(); + } + } finally { + if (pc2 != null) { + pc2.close(); + } + } + } + } + + @Test + @Tag("disable_universe_domain") + public void testSessionAndUncommittedTransactionResetOnReturn() throws Exception { + String dataset = ITBase.getSharedDataset(); + String tableName = "pooled_tx_reset_" + UUID.randomUUID().toString().replace("-", "_"); + String qualifiedTable = String.format("`%s.%s.%s`", PROJECT_ID, dataset, tableName); + + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(ITBase.connectionUrl + "EnableSession=1;ConnectionPoolSize=2;"); + + PooledConnection pc1 = null; + PooledConnection pc2 = null; + try { + ITBase.bigQuery.query( + QueryJobConfiguration.of("CREATE TABLE " + qualifiedTable + " (id INT64)")); + + pc1 = pooledDataSource.getPooledConnection(); + Connection conn1 = pc1.getConnection(); + BigQueryConnection firstPhysical = conn1.unwrap(BigQueryConnection.class); + Statement leakedStmt = conn1.createStatement(); + leakedStmt.execute("CREATE TEMP TABLE pooled_session_temp (id INT64) AS SELECT 42 AS id"); + + conn1.setAutoCommit(false); + leakedStmt.executeUpdate("INSERT INTO " + qualifiedTable + " (id) VALUES (1)"); + conn1.setClientInfo("CLIENTUSER", "first_borrower"); + + // Logical close without commit/rollback must close open statements, roll back the active + // transaction, abort the driver-created session, and reset mutable connection properties. + conn1.close(); + assertTrue(leakedStmt.isClosed()); + assertThrows(SQLException.class, () -> leakedStmt.executeQuery("SELECT 1")); + assertThrows(SQLException.class, conn1::createStatement); + + pc2 = pooledDataSource.getPooledConnection(); + try (Connection conn2 = pc2.getConnection(); + Statement stmt2 = conn2.createStatement()) { + assertSame(firstPhysical, conn2.unwrap(BigQueryConnection.class)); + assertTrue(conn2.getAutoCommit()); + assertNull(conn2.getClientInfo("CLIENTUSER")); + + try (ResultSet rs = stmt2.executeQuery("SELECT COUNT(*) FROM " + qualifiedTable)) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + assertThrows( + SQLException.class, () -> stmt2.executeQuery("SELECT * FROM pooled_session_temp")); + } + } finally { + try { + if (pc2 != null) { + pc2.close(); + } + } finally { + try { + if (pc1 != null) { + pc1.close(); + } + } finally { + ITBase.bigQuery.query(QueryJobConfiguration.of("DROP TABLE IF EXISTS " + qualifiedTable)); + } + } + } + } + private void assertConnectionPoolingResults(String connectionURL, Long connectionPoolSize) throws SQLException { // Create Pooled Connection Datasource PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); pooledDataSource.setURL(connectionURL); - // Get pooled connection and ensure listner was added with default connection pool size. + // Get pooled connection and ensure listener was added with expected connection pool size. PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); assertNotNull(pooledConnection); - PooledConnectionListener listener = pooledDataSource.getConnectionPoolManager(); - assertNotNull(listener); - assertTrue(listener.isConnectionPoolEmpty()); - - // Get Underlying physical connection - Connection connection = pooledConnection.getConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); - - // Execute query with physical connection - Statement statement = connection.createStatement(); - ITBase.validateStatement(statement, 850); - - // Close physical connection - connection.close(); - assertFalse(listener.isConnectionPoolEmpty()); - assertEquals(1, listener.getConnectionPoolCurrentCapacity()); - assertEquals(connectionPoolSize, listener.getConnectionPoolSize()); - - // Reuse same physical connection. - connection = pooledConnection.getConnection(); - assertNotNull(connection); - assertFalse(connection.isClosed()); - assertFalse(listener.isConnectionPoolEmpty()); - assertEquals(1, listener.getConnectionPoolCurrentCapacity()); - assertEquals(connectionPoolSize, listener.getConnectionPoolSize()); - - // Execute query with reusable physical connection - ITBase.validateStatement(statement, 850); - - // Return connection back to the pool. - connection.close(); - assertFalse(listener.isConnectionPoolEmpty()); - assertEquals(1, listener.getConnectionPoolCurrentCapacity()); - assertEquals(connectionPoolSize, listener.getConnectionPoolSize()); - pooledConnection.close(); - statement.close(); - connection.close(); + try { + PooledConnectionListener listener = pooledDataSource.getConnectionPoolManager(); + assertNotNull(listener); + assertTrue(listener.isConnectionPoolEmpty()); + + // Get logical connection handle + Connection connection = pooledConnection.getConnection(); + assertNotNull(connection); + assertFalse(connection.isClosed()); + + // Execute query with logical connection + try (Statement statement = connection.createStatement()) { + ITBase.validateStatement(statement, 850); + } + + // Close logical connection to return PooledConnection to the pool + connection.close(); + assertFalse(listener.isConnectionPoolEmpty()); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + assertEquals(connectionPoolSize, listener.getConnectionPoolSize()); + + // Check out the pooled connection from the DataSource and execute a query on a new Statement. + pooledConnection = pooledDataSource.getPooledConnection(); + assertTrue(listener.isConnectionPoolEmpty()); + assertEquals(0, listener.getConnectionPoolCurrentCapacity()); + connection = pooledConnection.getConnection(); + assertNotNull(connection); + assertFalse(connection.isClosed()); + + try (Statement statement = connection.createStatement()) { + ITBase.validateStatement(statement, 850); + } + + // Return connection back to the pool, then physically close. + connection.close(); + assertFalse(listener.isConnectionPoolEmpty()); + assertEquals(1, listener.getConnectionPoolCurrentCapacity()); + assertEquals(connectionPoolSize, listener.getConnectionPoolSize()); + pooledConnection.close(); + assertTrue(listener.isConnectionPoolEmpty()); + } finally { + pooledConnection.close(); + } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDatabaseMetadataTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDatabaseMetadataTest.java index 671f0b9341f6..992186f9895e 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDatabaseMetadataTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDatabaseMetadataTest.java @@ -721,7 +721,7 @@ public void testDatabaseMetadataGetColumns() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDatabaseMetadataGetTables() throws SQLException { Connection connection = DriverManager.getConnection(ITBase.connectionUrl); DatabaseMetaData databaseMetaData = connection.getMetaData(); @@ -822,7 +822,7 @@ public void testDatabaseMetadataGetTables() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") @Tag("advanced") public void testDatabaseMetadataGetTables_PropertyGraph() throws SQLException { String nodeTable = "GRAPH_NODE_TABLE_" + randomNumber; @@ -921,7 +921,7 @@ public void testDatabaseMetadataGetTables_PropertyGraph() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") @Tag("advanced") public void testDatabaseMetadataGetColumns_PropertyGraph() throws SQLException { String nodeTable = "GRAPH_COL_NODE_TABLE_" + randomNumber; @@ -1049,7 +1049,7 @@ public void testDatabaseMetadataGetColumns_PropertyGraph() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDatabaseMetadataGetSchemas() throws SQLException { Connection connection = DriverManager.getConnection(ITBase.connectionUrl); DatabaseMetaData databaseMetaData = connection.getMetaData(); @@ -1122,7 +1122,7 @@ public void testDatabaseMetadataGetSchemasNoArgs() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDatabaseMetaDataGetFunctions() throws SQLException { Connection connection = DriverManager.getConnection(ITBase.connectionUrl); DatabaseMetaData databaseMetaData = connection.getMetaData(); @@ -1362,7 +1362,7 @@ public void testDatabaseMetadataGetFunctionColumns() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testAdditionalProjectsInMetadata() throws SQLException { String additionalProjectsValue = "bigquery-public-data"; String datasetInAdditionalProject = "baseball"; @@ -1419,7 +1419,7 @@ public void testAdditionalProjectsInMetadata() throws SQLException { @Test @Tag("advanced") - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testFilterTablesOnDefaultDataset_getTables() throws SQLException { String defaultDatasetValue = CONSTRAINTS_DATASET; @@ -1491,7 +1491,7 @@ public void testFilterTablesOnDefaultDataset_getTables() throws SQLException { @Test @Tag("advanced") - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testFilterTablesOnDefaultDataset_getColumns() throws SQLException { String defaultDatasetValue = CONSTRAINTS_DATASET; String tableInDefaultDataset = CONSTRAINTS_TABLE_NAME; diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDriverTest.java index fe00631cb624..b4bb559fbab6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITDriverTest.java @@ -91,7 +91,7 @@ public void testGetDriverMethod() throws SQLException, InterruptedException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testDriverLocation() throws SQLException, InterruptedException { String datasetUS = "JDBC_DRIVER_US_TEST_DATASET" + random.nextInt(999); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITJdbcTimestampPicosTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITJdbcTimestampPicosTest.java index 93b121ea4bd8..e6d5043a0493 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITJdbcTimestampPicosTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITJdbcTimestampPicosTest.java @@ -56,7 +56,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -@Tag("disable_tpc") +@Tag("disable_universe_domain") public class ITJdbcTimestampPicosTest extends ITBase { private static final Random RANDOM = new Random(); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITNightlyBigQueryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITNightlyBigQueryTest.java index 2d5b31b4aa8f..ac9064f75bf9 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITNightlyBigQueryTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITNightlyBigQueryTest.java @@ -183,7 +183,7 @@ public void testMergeInExecuteBatch() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidLongRunningQuery() throws SQLException { // setup String selectQuery = @@ -268,7 +268,7 @@ public void testQueryInterruptGracefullyStopsOptionalJob() } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testWideColumnQueries() throws SQLException { String selectQuery = "SELECT * FROM `bigquery-public-data.covid19_open_data_eu.covid19_open_data` LIMIT 50000"; @@ -287,7 +287,7 @@ public void testWideColumnQueries() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testExecuteLargeUpdate() throws SQLException { String tableName = "JDBC_LARGE_UPDATE_TABLE_" + randomNumber; String createQuery = @@ -715,7 +715,7 @@ public void testFailedStatementInTheMiddleOfExecuteBatchStopsExecuting() throws } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testHTAPIWithValidDestinationTableSavesQueriesWithLegacy() throws SQLException { // setup String connection_uri = @@ -1043,7 +1043,7 @@ public void testMultipleExecuteBatches() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidAllDataTypesSerializationFromSelectQuery() throws SQLException { String DATASET = "JDBC_INTEGRATION_DATASET"; String TABLE_NAME = "JDBC_DATATYPES_INTEGRATION_TEST_TABLE"; @@ -1077,7 +1077,7 @@ public void testValidAllDataTypesSerializationFromSelectQuery() throws SQLExcept } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testRepeatedStructFromSelectQuery() throws SQLException { String DATASET = "JDBC_INTEGRATION_DATASET"; String TABLE_NAME = "JDBC_REPEATED_STRUCT_INTEGRATION_TEST"; @@ -1102,7 +1102,7 @@ public void testRepeatedStructFromSelectQuery() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testValidAllDataTypesSerializationFromSelectQueryArrowDataset() throws SQLException { String DATASET = "JDBC_INTEGRATION_DATASET"; String TABLE_NAME = "JDBC_INTEGRATION_ARROW_TEST_TABLE"; @@ -1623,7 +1623,7 @@ public void testFastQueryPathLarge() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") // reads using ReadAPI and makes sure that they are in order, which implies threads worked // correctly public void testIterateOrderArrowMultiThread() throws SQLException { @@ -1646,7 +1646,7 @@ public void testIterateOrderArrowMultiThread() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testNonEnabledUseLegacySQLThrowsSyntaxError() throws SQLException { // setup String connection_uri = ITNightlyBigQueryTest.connection_uri; diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java index 6e5f339e9880..d70de10f04ab 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java @@ -65,7 +65,7 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -@Tag("disable_tpc") +@Tag("disable_universe_domain") public class ITOpenTelemetryTest extends ITBase { private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId(); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITPcntTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITPcntTest.java index 1cc5408a9be9..4438bb6e4167 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITPcntTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITPcntTest.java @@ -33,7 +33,7 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -@Tag("disable_tpc") +@Tag("disable_universe_domain") public class ITPcntTest extends ITBase { private static final Random random = new Random(); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java index 3fb7a816cf5e..7473086e715c 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java @@ -229,9 +229,15 @@ public void testExecuteUpdate() throws SQLException { public void testScript() throws SQLException { Properties withReadApi = new Properties(); withReadApi.setProperty("EnableHighThroughputAPI", "1"); - String longQuery = String.format(GENERATE_ARRAY_QUERY, 500000); - String longerQuery = String.format(GENERATE_ARRAY_QUERY, 700000); - String longerQuery2 = String.format(GENERATE_ARRAY_QUERY, 900000); + // Each child result must exceed the Read API activation point (>= HighThroughputMinTableSize + // rows, default 10,000, and > HighThroughputActivationRatio pages, default 2, at the default + // MaxResults page size of 10,000), so >= 30,000 rows per child takes the Arrow path. Keep the + // counts modest: the presubmit suite runs all IT classes in one JVM and Arrow buffers are + // off-heap, so multi-million-row scripts have pushed the build container past its memory + // limit (exit 137). + String longQuery = String.format(GENERATE_ARRAY_QUERY, 30000); + String longerQuery = String.format(GENERATE_ARRAY_QUERY, 40000); + String longerQuery2 = String.format(GENERATE_ARRAY_QUERY, 50000); try (Connection connection = DriverManager.getConnection(ITBase.connectionUrl, withReadApi); Statement statement = connection.createStatement()) { @@ -239,17 +245,17 @@ public void testScript() throws SQLException { ResultSet arrowResultSet = statement.getResultSet(); assertArrowResultSet(arrowResultSet); - assertEquals(500000, resultSetRowCount(arrowResultSet)); + assertEquals(30000, resultSetRowCount(arrowResultSet)); assertTrue(statement.getMoreResults()); arrowResultSet = statement.getResultSet(); assertArrowResultSet(arrowResultSet); - assertEquals(700000, resultSetRowCount(arrowResultSet)); + assertEquals(40000, resultSetRowCount(arrowResultSet)); assertTrue(statement.getMoreResults()); arrowResultSet = statement.getResultSet(); assertArrowResultSet(arrowResultSet); - assertEquals(900000, resultSetRowCount(arrowResultSet)); + assertEquals(50000, resultSetRowCount(arrowResultSet)); assertFalse(statement.getMoreResults()); } @@ -387,7 +393,7 @@ public void testRangeSelectDataset() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testTemporaryDatasetLocation() throws SQLException, InterruptedException { String location = "europe-west3"; String randomSuffix = String.valueOf(100 + new Random().nextInt(900)); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITTPCBigQueryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITUniverseDomainBigQueryTest.java similarity index 72% rename from java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITTPCBigQueryTest.java rename to java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITUniverseDomainBigQueryTest.java index a3838e690741..417f301e3a7f 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITTPCBigQueryTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITUniverseDomainBigQueryTest.java @@ -29,44 +29,39 @@ import java.sql.Statement; import org.junit.jupiter.api.Test; -public class ITTPCBigQueryTest { +public class ITUniverseDomainBigQueryTest { private static final String ENDPOINT_URL = System.getenv("ENDPOINT_URL"); - private static final String UNIVERSE_DOMAIN = System.getenv("UNIVERSE_DOMAIN"); - private static final String TPC_SERVICE_ACCOUNT = System.getenv("SERVICE_ACCOUNT"); - private static final String TPC_PVT_KEY = System.getenv("PRIVATE_KEY"); - private static final String TPC_ACCESS_TOKEN = System.getenv("ACCESS_TOKEN"); - private static final String TPC_PROJECT_ID = System.getenv("PROJECT_ID"); + private static final String UNIVERSE_DOMAIN_ENV = System.getenv("UNIVERSE_DOMAIN"); + private static final String UNIVERSE_DOMAIN_SERVICE_ACCOUNT = System.getenv("SERVICE_ACCOUNT"); + private static final String UNIVERSE_DOMAIN_PVT_KEY = System.getenv("PRIVATE_KEY"); + private static final String UNIVERSE_DOMAIN_ACCESS_TOKEN = System.getenv("ACCESS_TOKEN"); + private static final String UNIVERSE_DOMAIN_PROJECT_ID = System.getenv("PROJECT_ID"); - private static final String TPC_ENDPOINT = + private static final String UNIVERSE_DOMAIN_ENDPOINT = (ENDPOINT_URL.isEmpty()) ? "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443" : "jdbc:bigquery://" + ENDPOINT_URL; - private static final String TPC_UNIVERSE_DOMAIN = - (UNIVERSE_DOMAIN.isEmpty()) ? "googleapis.com" : UNIVERSE_DOMAIN; - - // See here go/bq-cli-tpc for testing setup. - // Use the default test project. - // For the SA you will have to give it bigquery admin permissions cl/627813300 and will have to - // revert after testing. - // Plug in the values for the connection properties from the guide into the connection string. + private static final String UNIVERSE_DOMAIN = + (UNIVERSE_DOMAIN_ENV.isEmpty()) ? "googleapis.com" : UNIVERSE_DOMAIN_ENV; + @Test public void testServiceAccountAuthenticationViaEmail() throws SQLException { - validateTPCEnvironment(); + validateUniverseDomainEnvironment(); String connection_uri = - TPC_ENDPOINT + UNIVERSE_DOMAIN_ENDPOINT + ";" + "ProjectId=" - + TPC_PROJECT_ID + + UNIVERSE_DOMAIN_PROJECT_ID + ";" + "OAuthType=0;" + "universeDomain=" - + TPC_UNIVERSE_DOMAIN + + UNIVERSE_DOMAIN + ";" + "OAuthServiceAcctEmail=" - + TPC_SERVICE_ACCOUNT + + UNIVERSE_DOMAIN_SERVICE_ACCOUNT + ";" + "OAuthPvtKey=" - + TPC_PVT_KEY + + UNIVERSE_DOMAIN_PVT_KEY + ";"; Connection connection = DriverManager.getConnection(connection_uri); @@ -86,16 +81,16 @@ public void testServiceAccountAuthenticationViaEmail() throws SQLException { // the SA key file. @Test public void testValidApplicationDefaultCredentialsAuthentication() throws SQLException { - validateTPCEnvironment(); + validateUniverseDomainEnvironment(); String connection_uri = - TPC_ENDPOINT + UNIVERSE_DOMAIN_ENDPOINT + ";" + "OAuthType=3;" + "ProjectId=" - + TPC_PROJECT_ID + + UNIVERSE_DOMAIN_PROJECT_ID + ";" + "universeDomain=" - + TPC_UNIVERSE_DOMAIN + + UNIVERSE_DOMAIN + ";"; Connection connection = DriverManager.getConnection(connection_uri); @@ -113,19 +108,19 @@ public void testValidApplicationDefaultCredentialsAuthentication() throws SQLExc @Test public void testValidPreGeneratedAccessTokenAuthentication() throws SQLException { - validateTPCEnvironment(); + validateUniverseDomainEnvironment(); String connection_uri = - TPC_ENDPOINT + UNIVERSE_DOMAIN_ENDPOINT + ";" + "OAuthType=2;" + "ProjectId=" - + TPC_PROJECT_ID + + UNIVERSE_DOMAIN_PROJECT_ID + ";" + "OAuthAccessToken=" - + TPC_ACCESS_TOKEN + + UNIVERSE_DOMAIN_ACCESS_TOKEN + ";" + "universeDomain=" - + TPC_UNIVERSE_DOMAIN + + UNIVERSE_DOMAIN + ";"; Connection connection = DriverManager.getConnection(connection_uri); @@ -140,22 +135,22 @@ public void testValidPreGeneratedAccessTokenAuthentication() throws SQLException @Test public void testSimpleQueryReturns() throws SQLException { - validateTPCEnvironment(); + validateUniverseDomainEnvironment(); String connection_uri = - TPC_ENDPOINT + UNIVERSE_DOMAIN_ENDPOINT + ";" + "ProjectId=" - + TPC_PROJECT_ID + + UNIVERSE_DOMAIN_PROJECT_ID + ";" + "OAuthType=0;" + "universeDomain=" - + TPC_UNIVERSE_DOMAIN + + UNIVERSE_DOMAIN + ";" + "OAuthServiceAcctEmail=" - + TPC_SERVICE_ACCOUNT + + UNIVERSE_DOMAIN_SERVICE_ACCOUNT + ";" + "OAuthPvtKey=" - + TPC_PVT_KEY + + UNIVERSE_DOMAIN_PVT_KEY + ";"; // Plug in this value when testing from the key file Connection connection = DriverManager.getConnection(connection_uri); @@ -173,16 +168,16 @@ public void testSimpleQueryReturns() throws SQLException { @Test public void testServiceAccountKeyFileReturns() throws SQLException { - validateTPCEnvironment(); + validateUniverseDomainEnvironment(); String connection_uri = - TPC_ENDPOINT + UNIVERSE_DOMAIN_ENDPOINT + ";" + "ProjectId=" - + TPC_PROJECT_ID + + UNIVERSE_DOMAIN_PROJECT_ID + ";" + "OAuthType=0;" + "universeDomain=" - + TPC_UNIVERSE_DOMAIN + + UNIVERSE_DOMAIN + ";" // Point the key path to where you have downloaded it to. + "OAuthPvtKeyPath=/Users/YourPathToSecretFile/SAKeyFile.json;"; @@ -200,21 +195,21 @@ public void testServiceAccountKeyFileReturns() throws SQLException { connection.close(); } - private void validateTPCEnvironment() { - if (TPC_PROJECT_ID.isEmpty()) { - throw new IllegalArgumentException("TPC_PROJECT_ID is empty"); + private void validateUniverseDomainEnvironment() { + if (UNIVERSE_DOMAIN_PROJECT_ID.isEmpty()) { + throw new IllegalArgumentException("UNIVERSE_DOMAIN_PROJECT_ID is empty"); } - if (TPC_SERVICE_ACCOUNT.isEmpty()) { - throw new IllegalArgumentException("TPC_SERVICE_ACCOUNT is empty"); + if (UNIVERSE_DOMAIN_SERVICE_ACCOUNT.isEmpty()) { + throw new IllegalArgumentException("UNIVERSE_DOMAIN_SERVICE_ACCOUNT is empty"); } - if (TPC_ENDPOINT.isEmpty()) { - throw new IllegalArgumentException("TPC_ENDPOINT is empty"); + if (UNIVERSE_DOMAIN_ENDPOINT.isEmpty()) { + throw new IllegalArgumentException("UNIVERSE_DOMAIN_ENDPOINT is empty"); } - if (TPC_PVT_KEY.isEmpty()) { - throw new IllegalArgumentException("TPC_PVT_KEY is empty"); + if (UNIVERSE_DOMAIN_PVT_KEY.isEmpty()) { + throw new IllegalArgumentException("UNIVERSE_DOMAIN_PVT_KEY is empty"); } - if (TPC_UNIVERSE_DOMAIN.isEmpty()) { - throw new IllegalArgumentException("TPC_UNIVERSE_DOMAIN is empty"); + if (UNIVERSE_DOMAIN.isEmpty()) { + throw new IllegalArgumentException("UNIVERSE_DOMAIN is empty"); } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java index 871f03568020..240f57a95eb6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/telemetry/v1/TelemetryTestUtils.java @@ -16,10 +16,35 @@ package com.google.cloud.bigquery.jdbc.telemetry.v1; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + /** Test-only access to {@link TelemetryManager}'s package-private lifecycle state. */ public final class TelemetryTestUtils { private TelemetryTestUtils() {} + /** Initializes {@link TelemetryManager} with a mock transport that appends payloads. */ + public static void initCapturingPayloads(List captured) { + TelemetryConfiguration config = TelemetryConfiguration.builder().setEnabled(true).build(); + ClearcutTransport transport = mock(ClearcutTransport.class); + when(transport.send(any())) + .thenAnswer( + invocation -> { + captured.add(invocation.getArgument(0)); + return new TransportResult(true, -1); + }); + TelemetryManager.resetGlobalDisableForTest(); + TelemetryManager.init(config, transport); + } + + /** Flushes and closes the shared instance so captured payloads are delivered. */ + public static void flush() { + TelemetryManager.closeInstance(); + } + /** Closes the shared instance and clears the global opt-out kill switch. */ public static void reset() { TelemetryManager.closeInstance(); diff --git a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java index b8b7994f8775..f15b8a20e7ff 100644 --- a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java +++ b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java @@ -31,6 +31,18 @@ import io.opentelemetry.api.trace.Tracer; import java.util.Set; +/** + * Configuration options for creating a {@link BigQuery} client. + * + *

Configure overall retry bounds (such as maximum attempts, retry delays, and total timeout) via + * {@link Builder#setRetrySettings(com.google.api.gax.retrying.RetrySettings)}. Configure + * per-attempt HTTP connect and read timeouts via {@link + * Builder#setTransportOptions(TransportOptions)} with {@link HttpTransportOptions} (by default, + * {@link #getDefaultHttpTransportOptions()} sets a 60-second read timeout). + * + *

For message-based retries on job creation and query job status polling, see {@link + * BigQueryRetryConfig}. + */ public class BigQueryOptions extends ServiceOptions { private static final String API_SHORT_NAME = "BigQuery"; @@ -85,6 +97,12 @@ private Builder(BigQueryOptions options) { super(options); } + /** + * Sets the HTTP transport options, including per-attempt connect and read timeouts. + * + *

BigQuery supports only {@link HttpTransportOptions}. Passing any other {@link + * TransportOptions} implementation throws {@link IllegalArgumentException}. + */ @Override public Builder setTransportOptions(TransportOptions transportOptions) { if (!(transportOptions instanceof HttpTransportOptions)) { @@ -158,6 +176,15 @@ public Builder setOpenTelemetryTracer(Tracer tracer) { return this; } + /** + * Sets a custom {@link ResultRetryAlgorithm} to determine which exceptions or responses are + * retried on eligible RPCs. + * + *

If not set, {@code BigQueryOptions} uses the default BigQuery retry handler, which retries + * transient network exceptions and retryable errors (see {@link + * BigQueryException#isRetryable()}). Supplying a custom algorithm replaces that default + * behavior. + */ public Builder setResultRetryAlgorithm(ResultRetryAlgorithm resultRetryAlgorithm) { this.resultRetryAlgorithm = resultRetryAlgorithm; return this; @@ -211,6 +238,7 @@ public TransportOptions getDefaultTransportOptions() { } } + /** Returns the default {@link HttpTransportOptions} with a 60-second read timeout. */ public static HttpTransportOptions getDefaultHttpTransportOptions() { return HttpTransportOptions.newBuilder().setReadTimeout(DEFAULT_READ_API_TIME_OUT).build(); } diff --git a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryRetryConfig.java b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryRetryConfig.java index 2e1f7c0bdaa8..30357b0c5d84 100644 --- a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryRetryConfig.java +++ b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryRetryConfig.java @@ -19,6 +19,30 @@ import com.google.common.collect.ImmutableSet; +/** + * Configures additional error-message and regular-expression retry rules for job creation (via + * {@link BigQuery.JobOption#bigQueryRetryConfig(BigQueryRetryConfig)} on {@link + * BigQuery#create(JobInfo, BigQuery.JobOption...)}) and query job status polling (via {@link + * Job#waitFor(BigQueryRetryConfig, com.google.cloud.RetryOption...)}). + * + *

BigQuery surfaces several transient errors (such as rate-limit failures) with non-5xx HTTP + * status codes (such as 403 or 400) or inside job error payloads that are not retried automatically + * by default HTTP status retries (see {@link BigQueryException#isRetryable()} and BigQuery API HTTP status and error + * codes). This class lets callers opt into retrying eligible calls when an error message + * matches configured substrings or patterns, such as the constants in {@link + * BigQueryErrorMessages}. + * + *

Rules match case-insensitively against the exception or response error message text rather + * than structured {@link BigQueryError#getReason()} codes directly. Job creation via {@link + * BigQuery.JobOption#bigQueryRetryConfig(BigQueryRetryConfig)} applies to all job types, whereas + * {@link Job#waitFor(BigQueryRetryConfig, com.google.cloud.RetryOption...)} applies this + * configuration only to query jobs and ignores it for non-query jobs. + * + * @see BigQueryErrorMessages + * @see BigQuery API HTTP status and + * error codes + */ public class BigQueryRetryConfig { private final ImmutableSet retriableErrorMessages; private final ImmutableSet retriableRegExes; @@ -28,10 +52,12 @@ private BigQueryRetryConfig(Builder builder) { retriableRegExes = builder.retriableRegExes.build(); } + /** Returns the configured error message substrings that trigger a retry. */ public ImmutableSet getRetriableErrorMessages() { return retriableErrorMessages; } + /** Returns the configured full-string regular expression patterns that trigger a retry. */ public ImmutableSet getRetriableRegExes() { return retriableRegExes; } @@ -43,6 +69,10 @@ public static class Builder { private Builder() {} + /** + * Adds error message substrings to retry on using a case-insensitive substring match against + * the exception or response error message text. + */ public final Builder retryOnMessage(String... errorMessages) { for (String errorMessage : errorMessages) { retriableErrorMessages.add(checkNotNull(errorMessage)); @@ -50,6 +80,13 @@ public final Builder retryOnMessage(String... errorMessages) { return this; } + /** + * Adds regular expression patterns to retry on. Both the pattern and the error message are + * lowercased before performing a full-string regular expression match, so patterns must match + * the entire error message rather than only a substring (for example, {@code ".*rate limit.*"} + * rather than {@code "rate limit"}) and should avoid uppercase regex character escapes such as + * {@code \D} or {@code \S}. + */ public final Builder retryOnRegEx(String... regExPatterns) { for (String regExPattern : regExPatterns) { retriableRegExes.add(checkNotNull(regExPattern)); diff --git a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ConnectionImpl.java b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ConnectionImpl.java index 9416caf708ef..5a96f8c0dccd 100644 --- a/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ConnectionImpl.java +++ b/java-bigquery/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ConnectionImpl.java @@ -21,6 +21,7 @@ import com.google.api.core.BetaApi; import com.google.api.core.InternalApi; import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.services.bigquery.model.GetQueryResultsResponse; import com.google.api.services.bigquery.model.JobConfigurationQuery; import com.google.api.services.bigquery.model.QueryParameter; @@ -989,18 +990,37 @@ TableDataList tableDataListRpc(TableId destinationTable, String pageToken) { } } + /** + * Builds {@link BigQueryReadSettings} for the BigQuery Storage Read API client from {@link + * BigQueryOptions}, propagating credentials and universe domain configuration. + */ + @VisibleForTesting + BigQueryReadSettings createBigQueryReadSettings() throws IOException { + // ServiceOptions leaves credentials null if none were configured and ADC lookup failed. + // Use NoCredentialsProvider in that case instead of passing null to FixedCredentialsProvider. + BigQueryReadSettings.Builder settingsBuilder = + BigQueryReadSettings.newBuilder() + .setCredentialsProvider( + bigQueryOptions.getCredentials() != null + ? FixedCredentialsProvider.create(bigQueryOptions.getCredentials()) + : NoCredentialsProvider.create()); + // Forward an explicitly configured universe domain so the Read API client resolves + // bigquerystorage.:443 and validates credentials against the same universe. + // Leave it unset when null so GAX still checks GOOGLE_CLOUD_UNIVERSE_DOMAIN before defaulting + // to googleapis.com. + if (bigQueryOptions.getUniverseDomain() != null) { + settingsBuilder.setUniverseDomain(bigQueryOptions.getUniverseDomain()); + } + return settingsBuilder.build(); + } + @VisibleForTesting BigQueryResult highThroughPutRead( TableId destinationTable, long totalRows, Schema schema, BigQueryResultStats stats) { try { if (bqReadClient == null) { // if the read client isn't already initialized. Not thread safe. - BigQueryReadSettings settings = - BigQueryReadSettings.newBuilder() - .setCredentialsProvider( - FixedCredentialsProvider.create(bigQueryOptions.getCredentials())) - .build(); - bqReadClient = BigQueryReadClient.create(settings); + bqReadClient = BigQueryReadClient.create(createBigQueryReadSettings()); } String parent = String.format("projects/%s", destinationTable.getProject()); String srcTable = diff --git a/java-bigquery/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ConnectionImplTest.java b/java-bigquery/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ConnectionImplTest.java index addf83fa1b88..ad0787c6948f 100644 --- a/java-bigquery/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ConnectionImplTest.java +++ b/java-bigquery/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ConnectionImplTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -28,6 +29,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.services.bigquery.model.GetQueryResultsResponse; import com.google.api.services.bigquery.model.QueryParameter; import com.google.api.services.bigquery.model.QueryParameterType; @@ -37,10 +39,12 @@ import com.google.api.services.bigquery.model.TableDataList; import com.google.api.services.bigquery.model.TableRow; import com.google.api.services.bigquery.model.TableSchema; +import com.google.cloud.NoCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.Tuple; import com.google.cloud.bigquery.spi.BigQueryRpcFactory; import com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc; +import com.google.cloud.bigquery.storage.v1.BigQueryReadSettings; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; @@ -817,4 +821,61 @@ void testCreateQueryRequestAndJobWithEmptyParameters() throws BigQuerySQLExcepti connection.createQueryJob(SQL_QUERY, connectionSettings, emptyParameters, emptyLabels); assertEquals(JOB, createdJob.getId()); } + + @Test + void testCreateBigQueryReadSettings_forwardsUniverseDomain() throws IOException { + BigQueryOptions customUniverseOptions = + BigQueryOptions.newBuilder() + .setProjectId(PROJECT) + .setServiceRpcFactory(rpcFactoryMock) + .setCredentials(NoCredentials.getInstance()) + .setUniverseDomain("custom-universe.com") + .build(); + ConnectionImpl customConnection = + (ConnectionImpl) customUniverseOptions.getService().createConnection(connectionSettings); + + BigQueryReadSettings readSettings = customConnection.createBigQueryReadSettings(); + assertEquals("custom-universe.com", readSettings.getUniverseDomain()); + assertEquals("bigquerystorage.custom-universe.com:443", readSettings.getEndpoint()); + assertEquals( + NoCredentials.getInstance(), readSettings.getCredentialsProvider().getCredentials()); + } + + @Test + void testCreateBigQueryReadSettings_leavesUniverseDomainUnsetWhenDefault() throws IOException { + BigQueryOptions defaultUniverseOptions = + BigQueryOptions.newBuilder() + .setProjectId(PROJECT) + .setServiceRpcFactory(rpcFactoryMock) + .setCredentials(NoCredentials.getInstance()) + .build(); + ConnectionImpl defaultConnection = + (ConnectionImpl) defaultUniverseOptions.getService().createConnection(connectionSettings); + + BigQueryReadSettings readSettings = defaultConnection.createBigQueryReadSettings(); + assertEquals("googleapis.com", readSettings.getUniverseDomain()); + assertEquals("bigquerystorage.googleapis.com:443", readSettings.getEndpoint()); + assertEquals( + NoCredentials.getInstance(), readSettings.getCredentialsProvider().getCredentials()); + } + + @Test + void testCreateBigQueryReadSettings_usesNoCredentialsProviderWhenCredentialsNull() + throws IOException { + BigQueryOptions nullCredentialsOptions = mock(BigQueryOptions.class); + when(nullCredentialsOptions.getCredentials()).thenReturn(null); + when(nullCredentialsOptions.getUniverseDomain()).thenReturn(null); + ConnectionImpl nullCredentialsConnection = + new ConnectionImpl( + connectionSettings, + nullCredentialsOptions, + bigqueryRpcMock, + BigQueryRetryConfig.newBuilder().build()); + + BigQueryReadSettings readSettings = nullCredentialsConnection.createBigQueryReadSettings(); + assertInstanceOf(NoCredentialsProvider.class, readSettings.getCredentialsProvider()); + assertNull(readSettings.getCredentialsProvider().getCredentials()); + assertEquals("googleapis.com", readSettings.getUniverseDomain()); + assertEquals("bigquerystorage.googleapis.com:443", readSettings.getEndpoint()); + } } diff --git a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1/it/ITBigQueryStorageReadClientTest.java b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1/it/ITBigQueryStorageReadClientTest.java index 51a86db43d28..f80ba356e9dd 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1/it/ITBigQueryStorageReadClientTest.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1/it/ITBigQueryStorageReadClientTest.java @@ -1854,42 +1854,6 @@ void testSimpleReadWithOtelTracing() throws IOException { } } - void testUniverseDomain() throws IOException { - // This test is not yet part presubmit integration test as it requires the apis-tpclp.goog - // universe domain credentials. - // Test a valid domain using the default credentials and Google default universe domain. - BigQueryReadSettings bigQueryReadSettings = - BigQueryReadSettings.newBuilder().setUniverseDomain("apis-tpclp.goog").build(); - BigQueryReadClient localClient = BigQueryReadClient.create(bigQueryReadSettings); - - String table = - BigQueryResource.formatTableResource( - /* projectId= */ "google-tpc-testing-environment:cloudsdk-test-project", - /* datasetId= */ "tpc_demo_dataset", - /* tableId= */ "new_table"); - - ReadSession session = - localClient.createReadSession( - /* parent= */ parentProjectId, - /* readSession= */ ReadSession.newBuilder() - .setTable(table) - .setDataFormat(DataFormat.AVRO) - .build(), - /* maxStreamCount= */ 1); - - ReadRowsRequest readRowsRequest = - ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build(); - - long rowCount = 0; - ServerStream stream = localClient.readRowsCallable().call(readRowsRequest); - for (ReadRowsResponse response : stream) { - rowCount += response.getRowCount(); - } - - assertEquals(1, rowCount); - localClient.close(); - } - /** * Reads to the specified row offset within the stream. If the stream does not have the desired * rows to read, it will read all of them. diff --git a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta1/it/ITBigQueryStorageTest.java b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta1/it/ITBigQueryStorageTest.java index 3bc091e05b4f..42cb2909ae00 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta1/it/ITBigQueryStorageTest.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta1/it/ITBigQueryStorageTest.java @@ -1137,43 +1137,6 @@ void testUniverseDomainWithMatchingDomain() throws IOException { localClient.close(); } - void testUniverseDomain() throws IOException { - // This test is not yet part presubmit integration test as it requires the apis-tpclp.goog - // universe domain credentials. - // Test a valid domain using the default credentials and Google default universe domain. - BigQueryStorageSettings bigQueryStorageSettings = - BigQueryStorageSettings.newBuilder().setUniverseDomain("apis-tpclp.goog").build(); - BigQueryStorageClient localClient = BigQueryStorageClient.create(bigQueryStorageSettings); - - TableReference tableReference = - TableReference.newBuilder() - .setProjectId("google-tpc-testing-environment:cloudsdk-test-project") - .setDatasetId("tpc_demo_dataset") - .setTableId("new_table") - .build(); - - ReadSession session = - localClient.createReadSession( - /* tableReference= */ tableReference, - /* parent= */ parentProjectId, - /* requestedStreams= */ 1); - - StreamPosition readPosition = - StreamPosition.newBuilder().setStream(session.getStreams(0)).build(); - - ReadRowsRequest readRowsRequest = - ReadRowsRequest.newBuilder().setReadPosition(readPosition).build(); - - long rowCount = 0; - ServerStream stream = localClient.readRowsCallable().call(readRowsRequest); - for (ReadRowsResponse response : stream) { - rowCount += response.getRowCount(); - } - - assertEquals(1, rowCount); - localClient.close(); - } - /** * Reads to the specified row offset within the stream. If the stream does not have the desired * rows to read, it will read all of them. diff --git a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta2/it/ITBigQueryStorageTest.java b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta2/it/ITBigQueryStorageTest.java index 8781636550b4..498fcfbb5ce6 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta2/it/ITBigQueryStorageTest.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage-it/src/test/java/com/google/cloud/bigquery/storage/v1beta2/it/ITBigQueryStorageTest.java @@ -1117,42 +1117,6 @@ void testUniverseDomainWithMatchingDomain() throws IOException { localClient.close(); } - void testUniverseDomain() throws IOException { - // This test is not yet part presubmit integration test as it requires the apis-tpclp.goog - // universe domain credentials. - // Test a valid domain using the default credentials and Google default universe domain. - BigQueryReadSettings bigQueryReadSettings = - BigQueryReadSettings.newBuilder().setUniverseDomain("apis-tpclp.goog").build(); - BigQueryReadClient localClient = BigQueryReadClient.create(bigQueryReadSettings); - - String table = - BigQueryResource.FormatTableResource( - /* projectId= */ "google-tpc-testing-environment:cloudsdk-test-project", - /* datasetId= */ "tpc_demo_dataset", - /* tableId= */ "new_table"); - - ReadSession session = - localClient.createReadSession( - /* parent= */ parentProjectId, - /* readSession= */ ReadSession.newBuilder() - .setTable(table) - .setDataFormat(DataFormat.AVRO) - .build(), - /* maxStreamCount= */ 1); - - ReadRowsRequest readRowsRequest = - ReadRowsRequest.newBuilder().setReadStream(session.getStreams(0).getName()).build(); - - long rowCount = 0; - ServerStream stream = localClient.readRowsCallable().call(readRowsRequest); - for (ReadRowsResponse response : stream) { - rowCount += response.getRowCount(); - } - - assertEquals(1, rowCount); - localClient.close(); - } - /** * Reads to the specified row offset within the stream. If the stream does not have the desired * rows to read, it will read all of them. diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.java index bdf4d7b289c1..8cde8e0186da 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/JsonStreamWriter.java @@ -338,6 +338,17 @@ public Builder setEndpoint(String endpoint) { return this; } + /** + * Setter for the underlying StreamWriter's universe domain. + * + * @param universeDomain the universe domain to use + * @return Builder + */ + public Builder setUniverseDomain(String universeDomain) { + this.schemaAwareStreamWriterBuilder.setUniverseDomain(universeDomain); + return this; + } + /** * Setter for a traceId to help identify traffic origin. * diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/SchemaAwareStreamWriter.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/SchemaAwareStreamWriter.java index 257ea5d1448a..9541d2c262f2 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/SchemaAwareStreamWriter.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/SchemaAwareStreamWriter.java @@ -97,6 +97,7 @@ private SchemaAwareStreamWriter(Builder builder) builder.credentialsProvider, builder.executorProvider, builder.endpoint, + builder.universeDomain, builder.flowControlSettings, builder.traceId, builder.compressorName, @@ -318,6 +319,7 @@ private void setStreamWriterSettings( @Nullable CredentialsProvider credentialsProvider, @Nullable ExecutorProvider executorProvider, @Nullable String endpoint, + @Nullable String universeDomain, @Nullable FlowControlSettings flowControlSettings, @Nullable String traceId, @Nullable String compressorName, @@ -334,6 +336,9 @@ private void setStreamWriterSettings( if (endpoint != null) { streamWriterBuilder.setEndpoint(endpoint); } + if (universeDomain != null) { + streamWriterBuilder.setUniverseDomain(universeDomain); + } if (traceId != null) { streamWriterBuilder.setTraceId(traceId); } @@ -468,6 +473,7 @@ public static final class Builder { private ExecutorProvider executorProvider; private FlowControlSettings flowControlSettings; private String endpoint; + private String universeDomain; private String traceIdBase; private String traceId; private boolean ignoreUnknownFields = false; @@ -612,6 +618,17 @@ public Builder setEndpoint(String endpoint) { return this; } + /** + * Setter for the underlying StreamWriter's universe domain. + * + * @param universeDomain the universe domain to use + * @return Builder + */ + public Builder setUniverseDomain(String universeDomain) { + this.universeDomain = universeDomain; + return this; + } + /** * Setter for a traceId to help identify traffic origin. * diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/StreamWriter.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/StreamWriter.java index fbd2efb2aa73..d345808fd6e2 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/StreamWriter.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1/StreamWriter.java @@ -168,9 +168,18 @@ abstract static class ConnectionPoolKey { abstract int credentialsHashcode(); - public static ConnectionPoolKey create(String location, @Nullable Credentials credentials) { + abstract String endpoint(); + + abstract String universeDomain(); + + /** Creates a connection pool key scoped by location, credentials, endpoint, and universe. */ + public static ConnectionPoolKey create( + String location, + @Nullable Credentials credentials, + String endpoint, + String universeDomain) { return new AutoValue_StreamWriter_ConnectionPoolKey( - location, credentials != null ? credentials.hashCode() : 0); + location, credentials != null ? credentials.hashCode() : 0, endpoint, universeDomain); } } @@ -348,7 +357,9 @@ public String call() throws Exception { connectionPoolMap.computeIfAbsent( ConnectionPoolKey.create( location, - credentialsProvider != null ? credentialsProvider.getCredentials() : null), + credentialsProvider != null ? credentialsProvider.getCredentials() : null, + client.getSettings().getEndpoint(), + client.getSettings().getUniverseDomain()), (key) -> { return new ConnectionWorkerPool( builder.maxInflightRequest, @@ -414,7 +425,20 @@ AppendRowsRequest.MissingValueInterpretation getDefaultValueInterpretation() { static BigQueryWriteSettings getBigQueryWriteSettings(Builder builder) throws IOException { BigQueryWriteSettings.Builder settingsBuilder = null; if (builder.client != null) { - settingsBuilder = builder.client.getSettings().toBuilder(); + // Fail fast if setUniverseDomain() conflicts with the provided BigQueryWriteClient to avoid + // split-brain routing between metadata calls and streaming connections. + BigQueryWriteSettings clientSettings = builder.client.getSettings(); + String clientUniverseDomain = clientSettings.getUniverseDomain(); + if (builder.universeDomain != null + && clientUniverseDomain != null + && !builder.universeDomain.equals(clientUniverseDomain)) { + throw new IllegalArgumentException( + String.format( + "The configured universe domain (%s) does not match the universe domain on the" + + " provided BigQueryWriteClient (%s).", + builder.universeDomain, clientUniverseDomain)); + } + settingsBuilder = clientSettings.toBuilder(); } else { settingsBuilder = new BigQueryWriteSettings.Builder() @@ -428,8 +452,9 @@ static BigQueryWriteSettings getBigQueryWriteSettings(Builder builder) throws IO .setCredentialsProvider( BigQueryWriteSettings.defaultCredentialsProviderBuilder().build()) .setBackgroundExecutorProvider( - BigQueryWriteSettings.defaultExecutorProviderBuilder().build()) - .setEndpoint(BigQueryWriteSettings.getDefaultEndpoint()); + BigQueryWriteSettings.defaultExecutorProviderBuilder().build()); + // Omit setEndpoint(getDefaultEndpoint()) so GAX expands GOOGLE_CLOUD_UNIVERSE_DOMAIN when + // no custom endpoint is explicitly configured. } if (builder.channelProvider != null) { settingsBuilder.setTransportChannelProvider(builder.channelProvider); @@ -443,6 +468,9 @@ static BigQueryWriteSettings getBigQueryWriteSettings(Builder builder) throws IO if (builder.endpoint != null) { settingsBuilder.setEndpoint(builder.endpoint); } + if (builder.universeDomain != null) { + settingsBuilder.setUniverseDomain(builder.universeDomain); + } return settingsBuilder.build(); } @@ -864,6 +892,8 @@ public static final class Builder { private String endpoint = null; + private String universeDomain = null; + private TransportChannelProvider channelProvider = null; private CredentialsProvider credentialsProvider = null; @@ -957,6 +987,12 @@ public Builder setEndpoint(String endpoint) { return this; } + /** Gives the ability to override the universe domain. */ + public Builder setUniverseDomain(String universeDomain) { + this.universeDomain = universeDomain; + return this; + } + /** * Enables a static shared bidi-streaming connection pool that would dynamically scale up * connections based on backlog within each individual connection. A single table's traffic diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2.java index 1d00f07dfb69..7a48b0e7dfdf 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/main/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2.java @@ -159,19 +159,10 @@ private StreamWriterV2(Builder builder) throws IOException { this.waitingRequestQueue = new LinkedList(); this.inflightRequestQueue = new LinkedList(); if (builder.client == null) { - BigQueryWriteSettings stubSettings = - BigQueryWriteSettings.newBuilder() - .setCredentialsProvider(builder.credentialsProvider) - .setTransportChannelProvider(builder.channelProvider) - .setEndpoint(builder.endpoint) - // (b/185842996): Temporily fix this by explicitly providing the header. - .setHeaderProvider( - FixedHeaderProvider.create( - "x-goog-request-params", "write_stream=" + this.streamName)) - .build(); - this.client = BigQueryWriteClient.create(stubSettings); + this.client = BigQueryWriteClient.create(getBigQueryWriteSettings(builder, this.streamName)); this.ownsBigQueryWriteClient = true; } else { + validateUniverseDomain(builder); this.client = builder.client; this.ownsBigQueryWriteClient = false; } @@ -202,6 +193,44 @@ public void run() { this.appendThread.start(); } + /** + * Validates that an explicitly configured universe domain matches the provided {@link + * BigQueryWriteClient}'s universe domain. + */ + static void validateUniverseDomain(Builder builder) { + if (builder.client != null && builder.universeDomain != null) { + String clientUniverseDomain = builder.client.getSettings().getUniverseDomain(); + if (clientUniverseDomain != null && !builder.universeDomain.equals(clientUniverseDomain)) { + throw new IllegalArgumentException( + String.format( + "The configured universe domain (%s) does not match the universe domain on the" + + " provided BigQueryWriteClient (%s).", + builder.universeDomain, clientUniverseDomain)); + } + } + } + + /** Builds {@link BigQueryWriteSettings} from the builder without pinning the default endpoint. */ + static BigQueryWriteSettings getBigQueryWriteSettings(Builder builder, String streamName) + throws IOException { + BigQueryWriteSettings.Builder settingsBuilder = + BigQueryWriteSettings.newBuilder() + .setCredentialsProvider(builder.credentialsProvider) + .setTransportChannelProvider(builder.channelProvider) + // (b/185842996): Temporily fix this by explicitly providing the header. + .setHeaderProvider( + FixedHeaderProvider.create("x-goog-request-params", "write_stream=" + streamName)); + // Omit setEndpoint(getDefaultEndpoint()) so GAX expands GOOGLE_CLOUD_UNIVERSE_DOMAIN when + // no custom endpoint is explicitly configured. + if (builder.endpoint != null) { + settingsBuilder.setEndpoint(builder.endpoint); + } + if (builder.universeDomain != null) { + settingsBuilder.setUniverseDomain(builder.universeDomain); + } + return settingsBuilder.build(); + } + /** * Schedules the writing of a message. * @@ -527,7 +556,9 @@ public static final class Builder { private long maxInflightBytes = DEFAULT_MAX_INFLIGHT_BYTES; - private String endpoint = BigQueryWriteSettings.getDefaultEndpoint(); + private String endpoint = null; + + private String universeDomain = null; private TransportChannelProvider channelProvider = BigQueryWriteSettings.defaultGrpcTransportProviderBuilder().setChannelsPerCpu(1).build(); @@ -569,6 +600,12 @@ public Builder setEndpoint(String endpoint) { return this; } + /** Gives the ability to override the universe domain. */ + public Builder setUniverseDomain(String universeDomain) { + this.universeDomain = universeDomain; + return this; + } + /** * {@code ChannelProvider} to use to create Channels, which must point at Cloud BigQuery Storage * API endpoint. diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1/StreamWriterTest.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1/StreamWriterTest.java index 194b55805d4b..56e49e8029b3 100644 --- a/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1/StreamWriterTest.java +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1/StreamWriterTest.java @@ -2611,4 +2611,83 @@ void testLocationCacheExpires() throws Exception { .build(); assertEquals(2, testBigQueryWrite.getWriteStreamRequests().size()); } + + @Test + void testGetBigQueryWriteSettingsResolvesUniverseDomainEndpoint() throws Exception { + StreamWriter.Builder builder = + StreamWriter.newBuilder(TEST_STREAM_1) + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("custom.example.com"); + + BigQueryWriteSettings settings = StreamWriter.getBigQueryWriteSettings(builder); + + assertEquals("custom.example.com", settings.getUniverseDomain()); + assertEquals("bigquerystorage.custom.example.com:443", settings.getEndpoint()); + } + + @Test + void testGetBigQueryWriteSettingsRespectsExplicitEndpoint() throws Exception { + StreamWriter.Builder builder = + StreamWriter.newBuilder(TEST_STREAM_1) + .setCredentialsProvider(NoCredentialsProvider.create()) + .setEndpoint("custom-endpoint.example.com:443"); + + BigQueryWriteSettings settings = StreamWriter.getBigQueryWriteSettings(builder); + + assertEquals("custom-endpoint.example.com:443", settings.getEndpoint()); + } + + @Test + void testConnectionPoolKeyDistinguishesEndpointAndUniverseDomain() { + StreamWriter.ConnectionPoolKey defaultKey = + StreamWriter.ConnectionPoolKey.create( + "us", null, "bigquerystorage.googleapis.com:443", "googleapis.com"); + StreamWriter.ConnectionPoolKey customUniverseKey = + StreamWriter.ConnectionPoolKey.create( + "us", null, "bigquerystorage.custom.example.com:443", "custom.example.com"); + StreamWriter.ConnectionPoolKey customEndpointKey = + StreamWriter.ConnectionPoolKey.create( + "us", null, "custom.example.com:443", "googleapis.com"); + + assertNotEquals(defaultKey, customUniverseKey); + assertNotEquals(defaultKey, customEndpointKey); + assertNotEquals(customUniverseKey, customEndpointKey); + } + + @Test + void testGetBigQueryWriteSettingsThrowsOnMismatchedClientUniverseDomain() throws Exception { + BigQueryWriteSettings clientSettings = + BigQueryWriteSettings.newBuilder() + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("googleapis.com") + .build(); + try (BigQueryWriteClient writeClient = BigQueryWriteClient.create(clientSettings)) { + StreamWriter.Builder builder = + StreamWriter.newBuilder(TEST_STREAM_1, writeClient) + .setUniverseDomain("custom.example.com"); + + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, () -> StreamWriter.getBigQueryWriteSettings(builder)); + assertTrue(ex.getMessage().contains("custom.example.com")); + assertTrue(ex.getMessage().contains("googleapis.com")); + } + } + + @Test + void testGetBigQueryWriteSettingsAllowsMatchingClientUniverseDomain() throws Exception { + BigQueryWriteSettings clientSettings = + BigQueryWriteSettings.newBuilder() + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("custom.example.com") + .build(); + try (BigQueryWriteClient writeClient = BigQueryWriteClient.create(clientSettings)) { + StreamWriter.Builder builder = + StreamWriter.newBuilder(TEST_STREAM_1, writeClient) + .setUniverseDomain("custom.example.com"); + + BigQueryWriteSettings settings = StreamWriter.getBigQueryWriteSettings(builder); + assertEquals("custom.example.com", settings.getUniverseDomain()); + } + } } diff --git a/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2Test.java b/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2Test.java new file mode 100644 index 000000000000..c371f6cfde65 --- /dev/null +++ b/java-bigquerystorage/google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2Test.java @@ -0,0 +1,91 @@ +/* + * 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 + * + * https://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.bigquery.storage.v1beta2; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.api.gax.core.NoCredentialsProvider; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link StreamWriterV2} settings resolution. */ +class StreamWriterV2Test { + + private static final String TEST_STREAM = "projects/p/datasets/d/tables/t/streams/s"; + + @Test + void testGetBigQueryWriteSettingsResolvesUniverseDomainEndpoint() throws Exception { + StreamWriterV2.Builder builder = + StreamWriterV2.newBuilder(TEST_STREAM) + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("custom.example.com"); + + BigQueryWriteSettings settings = StreamWriterV2.getBigQueryWriteSettings(builder, TEST_STREAM); + + assertEquals("custom.example.com", settings.getUniverseDomain()); + assertEquals("bigquerystorage.custom.example.com:443", settings.getEndpoint()); + } + + @Test + void testGetBigQueryWriteSettingsRespectsExplicitEndpoint() throws Exception { + StreamWriterV2.Builder builder = + StreamWriterV2.newBuilder(TEST_STREAM) + .setCredentialsProvider(NoCredentialsProvider.create()) + .setEndpoint("custom-endpoint.example.com:443"); + + BigQueryWriteSettings settings = StreamWriterV2.getBigQueryWriteSettings(builder, TEST_STREAM); + + assertEquals("custom-endpoint.example.com:443", settings.getEndpoint()); + } + + @Test + void testValidateUniverseDomainThrowsOnMismatchedClientUniverseDomain() throws Exception { + BigQueryWriteSettings clientSettings = + BigQueryWriteSettings.newBuilder() + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("googleapis.com") + .build(); + try (BigQueryWriteClient writeClient = BigQueryWriteClient.create(clientSettings)) { + StreamWriterV2.Builder builder = + StreamWriterV2.newBuilder(TEST_STREAM, writeClient) + .setUniverseDomain("custom.example.com"); + + IllegalArgumentException ex = + assertThrows( + IllegalArgumentException.class, () -> StreamWriterV2.validateUniverseDomain(builder)); + assertTrue(ex.getMessage().contains("custom.example.com")); + assertTrue(ex.getMessage().contains("googleapis.com")); + } + } + + @Test + void testValidateUniverseDomainAllowsMatchingClientUniverseDomain() throws Exception { + BigQueryWriteSettings clientSettings = + BigQueryWriteSettings.newBuilder() + .setCredentialsProvider(NoCredentialsProvider.create()) + .setUniverseDomain("custom.example.com") + .build(); + try (BigQueryWriteClient writeClient = BigQueryWriteClient.create(clientSettings)) { + StreamWriterV2.Builder builder = + StreamWriterV2.newBuilder(TEST_STREAM, writeClient) + .setUniverseDomain("custom.example.com"); + + StreamWriterV2.validateUniverseDomain(builder); + } + } +} diff --git a/java-bigtable/google-cloud-bigtable/pom.xml b/java-bigtable/google-cloud-bigtable/pom.xml index 8dcd545ba78e..3c1272a0f18c 100644 --- a/java-bigtable/google-cloud-bigtable/pom.xml +++ b/java-bigtable/google-cloud-bigtable/pom.xml @@ -41,6 +41,7 @@ false + + + 7012 + com/google/cloud/spanner/SpannerOptions$SpannerEnvironment + java.lang.String getUniverseDomain() + diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java index c13c306e21e4..108414fe7233 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/AsyncResultSetImpl.java @@ -21,38 +21,41 @@ import com.google.api.core.SettableApiFuture; import com.google.api.gax.core.ExecutorProvider; import com.google.cloud.spanner.AbstractReadContext.ListenableAsyncResultSet; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.ListeningScheduledExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.ResultSetMetadata; import com.google.spanner.v1.ResultSetStats; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.LinkedList; import java.util.List; -import java.util.concurrent.BlockingDeque; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; /** Default implementation for {@link AsyncResultSet}. */ +@NullMarked class AsyncResultSetImpl extends ForwardingStructReader implements ListenableAsyncResultSet, AsyncResultSet.StreamMessageListener { private static final Logger log = Logger.getLogger(AsyncResultSetImpl.class.getName()); /** State of an {@link AsyncResultSetImpl}. */ - private enum State { + @VisibleForTesting + enum State { INITIALIZED, STREAMING_INITIALIZED, /** SYNC indicates that the {@link ResultSet} is used in sync pattern. */ @@ -76,12 +79,12 @@ private enum State { } static final int DEFAULT_BUFFER_SIZE = 10; + static final int MAX_BUFFERED_CHUNKS = 512; private static final int MAX_WAIT_FOR_BUFFER_CONSUMPTION = 10; - private static final SpannerException CANCELLED_EXCEPTION = - SpannerExceptionFactory.newSpannerException( - ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled"); private final Object monitor = new Object(); + + @GuardedBy("monitor") private boolean closed; /** @@ -90,14 +93,25 @@ private enum State { */ private final ExecutorProvider executorProvider; - private final ListeningScheduledExecutorService service; + private final ScheduledExecutorService service; + + private final int maxBufferSize; + + @GuardedBy("monitor") + private final ArrayDeque buffer; + + @GuardedBy("monitor") + private boolean waitingForBufferSpace; + + @Nullable private volatile Struct currentRow; - private final BlockingDeque buffer; - private Struct currentRow; + private volatile boolean syncHasCurrentRow; /** Supplies the underlying synchronous {@link ResultSet} that will be producing the rows. */ private final Supplier delegateResultSet; + @VisibleForTesting @Nullable volatile ResultSet initializedDelegate; + /** * Callback invoked once when query execution begins or when the result set is closed without * starting, allowing callers (like {@link MultiUseReadOnlyTransaction}) to track query lifecycle. @@ -113,64 +127,110 @@ private enum State { @GuardedBy("monitor") private boolean delegateClosed; - @GuardedBy("monitor") - private Throwable supplierException; - /** * Any exception that occurs while executing the query and iterating over the result set will be * stored in this variable and propagated to the user through {@link #tryNext()}. */ - private volatile SpannerException executionException; + @GuardedBy("monitor") + @Nullable + private SpannerException executionException; + + @GuardedBy("monitor") + @Nullable + private SpannerException cancelledException; /** * Executor for callbacks. Regardless of the type of executor that is provided, the {@link * AsyncResultSetImpl} will ensure that at most 1 callback call will be active at any one time. */ + @GuardedBy("monitor") + @Nullable private Executor executor; + @GuardedBy("monitor") + @Nullable private ReadyCallback callback; /** * Listeners that will be called when the {@link AsyncResultSetImpl} has finished fetching all * rows and any underlying transaction or session can be closed. */ - private final Collection listeners = new LinkedList<>(); + @GuardedBy("monitor") + private final Collection listeners = new ArrayList<>(2); - private volatile State state = State.INITIALIZED; + @GuardedBy("monitor") + private State state = State.INITIALIZED; - /** This variable indicates that produce rows thread is initiated */ - private volatile boolean produceRowsInitiated; + /** Indicates whether InitiateStreamingRunnable is currently scheduled or executing. */ + @GuardedBy("monitor") + private boolean initiatingStreaming; + + /** Indicates whether the delegate dynamically supports non-blocking streaming notifications. */ + @GuardedBy("monitor") + private boolean streamingSupported; + + /** Indicates whether a task is currently scheduled or executing ProduceRowsRunnable. */ + @GuardedBy("monitor") + private boolean producerRunning; + + /** Indicates whether a producer wakeup has been requested while a producer task is running. */ + @GuardedBy("monitor") + private boolean producerWakeupRequested; + + /** Indicates whether produce rows has been initiated. */ + @GuardedBy("monitor") + private boolean produceRowsInitiated; /** - * This variable indicates whether all the results from the underlying result set have been read. + * Counts initial stream chunks without a resume token before {@link #produceRowsInitiated} flips + * to {@code true}, ensuring row production starts once {@link ResumableStreamIterator} exceeds + * {@link #MAX_BUFFERED_CHUNKS} even when {@code prefetchChunks} is larger. */ - private volatile boolean finished; - - private volatile SettableApiFuture result; + @GuardedBy("monitor") + private int initialChunksWithoutResumeToken; /** - * This variable indicates whether {@link #tryNext()} has returned {@link CursorState#DONE} or a - * {@link SpannerException}. + * Indicates whether the entire async result set lifecycle and cleanup have been completed (all + * rows processed/handled, callback done, future resolved, resources freed). */ - private volatile boolean cursorReturnedDoneOrException; + @GuardedBy("monitor") + private boolean completed; + + /** Indicates whether a task is currently scheduled or executing CallbackRunnable. */ + @GuardedBy("monitor") + private boolean callbackRunning; /** - * This variable is used to pause the producer when the {@link AsyncResultSet} is paused. The - * production of rows that are put into the buffer is only paused once the buffer is full. + * The thread currently executing {@link ReadyCallback#cursorReady(AsyncResultSet)}, or {@code + * null} when no callback invocation is in progress. Written only under {@link #monitor} by the + * callback thread itself; volatile allows lock-free self-thread checks in {@link + * #checkValidState()}. */ - private volatile CountDownLatch pausedLatch = new CountDownLatch(1); + @Nullable private volatile Thread callbackInvocationThread; /** - * This variable is used to pause the producer when the buffer is full and the consumer needs some - * time to catch up. + * This variable indicates whether all the results from the underlying result set have been read. */ - private volatile CountDownLatch bufferConsumptionLatch = new CountDownLatch(0); + @GuardedBy("monitor") + private boolean finished; + + @GuardedBy("monitor") + @Nullable + private SettableApiFuture result; /** - * This variable is used to pause the producer when all rows have been put into the buffer, but - * the consumer (the callback) has not yet received and processed all rows. + * This variable indicates whether {@link #tryNext()} has returned {@link CursorState#DONE} or a + * {@link SpannerException}. */ - private volatile CountDownLatch consumingLatch = new CountDownLatch(0); + @GuardedBy("monitor") + private boolean cursorReturnedDoneOrException; + + @VisibleForTesting + State getState() { + synchronized (monitor) { + return state; + } + } AsyncResultSetImpl(ExecutorProvider executorProvider, ResultSet delegate, int bufferSize) { this( @@ -193,7 +253,7 @@ private enum State { Runnable onStartOrClose) { this( executorProvider, - Suppliers.memoize(Preconditions.checkNotNull(delegate)), + new MemoizingSupplier(Preconditions.checkNotNull(delegate)), bufferSize, Preconditions.checkNotNull(onStartOrClose), /* delegateInitialized= */ false); @@ -206,12 +266,20 @@ private AsyncResultSetImpl( Runnable onStartOrClose, boolean delegateInitialized) { super(memoizedDelegate); + Preconditions.checkArgument(bufferSize > 0, "bufferSize must be > 0"); this.executorProvider = Preconditions.checkNotNull(executorProvider); this.delegateResultSet = memoizedDelegate; this.onStartOrClose = onStartOrClose; this.delegateInitialized = delegateInitialized; - this.service = MoreExecutors.listeningDecorator(executorProvider.getExecutor()); - this.buffer = new LinkedBlockingDeque<>(bufferSize); + this.service = executorProvider.getExecutor(); + this.maxBufferSize = bufferSize; + this.buffer = new ArrayDeque<>(Math.min(bufferSize, 1024)); + replaceDelegateSupplier(this::currentRowOrDelegate); + } + + private StructReader currentRowOrDelegate() { + Struct row = getCurrentCallbackRow(); + return row != null ? row : getOrInitializeDelegate(); } /** @@ -219,38 +287,18 @@ private AsyncResultSetImpl( * any necessary early-close reconciliation and start/close notifications. */ private ResultSet getOrInitializeDelegate() { + ResultSet delegate = initializedDelegate; + if (delegate != null) { + return delegate; + } try { - ResultSet delegate = invokeDelegateSupplier(); + delegate = delegateResultSet.get(); closeIfClosedBeforeInitialization(delegate); - return delegate; } finally { maybeNotifyStartOrClose(); } - } - - private ResultSet invokeDelegateSupplier() { - checkSupplierException(); - try { - return delegateResultSet.get(); - } catch (Throwable throwable) { - synchronized (monitor) { - supplierException = throwable; - } - throw throwable; - } - } - - private void checkSupplierException() { - synchronized (monitor) { - if (supplierException != null) { - if (supplierException instanceof RuntimeException) { - throw (RuntimeException) supplierException; - } else if (supplierException instanceof Error) { - throw (Error) supplierException; - } - throw SpannerExceptionFactory.asSpannerException(supplierException); - } - } + initializedDelegate = delegate; + return delegate; } private void closeIfClosedBeforeInitialization(ResultSet delegate) { @@ -289,12 +337,6 @@ private void maybeNotifyStartOrClose() { } } - boolean isUsed() { - synchronized (monitor) { - return state != State.INITIALIZED; - } - } - /** * Closes the {@link AsyncResultSet}. {@link #close()} is non-blocking and may be called multiple * times without side effects. An {@link AsyncResultSet} may be closed before all rows have been @@ -312,6 +354,8 @@ public void close() { } if (state == State.INITIALIZED || state == State.SYNC) { shouldCloseDelegate = true; + currentRow = null; + syncHasCurrentRow = false; } if (state == State.INITIALIZED) { shouldNotifyClose = true; @@ -356,36 +400,44 @@ public void removeListener(Runnable listener) { */ @Override public CursorState tryNext() throws SpannerException { + boolean shouldExecuteProducer = false; synchronized (monitor) { + Preconditions.checkState( + isInCallbackInvocation(), "tryNext may only be called from a DataReady callback."); if (state == State.CANCELLED) { + currentRow = null; cursorReturnedDoneOrException = true; - throw CANCELLED_EXCEPTION; + throw Preconditions.checkNotNull(cancelledException); } - if (buffer.isEmpty() && executionException != null) { - cursorReturnedDoneOrException = true; - throw executionException; - } - Preconditions.checkState( - this.callback != null, "tryNext may only be called after a callback has been set."); - Preconditions.checkState( - this.state == State.CONSUMING, - "tryNext may only be called from a DataReady callback. Current state: " - + this.state.name()); - - if (finished && buffer.isEmpty()) { - cursorReturnedDoneOrException = true; - return CursorState.DONE; + if (!buffer.isEmpty()) { + currentRow = buffer.removeFirst(); + if (waitingForBufferSpace && hasBufferBatchSpace()) { + waitingForBufferSpace = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + } else { + currentRow = null; + if (executionException != null) { + cursorReturnedDoneOrException = true; + throw executionException; + } else if (finished) { + cursorReturnedDoneOrException = true; + return CursorState.DONE; + } else { + return CursorState.NOT_READY; + } } } - if (!buffer.isEmpty()) { - // Set the next row from the buffer as the current row of the StructReader. - replaceDelegate(currentRow = buffer.pop()); - synchronized (monitor) { - bufferConsumptionLatch.countDown(); - } - return CursorState.OK; + if (shouldExecuteProducer) { + executeProducer(); } - return CursorState.NOT_READY; + return CursorState.OK; + } + + @GuardedBy("monitor") + private boolean hasBufferBatchSpace() { + int minAvailableSlots = Math.min(maxBufferSize / 2 + 1, MAX_WAIT_FOR_BUFFER_CONSUMPTION); + return maxBufferSize - buffer.size() >= minAvailableSlots; } private void closeDelegateResultSet() { @@ -399,8 +451,8 @@ private void closeDelegateResultSet() { if (shouldClose) { try { delegateResultSet.get().close(); - } catch (Throwable t) { - log.log(Level.FINE, "Ignoring error from closing delegate result set", t); + } catch (Throwable throwable) { + log.log(Level.FINE, "Ignoring error from closing delegate result set", throwable); } } } @@ -414,10 +466,8 @@ private class CallbackRunnable implements Runnable { public void run() { try { while (true) { + ReadyCallback callback; synchronized (monitor) { - if (cursorReturnedDoneOrException) { - break; - } if (state == State.CANCELLED) { // The callback should always get at least one chance to catch the CANCELLED // exception. It is however possible that the callback does not call tryNext(), and @@ -425,68 +475,71 @@ public void run() { // also stop, even though the callback has not seen the CANCELLED state. cursorReturnedDoneOrException = true; } + callback = Preconditions.checkNotNull(AsyncResultSetImpl.this.callback); + callbackInvocationThread = Thread.currentThread(); } CallbackResponse response; try { - response = callback.cursorReady(AsyncResultSetImpl.this); - } catch (Throwable e) { + response = + Preconditions.checkNotNull( + callback.cursorReady(AsyncResultSetImpl.this), + "CallbackResponse may not be null"); + } catch (Throwable throwable) { + boolean shouldCloseDelegate = true; synchronized (monitor) { - if (cursorReturnedDoneOrException - && state == State.CANCELLED - && e instanceof SpannerException - && ((SpannerException) e).getErrorCode() == ErrorCode.CANCELLED) { + currentRow = null; + callbackInvocationThread = null; + cursorReturnedDoneOrException = true; + if (state == State.CANCELLED && throwable == cancelledException) { // The callback did not catch the cancelled exception (which it should have), but // we'll keep the cancelled state. - return; + shouldCloseDelegate = false; + } else { + executionException = SpannerExceptionFactory.asSpannerException(throwable); } - executionException = SpannerExceptionFactory.asSpannerException(e); - cursorReturnedDoneOrException = true; + } + if (shouldCloseDelegate) { + closeDelegateResultSet(); } return; } + boolean shouldCloseDelegate = false; + boolean shouldReturn = false; synchronized (monitor) { - if (state == State.CANCELLED) { - if (cursorReturnedDoneOrException) { - return; - } - } else { - switch (response) { - case DONE: - state = State.DONE; - cursorReturnedDoneOrException = true; - return; - case PAUSE: - state = State.PAUSED; - // Make sure no-one else is waiting on the current pause latch and create a new - // one. - pausedLatch.countDown(); - pausedLatch = new CountDownLatch(1); - return; - case CONTINUE: - if (buffer.isEmpty()) { - // Call the callback once more if the entire result set has been processed but - // the callback has not yet received a CursorState.DONE or a CANCELLED error. - if (finished && !cursorReturnedDoneOrException) { - break; - } - state = State.RUNNING; - return; - } - break; - default: - throw new IllegalStateException("Unknown response: " + response); + currentRow = null; + callbackInvocationThread = null; + if (response == CallbackResponse.DONE || cursorReturnedDoneOrException) { + if (state != State.CANCELLED) { + state = State.DONE; } + cursorReturnedDoneOrException = true; + shouldCloseDelegate = true; + shouldReturn = true; + } else if (state == State.CANCELLED) { + // cancel() occurred concurrently during cursorReady() before tryNext() observed + // CANCELLED, and callback returned PAUSE or CONTINUE. Loop once more so the + // callback gets its one guaranteed chance to catch CANCELLED. + } else if (response == CallbackResponse.PAUSE) { + state = State.PAUSED; + shouldReturn = true; + } else if (buffer.isEmpty() && !finished && executionException == null) { + state = State.RUNNING; + shouldReturn = true; } } + if (shouldCloseDelegate) { + closeDelegateResultSet(); + } + if (shouldReturn) { + return; + } } } finally { synchronized (monitor) { - // Count down all latches that the producer might be waiting on. - consumingLatch.countDown(); - while (bufferConsumptionLatch.getCount() > 0L) { - bufferConsumptionLatch.countDown(); - } + callbackRunning = false; } + scheduleCallbackIfNecessary(); + checkCompletion(); } } } @@ -496,247 +549,422 @@ public void run() { /** * {@link ProduceRowsRunnable} reads data from the underlying {@link ResultSet}, places these in * the buffer and dispatches the {@link CallbackRunnable} when data is ready to be consumed. + * + *

For {@link StreamingResultSet} delegates, this task yields back to the executor whenever + * {@link StreamingResultSet#isDataAvailable()} returns {@code false} or the row buffer reaches + * {@link #maxBufferSize}, and is re-scheduled by {@link #onStreamMessage} or consumer drain. A + * task thread may still block synchronously on non-streaming {@link ResultSet} implementations or + * mid-stream retry backoff inside {@link ResumableStreamIterator}. */ private class ProduceRowsRunnable implements Runnable { @Override public void run() { - boolean stop = false; - boolean hasNext = false; - ResultSet delegate = null; try { + boolean isStreaming; synchronized (monitor) { - stop = shouldStopProducing(); - } - if (!stop) { - delegate = getOrInitializeDelegate(); - hasNext = delegate.next(); - } - } catch (Throwable e) { - synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(e); - stop = true; + if (shouldStopProducer()) { + return; + } + producerWakeupRequested = false; + isStreaming = streamingSupported; } - } - try { - while (!stop && hasNext && delegate != null) { - try { + ResultSet delegate = getOrInitializeDelegate(); + while (true) { + if (!isDataAvailable(delegate)) { synchronized (monitor) { - stop = shouldStopProducing(); + if (producerWakeupRequested && !shouldStopProducer()) { + producerWakeupRequested = false; + continue; + } } - if (!stop) { - while (buffer.remainingCapacity() == 0 && !stop) { - waitIfPaused(); - // The buffer is full and we should let the callback consume a number of rows before - // we proceed with producing any more rows to prevent us from potentially waiting on - // a full buffer repeatedly. - // Wait until at least half of the buffer is available, or if it's a bigger buffer, - // wait until at least 10 rows can be placed in it. - // TODO: Make this more dynamic / configurable? - startCallbackWithBufferLatchIfNecessary( - Math.min( - Math.min(buffer.size() / 2 + 1, buffer.size()), - MAX_WAIT_FOR_BUFFER_CONSUMPTION)); - bufferConsumptionLatch.await(); - synchronized (monitor) { - stop = shouldStopProducing(); - } + break; + } + boolean hasNext = delegate.next(); + if (hasNext) { + Struct row = delegate.getCurrentRowAsStruct(); + boolean shouldScheduleCallback; + synchronized (monitor) { + buffer.addLast(row); + if (buffer.size() >= maxBufferSize) { + waitingForBufferSpace = true; + break; } + if (shouldStopProducer()) { + break; + } + producerWakeupRequested = false; + shouldScheduleCallback = + !callbackRunning && (!isStreaming || buffer.size() >= DEFAULT_BUFFER_SIZE); } - if (!stop) { - buffer.put(delegate.getCurrentRowAsStruct()); - startCallbackIfNecessary(); - hasNext = delegate.next(); + if (shouldScheduleCallback) { + scheduleCallbackIfNecessary(); + synchronized (monitor) { + if (shouldStopProducer()) { + break; + } + } } - } catch (Throwable e) { + } else { + closeDelegateResultSet(); synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(e); - stop = true; + finished = true; } + break; } } - // We don't need any more data from the underlying result set, so we close it as soon as - // possible. Any error that might occur during this will be ignored. - closeDelegateResultSet(); - - // Ensure that the callback has been called at least once, even if the result set was - // cancelled. + scheduleCallbackIfNecessary(); + } catch (Throwable throwable) { synchronized (monitor) { - finished = true; - stop = cursorReturnedDoneOrException; - } - // Call the callback if there are still rows in the buffer that need to be processed. - while (!stop) { - try { - waitIfPaused(); - startCallbackIfNecessary(); - // Make sure we wait until the callback runner has actually finished. - consumingLatch.await(); - synchronized (monitor) { - stop = cursorReturnedDoneOrException; - } - } catch (Throwable e) { - result.setException(e); - return; - } + setExecutionExceptionLocked(throwable); } + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); } finally { - if (executorProvider.shouldAutoClose()) { - service.shutdown(); - } - List listenersToNotify = Collections.emptyList(); + boolean shouldExecuteProducer = false; synchronized (monitor) { - if (!listeners.isEmpty()) { - listenersToNotify = new ArrayList<>(listeners); + producerRunning = false; + if (producerWakeupRequested) { + producerWakeupRequested = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); } } - for (Runnable listener : listenersToNotify) { - listener.run(); - } - synchronized (monitor) { - if (executionException != null) { - result.setException(executionException); - } else if (state == State.CANCELLED) { - result.setException(CANCELLED_EXCEPTION); - } else { - result.set(null); - } + if (shouldExecuteProducer) { + executeProducer(); } + checkCompletion(); } } + } - /** - * Returns true if no more rows should be produced. This is the case if the result set has been - * cancelled or is done, or if the callback will not be invoked anymore (e.g. because it threw - * an exception). Must be called while holding the monitor. - */ - private boolean shouldStopProducing() { - return state.shouldStop || cursorReturnedDoneOrException; + private final ProduceRowsRunnable produceRowsRunnable = new ProduceRowsRunnable(); + + private static boolean isDataAvailable(ResultSet delegate) { + try { + return StreamingUtil.isDataAvailable(delegate); + } catch (Throwable throwable) { + // Returning true ensures that any exception encountered while checking for available data is + // not swallowed. The producer will proceed to invoke next(), where the exception is caught, + // recorded in executionException, and propagated to the caller. + return true; } + } - private void waitIfPaused() throws InterruptedException { - CountDownLatch pause; + @GuardedBy("monitor") + private void setExecutionExceptionLocked(Throwable throwable) { + if (executionException == null && !state.shouldStop) { + executionException = SpannerExceptionFactory.asSpannerException(throwable); + } + } + + @GuardedBy("monitor") + private boolean shouldStopProducer() { + return finished + || cursorReturnedDoneOrException + || state.shouldStop + || state == State.PAUSED + || executionException != null; + } + + @GuardedBy("monitor") + private boolean canScheduleProducer() { + return !initiatingStreaming + && produceRowsInitiated + && !shouldStopProducer() + && !waitingForBufferSpace; + } + + @GuardedBy("monitor") + private boolean prepareScheduleProducerLocked() { + if (producerRunning) { + if (!shouldStopProducer() && !waitingForBufferSpace) { + producerWakeupRequested = true; + } + return false; + } + if (!canScheduleProducer()) { + return false; + } + producerRunning = true; + producerWakeupRequested = false; + return true; + } + + private void executeProducer() { + try { + service.execute(produceRowsRunnable); + } catch (Throwable throwable) { synchronized (monitor) { - pause = pausedLatch; + setExecutionExceptionLocked(throwable); + producerRunning = false; } - pause.await(); + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); + checkCompletion(); } + } - private void startCallbackIfNecessary() { - startCallbackWithBufferLatchIfNecessary(0); + private void scheduleProducerIfNecessary() { + boolean shouldExecute; + synchronized (monitor) { + shouldExecute = prepareScheduleProducerLocked(); } + if (shouldExecute) { + executeProducer(); + } + } - private void startCallbackWithBufferLatchIfNecessary(int bufferLatch) { - boolean shouldExecute = false; - synchronized (monitor) { - if ((state == State.RUNNING || state == State.CANCELLED) - && !cursorReturnedDoneOrException) { - consumingLatch = new CountDownLatch(1); - if (bufferLatch > 0) { - bufferConsumptionLatch = new CountDownLatch(bufferLatch); - } - if (state == State.RUNNING) { - state = State.CONSUMING; - } - shouldExecute = true; + @GuardedBy("monitor") + private boolean canScheduleCallback() { + return !initiatingStreaming + && !cursorReturnedDoneOrException + && !callbackRunning + && (state == State.CANCELLED + || (state == State.RUNNING + && (!buffer.isEmpty() || finished || executionException != null))); + } + + private void scheduleCallbackIfNecessary() { + Executor callbackExecutor = null; + synchronized (monitor) { + if (canScheduleCallback()) { + if (state == State.RUNNING) { + state = State.CONSUMING; } + callbackRunning = true; + callbackExecutor = Preconditions.checkNotNull(this.executor); + } + } + if (callbackExecutor != null) { + try { + callbackExecutor.execute(callbackRunnable); + } catch (Throwable throwable) { + synchronized (monitor) { + setExecutionExceptionLocked(throwable); + callbackRunning = false; + cursorReturnedDoneOrException = true; + } + closeDelegateResultSet(); + checkCompletion(); + } + } + } + + private void checkCompletion() { + boolean shouldComplete = false; + synchronized (monitor) { + if (!completed + && cursorReturnedDoneOrException + && !initiatingStreaming + && !producerRunning + && !callbackRunning) { + if (state != State.CANCELLED) { + state = State.DONE; + } + completed = true; + shouldComplete = true; + } + } + if (shouldComplete) { + cleanupAndCompleteResult(); + } + } + + private void cleanupAndCompleteResult() { + closeDelegateResultSet(); + maybeNotifyStartOrClose(); + currentRow = null; + SpannerException finalException; + SpannerException finalCancelledException; + State finalState; + SettableApiFuture resultFuture; + List listenersToNotify = Collections.emptyList(); + synchronized (monitor) { + buffer.clear(); + finalException = executionException; + finalCancelledException = cancelledException; + finalState = state; + resultFuture = Preconditions.checkNotNull(result); + callback = null; + executor = null; + if (!listeners.isEmpty()) { + listenersToNotify = new ArrayList<>(listeners); + listeners.clear(); } - if (shouldExecute) { + } + try { + for (Runnable listener : listenersToNotify) { try { - executor.execute(callbackRunnable); - } catch (Throwable t) { - synchronized (monitor) { - consumingLatch.countDown(); - while (bufferConsumptionLatch.getCount() > 0L) { - bufferConsumptionLatch.countDown(); - } - if (state == State.CONSUMING) { - state = State.RUNNING; - } - } - throw t; + listener.run(); + } catch (Throwable throwable) { + log.log(Level.WARNING, "Listener threw exception", throwable); } } + if (executorProvider.shouldAutoClose()) { + service.shutdown(); + } + } finally { + if (finalException != null) { + resultFuture.setException(finalException); + } else if (finalState == State.CANCELLED) { + resultFuture.setException(Preconditions.checkNotNull(finalCancelledException)); + } else { + resultFuture.set(null); + } } } + /** + * Initializes the delegate {@link ResultSet} and starts streaming if supported. Note that + * obtaining the delegate or starting the stream may still block synchronously on future-backed + * {@link ResultSet} suppliers (such as {@link ResultSets#toAsyncResultSet(ApiFuture, + * ExecutorProvider, Options.ReadQueryUpdateTransactionOption...)}) or when waiting for an + * inlined-begin transaction ID on concurrent queries sharing a transaction. + */ private class InitiateStreamingRunnable implements Runnable { @Override public void run() { try { - // This method returns true if the underlying result set is a streaming result set (e.g. a - // GrpcResultSet). - // Those result sets will trigger initiateProduceRows() when the first results are received. - // Non-streaming result sets do not trigger this callback, and for those result sets, we - // need to eagerly start the ProduceRowsRunnable. - if (!initiateStreaming(AsyncResultSetImpl.this)) { - initiateProduceRows(); + boolean shouldStop; + synchronized (monitor) { + shouldStop = state.shouldStop; + } + if (shouldStop) { + closeDelegateResultSet(); + return; + } + // Initiate streaming on the underlying result set if it supports streaming (such as + // GrpcResultSet). Streaming result sets notify onStreamMessage() as chunks arrive. While + // initiatingStreaming is true, neither ProduceRowsRunnable nor CallbackRunnable may be + // dispatched so that delegate access remains strictly single-threaded until + // initiateStreaming() finishes. If the delegate is non-streaming or already has data or + // closure ready immediately after initiateStreaming() (for example, if the delegate was + // closed concurrently before starting an RPC), start producing rows immediately. + boolean isStreaming = initiateStreaming(AsyncResultSetImpl.this); + boolean startImmediately = !isStreaming; + if (!startImmediately) { + boolean alreadyInitiated; + synchronized (monitor) { + alreadyInitiated = produceRowsInitiated || state.shouldStop; + } + startImmediately = !alreadyInitiated && isDataAvailable(delegateResultSet.get()); + } + synchronized (monitor) { + streamingSupported = isStreaming; + if (startImmediately) { + produceRowsInitiated = true; + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + } } } catch (Throwable exception) { + GrpcResultSet grpcDelegate = unwrapGrpcResultSet(); + if (grpcDelegate != null) { + exception = translateGrpcInitiateStreamingException(grpcDelegate, exception); + } + closeDelegateResultSet(); synchronized (monitor) { - executionException = SpannerExceptionFactory.asSpannerException(exception); + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + setExecutionExceptionLocked(exception); } - initiateProduceRows(); + } finally { + boolean shouldExecuteProducer; + synchronized (monitor) { + initiatingStreaming = false; + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + if (shouldExecuteProducer) { + executeProducer(); + } + scheduleCallbackIfNecessary(); + checkCompletion(); + } + } + } + + @Nullable + private GrpcResultSet unwrapGrpcResultSet() { + synchronized (monitor) { + if (!delegateInitialized || delegateClosed || state.shouldStop) { + return null; } } + try { + ResultSet current = delegateResultSet.get(); + while (current instanceof ForwardingResultSet) { + current = ((ForwardingResultSet) current).getDelegate(); + } + return current instanceof GrpcResultSet ? (GrpcResultSet) current : null; + } catch (Throwable ignored) { + return null; + } + } + + private static Throwable translateGrpcInitiateStreamingException( + GrpcResultSet grpcDelegate, Throwable exception) { + try { + if (grpcDelegate.isDataAvailable()) { + grpcDelegate.next(); + } + } catch (Throwable nextException) { + return nextException; + } + return exception; } /** Sets the callback for this {@link AsyncResultSet}. */ @Override - public ApiFuture setCallback(Executor exec, ReadyCallback cb) { - Preconditions.checkNotNull(exec, "exec cannot be null"); - Preconditions.checkNotNull(cb, "cb cannot be null"); - boolean shouldClose = false; + public ApiFuture setCallback(Executor executor, ReadyCallback callback) { + Preconditions.checkNotNull(executor, "exec cannot be null"); + Preconditions.checkNotNull(callback, "cb cannot be null"); + SettableApiFuture resultFuture = SettableApiFuture.create(); + synchronized (monitor) { + Preconditions.checkState(!closed, "This AsyncResultSet has been closed"); + Preconditions.checkState( + this.state == State.INITIALIZED, "callback may not be set multiple times"); + + // Start to fetch data and buffer these. + this.result = resultFuture; + this.executor = MoreExecutors.newSequentialExecutor(executor); + this.callback = callback; + this.state = State.STREAMING_INITIALIZED; + this.initiatingStreaming = true; + } try { + this.service.execute(new InitiateStreamingRunnable()); + } catch (Throwable throwable) { + boolean shouldRollback = false; synchronized (monitor) { - Preconditions.checkState(!closed, "This AsyncResultSet has been closed"); - Preconditions.checkState( - this.state == State.INITIALIZED, "callback may not be set multiple times"); - - // Start to fetch data and buffer these. - this.result = SettableApiFuture.create(); - this.executor = MoreExecutors.newSequentialExecutor(exec); - this.callback = cb; - this.state = State.STREAMING_INITIALIZED; - try { - this.service.execute(new InitiateStreamingRunnable()); - } catch (Throwable throwable) { + if (this.initiatingStreaming) { + this.initiatingStreaming = false; + this.cancelledException = null; + this.state = State.INITIALIZED; this.closed = true; - shouldClose = true; - throw throwable; + this.executor = null; + this.callback = null; + this.result = null; + shouldRollback = true; } - pausedLatch.countDown(); - return result; } - } finally { - if (shouldClose) { + if (shouldRollback) { closeDelegateResultSet(); maybeNotifyStartOrClose(); if (executorProvider.shouldAutoClose()) { service.shutdown(); } } + throw throwable; } + return resultFuture; } - private void initiateProduceRows() { - boolean shouldExecute = false; + @Nullable Future getResult() { synchronized (monitor) { - if (!produceRowsInitiated) { - produceRowsInitiated = true; - if (this.state == State.STREAMING_INITIALIZED) { - this.state = State.RUNNING; - } - shouldExecute = true; - } + return result; } - if (shouldExecute) { - this.service.execute(new ProduceRowsRunnable()); - } - } - - Future getResult() { - return result; } @Override @@ -745,22 +973,38 @@ public void cancel() { Preconditions.checkState( state != State.INITIALIZED && state != State.SYNC, "cannot cancel a result set without a callback"); + if (completed || state == State.DONE || cursorReturnedDoneOrException) { + return; + } + if (cancelledException == null) { + cancelledException = + SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "This AsyncResultSet has been cancelled"); + } + executionException = null; state = State.CANCELLED; - pausedLatch.countDown(); } + closeDelegateResultSet(); + scheduleCallbackIfNecessary(); + checkCompletion(); } @Override public void resume() { + boolean shouldResume = false; synchronized (monitor) { Preconditions.checkState( state != State.INITIALIZED && state != State.SYNC, "cannot resume a result set without a callback"); if (state == State.PAUSED) { state = State.RUNNING; - pausedLatch.countDown(); + shouldResume = true; } } + if (shouldResume) { + scheduleCallbackIfNecessary(); + scheduleProducerIfNecessary(); + } } private static class CreateListCallback implements ReadyCallback { @@ -814,8 +1058,9 @@ public List toList(Function transformer) throws SpannerE return future.get(); } catch (ExecutionException e) { throw SpannerExceptionFactory.asSpannerException(e.getCause()); - } catch (Throwable e) { - throw SpannerExceptionFactory.asSpannerException(e); + } catch (InterruptedException e) { + cancel(); + throw SpannerExceptionFactory.propagateInterrupt(e); } } @@ -828,10 +1073,11 @@ public boolean next() throws SpannerException { "Cannot call next() on a result set with a callback."); this.state = State.SYNC; } + syncHasCurrentRow = false; ResultSet delegate = getOrInitializeDelegate(); - boolean res = delegate.next(); - currentRow = res ? delegate.getCurrentRowAsStruct() : null; - return res; + boolean hasNext = delegate.next(); + syncHasCurrentRow = hasNext; + return hasNext; } /** @@ -840,6 +1086,7 @@ public boolean next() throws SpannerException { * and finishing the query. */ @Override + @Nullable public ResultSetStats getStats() { return getOrInitializeDelegate().getStats(); } @@ -855,41 +1102,152 @@ public ResultSetMetadata getMetadata() { return getOrInitializeDelegate().getMetadata(); } + @VisibleForTesting boolean initiateStreaming(StreamMessageListener streamMessageListener) { return StreamingUtil.initiateStreaming(getOrInitializeDelegate(), streamMessageListener); } + private StructReader getSchemaReader() { + Struct row = getCurrentCallbackRow(); + if (row != null) { + return row; + } + checkValidStateSlow(/* allowAfterDone= */ true); + return getOrInitializeDelegate(); + } + + @Override + public Type getType() { + return getSchemaReader().getType(); + } + + @Override + public int getColumnCount() { + return getSchemaReader().getColumnCount(); + } + + @Override + public int getColumnIndex(String columnName) { + return getSchemaReader().getColumnIndex(columnName); + } + + @Override + public Type getColumnType(int columnIndex) { + return getSchemaReader().getColumnType(columnIndex); + } + + @Override + @Nullable + public Type getColumnType(String columnName) { + return getSchemaReader().getColumnType(columnName); + } + + private boolean isInCallbackInvocation() { + return callbackInvocationThread == Thread.currentThread(); + } + + @Nullable + private Struct getCurrentCallbackRow() { + return isInCallbackInvocation() ? currentRow : null; + } + @Override protected void checkValidState() { + if (getCurrentCallbackRow() != null) { + return; + } + checkValidStateSlow(/* allowAfterDone= */ false); + } + + private void checkValidStateSlow(boolean allowAfterDone) { synchronized (monitor) { + if (state == State.SYNC) { + Preconditions.checkState(!closed, "ResultSet is closed"); + return; + } Preconditions.checkState( - state == State.SYNC || state == State.CONSUMING || state == State.CANCELLED, + isInCallbackInvocation(), "only allowed after a next() call or from within a ReadyCallback#cursorReady callback"); - Preconditions.checkState(state != State.SYNC || !closed, "ResultSet is closed"); + Preconditions.checkState( + allowAfterDone && finished && cursorReturnedDoneOrException && state != State.CANCELLED, + "AsyncResultSet is not positioned on a row"); } } @Override public Struct getCurrentRowAsStruct() { - checkValidState(); - return currentRow; + Struct row = getCurrentCallbackRow(); + if (row != null) { + return row; + } + checkValidStateSlow(/* allowAfterDone= */ false); + Preconditions.checkState(syncHasCurrentRow, "next() call required"); + return getOrInitializeDelegate().getCurrentRowAsStruct(); } @Override public void onStreamMessage(PartialResultSet partialResultSet, boolean bufferIsFull) { + boolean shouldExecuteProducer; synchronized (monitor) { - if (produceRowsInitiated) { + if (state.shouldStop) { return; } - // if PartialResultSet contains a resume token or buffer size is full, or - // we have reached the end of the stream, we can start the thread. - boolean startJobThread = - !partialResultSet.getResumeToken().isEmpty() + if (!produceRowsInitiated + && (!partialResultSet.getResumeToken().isEmpty() || bufferIsFull - || partialResultSet == GrpcStreamIterator.END_OF_STREAM; - if (startJobThread || state != State.STREAMING_INITIALIZED) { - initiateProduceRows(); + || partialResultSet == GrpcStreamIterator.END_OF_STREAM + || ++initialChunksWithoutResumeToken > MAX_BUFFERED_CHUNKS)) { + produceRowsInitiated = true; + if (state == State.STREAMING_INITIALIZED) { + state = State.RUNNING; + } + } + shouldExecuteProducer = prepareScheduleProducerLocked(); + } + if (shouldExecuteProducer) { + executeProducer(); + } + } + + private static final class MemoizingSupplier implements Supplier { + private final Object lock = new Object(); + + @GuardedBy("lock") + @Nullable + private Supplier delegate; + + private volatile boolean initialized; + + @Nullable private ResultSet value; + @Nullable private Throwable exception; + + private MemoizingSupplier(Supplier delegate) { + this.delegate = delegate; + } + + @Override + public ResultSet get() { + if (!initialized) { + synchronized (lock) { + if (!initialized) { + Supplier supplier = Preconditions.checkNotNull(delegate); + delegate = null; + try { + value = Preconditions.checkNotNull(supplier.get()); + } catch (Throwable throwable) { + exception = throwable; + } finally { + initialized = true; + } + } + } + } + Throwable thrown = exception; + if (thrown != null) { + Throwables.throwIfUnchecked(thrown); + throw SpannerExceptionFactory.asSpannerException(thrown); } + return Preconditions.checkNotNull(value); } } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsProvider.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsProvider.java index e43d848671af..13446ba49884 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsProvider.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsProvider.java @@ -40,8 +40,10 @@ import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.contrib.gcp.resource.GCPResourceProvider; import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.export.MetricExporter; import io.opentelemetry.sdk.resources.Resource; import java.io.BufferedReader; import java.io.IOException; @@ -57,107 +59,247 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; -final class BuiltInMetricsProvider { - - static BuiltInMetricsProvider INSTANCE = new BuiltInMetricsProvider(); +/** + * Per-client provider for built-in Cloud Monitoring metrics. Each {@link SpannerOptions} owns a + * dedicated instance so credentials, monitoring endpoints, universe domains, fallback project IDs, + * and {@code client_uid} values remain isolated across clients in the same JVM. + */ +class BuiltInMetricsProvider { private static final Logger logger = Logger.getLogger(BuiltInMetricsProvider.class.getName()); - private static String taskId; + static final long DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 10L; + + private static final Object PID_AND_HOST_LOCK = new Object(); + private static volatile String cachedPidAndHost; - private static String location; + private static final Object LOCATION_LOCK = new Object(); + private static volatile String location; private static final String default_location = "global"; + private final Object lock = new Object(); private OpenTelemetry openTelemetry; - private String projectId; + private boolean ownsOpenTelemetry; + // Held in an AtomicReference so PeriodicMetricReader export threads read the fallback project + // lock-free during periodic and final-flush exports, and close() can detach a new reference + // without clearing the closing exporter's view. + private volatile AtomicReference fallbackProjectId = new AtomicReference<>(); private boolean mismatchedProjectIdLogged; private Thread shutdownHook; + private String clientUid; - private BuiltInMetricsProvider() {} + // Package-private and non-final so tests can record the arguments passed by SpannerOptions. + @VisibleForTesting + BuiltInMetricsProvider() {} - synchronized OpenTelemetry getOrCreateOpenTelemetry( + /** + * Returns the Cloud Monitoring {@link OpenTelemetry} instance for this client, lazily creating + * and registering a JVM shutdown hook for it on the first call. Returns {@code null} if exporter + * creation fails with an {@link IOException}. + */ + @Nullable + OpenTelemetry getOrCreateOpenTelemetry( String projectId, @Nullable Credentials credentials, @Nullable String monitoringHost, String universeDomain) { - try { - if (this.openTelemetry == null) { - SdkMeterProviderBuilder sdkMeterProviderBuilder = SdkMeterProvider.builder(); - BuiltInMetricsView.registerBuiltinMetrics( - SpannerCloudMonitoringExporter.create( - this::getProjectId, credentials, monitoringHost, universeDomain), - sdkMeterProviderBuilder); - sdkMeterProviderBuilder.setResource(Resource.create(createResourceAttributes(projectId))); - SdkMeterProvider sdkMeterProvider = sdkMeterProviderBuilder.build(); - this.openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProvider).build(); - this.shutdownHook = new Thread(sdkMeterProvider::close); - Runtime.getRuntime().addShutdownHook(this.shutdownHook); + synchronized (lock) { + try { + if (this.openTelemetry == null) { + AtomicReference projectRef = this.fallbackProjectId; + String uid = currentClientUid(); + SdkMeterProviderBuilder sdkMeterProviderBuilder = SdkMeterProvider.builder(); + BuiltInMetricsView.registerBuiltinMetrics( + createExporter( + projectRef::get, + createClientAttributes(uid), + credentials, + monitoringHost, + universeDomain), + sdkMeterProviderBuilder); + sdkMeterProviderBuilder.setResource( + Resource.create(createResourceAttributes(projectId, uid))); + SdkMeterProvider sdkMeterProvider = sdkMeterProviderBuilder.build(); + this.openTelemetry = + OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProvider).build(); + this.ownsOpenTelemetry = true; + Thread hook = new Thread(sdkMeterProvider::close); + try { + Runtime.getRuntime().addShutdownHook(hook); + this.shutdownHook = hook; + } catch (IllegalStateException ignored) { + // The JVM is already shutting down; skip registering a shutdown hook. + this.shutdownHook = null; + } + } + return this.openTelemetry; + } catch (IOException ex) { + logger.log( + Level.WARNING, + "Unable to get OpenTelemetry object for client side metrics, will skip exporting client" + + " side metrics", + ex); + return null; } - return this.openTelemetry; - } catch (IOException ex) { - logger.log( - Level.WARNING, - "Unable to get OpenTelemetry object for client side metrics, will skip exporting client" - + " side metrics", - ex); - return null; } } - synchronized void setProjectIdIfAbsent(String projectId) { - if (this.projectId == null) { - this.projectId = projectId; - } else if (!this.projectId.equals(projectId) && !mismatchedProjectIdLogged) { - mismatchedProjectIdLogged = true; - logger.log( - Level.WARNING, - "Built-in metrics fallback project is already initialized to project {0}. Non-Spanner" - + " metrics without project information will be exported using that project instead" - + " of project {1}.", - new Object[] {this.projectId, projectId}); + /** + * Creates the {@link MetricExporter} backing this provider. Package-private and overridable in + * tests to inspect exporter settings or inject deterministic test doubles. + */ + @VisibleForTesting + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) + throws IOException { + return SpannerCloudMonitoringExporter.create( + fallbackProjectIdSupplier, clientAttributes, credentials, monitoringHost, universeDomain); + } + + /** Sets the fallback project ID for non-Spanner gRPC metrics if not yet initialized. */ + void setProjectIdIfAbsent(String projectId) { + synchronized (lock) { + String current = this.fallbackProjectId.get(); + if (current == null) { + this.fallbackProjectId.set(projectId); + } else if (!current.equals(projectId) && !mismatchedProjectIdLogged) { + mismatchedProjectIdLogged = true; + logger.log( + Level.WARNING, + "Built-in metrics fallback project is already initialized to project {0}. Non-Spanner" + + " metrics without project information will be exported using that project instead" + + " of project {1}.", + new Object[] {current, projectId}); + } } } @Nullable - synchronized OpenTelemetry getOpenTelemetry() { - return this.openTelemetry; + OpenTelemetry getOpenTelemetry() { + synchronized (lock) { + return this.openTelemetry; + } } /** * Injects the Cloud Monitoring OpenTelemetry so that {@link #getOrCreateOpenTelemetry} returns it * instead of building one backed by the live Cloud Monitoring exporter. Used to observe the - * reserved-namespace sink in-memory in tests. + * reserved-namespace sink in-memory in tests. Injected instances are owned by the caller and are + * not shut down by {@link #close()}. */ @VisibleForTesting - synchronized void setOpenTelemetry(OpenTelemetry openTelemetry) { - this.openTelemetry = openTelemetry; + void setOpenTelemetry(OpenTelemetry openTelemetry) { + synchronized (lock) { + this.openTelemetry = openTelemetry; + this.ownsOpenTelemetry = false; + } + } + + /** Returns the current fallback project ID lock-free for export threads. */ + String getProjectId() { + return this.fallbackProjectId.get(); } - synchronized String getProjectId() { - return this.projectId; + /** + * Closes the provider-owned {@link OpenTelemetrySdk} with the default bounded shutdown timeout + * and rotates state so subsequent reuse of the owning {@link SpannerOptions} starts cleanly. + */ + void close() { + close(DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + /** + * Closes the provider-owned {@link OpenTelemetrySdk}, waiting at most {@code timeout} for the + * final flush. When {@code timeout <= 0}, shutdown is initiated asynchronously without blocking. + */ + void close(long timeout, TimeUnit unit) { + closeInternal(/* closeInjected= */ false, timeout, unit); } @VisibleForTesting - synchronized void reset() { - if (this.openTelemetry instanceof OpenTelemetrySdk) { - ((OpenTelemetrySdk) this.openTelemetry).getSdkMeterProvider().close(); + boolean hasShutdownHook() { + synchronized (lock) { + return this.shutdownHook != null; } - if (this.shutdownHook != null) { + } + + @VisibleForTesting + void reset() { + closeInternal(/* closeInjected= */ true, DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + + private void closeInternal(boolean closeInjected, long timeout, TimeUnit unit) { + final OpenTelemetry toClose; + final Thread hookToRemove; + synchronized (lock) { + toClose = (closeInjected || this.ownsOpenTelemetry) ? this.openTelemetry : null; + hookToRemove = this.shutdownHook; + this.openTelemetry = null; + this.ownsOpenTelemetry = false; + this.shutdownHook = null; + // Clear fallbackProjectId and clientUid so a subsequent reopen starts cleanly with a new + // lazy client_uid while any in-flight final flush keeps reading the previous AtomicReference. + this.fallbackProjectId = new AtomicReference<>(); + this.mismatchedProjectIdLogged = false; + this.clientUid = null; + } + if (hookToRemove != null) { try { - Runtime.getRuntime().removeShutdownHook(this.shutdownHook); + Runtime.getRuntime().removeShutdownHook(hookToRemove); } catch (IllegalStateException ignored) { // The JVM is already shutting down. } } - this.openTelemetry = null; - this.projectId = null; - this.mismatchedProjectIdLogged = false; - this.shutdownHook = null; + if (toClose instanceof OpenTelemetrySdk) { + shutdownMeterProvider(((OpenTelemetrySdk) toClose).getSdkMeterProvider(), timeout, unit); + } + } + + /** + * Shuts down {@code meterProvider} on a daemon thread so caller timeouts are strictly honored + * even though {@code PeriodicMetricReader#shutdown()} synchronously blocks up to 5 seconds per + * internal phase while waiting on a final export. + */ + private static void shutdownMeterProvider( + SdkMeterProvider meterProvider, long timeout, TimeUnit unit) { + CountDownLatch completed = new CountDownLatch(1); + Thread shutdownThread = + new Thread( + () -> { + try { + CompletableResultCode shutdownResult = meterProvider.shutdown(); + if (timeout > 0) { + shutdownResult.join(timeout, unit); + } + } catch (RuntimeException e) { + logger.log(Level.WARNING, "Failed to shut down built-in metrics provider", e); + } finally { + completed.countDown(); + } + }, + "spanner-builtin-metrics-shutdown"); + shutdownThread.setDaemon(true); + shutdownThread.start(); + if (timeout > 0) { + try { + completed.await(timeout, unit); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } } // TODO: Remove when @@ -196,19 +338,24 @@ void enableGrpcMetrics( @Nullable Credentials credentials, @Nullable String monitoringHost, String universeDomain) { - enableGrpcMetrics( - channelProviderBuilder, - this.getOrCreateOpenTelemetry(projectId, credentials, monitoringHost, universeDomain)); + OpenTelemetry otel = + this.getOrCreateOpenTelemetry(projectId, credentials, monitoringHost, universeDomain); + if (otel == null) { + return; + } + enableGrpcMetrics(channelProviderBuilder, otel); } /** - * Wires gRPC-layer metrics into the channel builder using the given OpenTelemetry instance - * instead of the process-wide Cloud Monitoring one. Used for {@link - * CustomOpenTelemetryMetricsProvider}; does not touch any state of this singleton. + * Wires gRPC-layer metrics into the channel builder using the given OpenTelemetry instance. Does + * nothing if {@code openTelemetry} is {@code null}. */ void enableGrpcMetrics( InstantiatingGrpcChannelProvider.Builder channelProviderBuilder, - OpenTelemetry openTelemetry) { + @Nullable OpenTelemetry openTelemetry) { + if (openTelemetry == null) { + return; + } GrpcOpenTelemetry grpcOpenTelemetry = GrpcOpenTelemetry.newBuilder() .sdk(openTelemetry) @@ -232,11 +379,15 @@ void enableGrpcMetrics( } Attributes createResourceAttributes(String projectId) { + return createResourceAttributes(projectId, currentClientUid()); + } + + private Attributes createResourceAttributes(String projectId, String uid) { AttributesBuilder attributesBuilder = Attributes.builder() .put(PROJECT_ID_KEY.getKey(), projectId) .put(INSTANCE_CONFIG_ID_KEY.getKey(), "unknown") - .put(CLIENT_HASH_KEY.getKey(), generateClientHash(getDefaultTaskValue())) + .put(CLIENT_HASH_KEY.getKey(), generateClientHash(uid)) .put(INSTANCE_ID_KEY.getKey(), "unknown") .put(LOCATION_ID_KEY.getKey(), detectClientLocation()); @@ -244,10 +395,24 @@ Attributes createResourceAttributes(String projectId) { } Map createClientAttributes() { + return createClientAttributes(currentClientUid()); + } + + /** Lazily initializes and returns the per-provider {@code client_uid} on first metrics use. */ + private String currentClientUid() { + synchronized (lock) { + if (this.clientUid == null) { + this.clientUid = createTaskValue(); + } + return this.clientUid; + } + } + + private Map createClientAttributes(String uid) { Map clientAttributes = new HashMap<>(); clientAttributes.put( CLIENT_NAME_KEY.getKey(), "spanner-java/" + GaxProperties.getLibraryVersion(getClass())); - clientAttributes.put(CLIENT_UID_KEY.getKey(), getDefaultTaskValue()); + clientAttributes.put(CLIENT_UID_KEY.getKey(), uid); return clientAttributes; } @@ -280,47 +445,78 @@ static String generateClientHash(String clientUid) { } static String detectClientLocation() { - if (location == null) { - location = default_location; - if (quickCheckIsRunningOnGcp()) { - Attributes detectedResourceAttributes = new GCPResourceProvider().getAttributes(); - // All platform except GKE uses "cloud.region" for region attribute. - // GKE could either use "cloud.region" or "cloud.availability_zone" for region attribute. - String region = detectedResourceAttributes.get(AttributeKey.stringKey("cloud.region")); - String gkeZonalClusterLocation = - detectedResourceAttributes.get(AttributeKey.stringKey("cloud.availability_zone")); - if (region == null && gkeZonalClusterLocation != null) { - region = gkeZonalClusterLocation; - } - location = region == null ? location : region; + return detectClientLocation(BuiltInMetricsProvider::resolveGcpLocation); + } + + /** + * Resolves and caches the client's GCP location once per JVM, ensuring concurrent clients wait + * for the first resolution to complete instead of observing an intermediate default value. + */ + @VisibleForTesting + static String detectClientLocation(Supplier locationResolver) { + String cachedLocation = location; + if (cachedLocation != null) { + return cachedLocation; + } + synchronized (LOCATION_LOCK) { + if (location == null) { + String resolved = locationResolver.get(); + location = resolved == null ? default_location : resolved; } + return location; + } + } + + private static String resolveGcpLocation() { + if (!quickCheckIsRunningOnGcp()) { + return default_location; + } + Attributes detectedResourceAttributes = new GCPResourceProvider().getAttributes(); + // All platform except GKE uses "cloud.region" for region attribute. + // GKE could either use "cloud.region" or "cloud.availability_zone" for region attribute. + String region = detectedResourceAttributes.get(AttributeKey.stringKey("cloud.region")); + String gkeZonalClusterLocation = + detectedResourceAttributes.get(AttributeKey.stringKey("cloud.availability_zone")); + if (region == null && gkeZonalClusterLocation != null) { + region = gkeZonalClusterLocation; + } + return region == null ? default_location : region; + } + + @VisibleForTesting + static void resetLocationForTesting() { + synchronized (LOCATION_LOCK) { + location = null; } - return location; } /** - * Generates a unique identifier for the Client_uid metric field. The identifier is composed of a - * UUID, the process ID (PID), and the hostname. - * - *

For Java 9 and later, the PID is obtained using the ProcessHandle API. For Java 8, the PID - * is extracted from ManagementFactory.getRuntimeMXBean().getName(). - * - * @return A unique identifier string in the format UUID@PID@hostname + * Generates a unique identifier for the {@code client_uid} metric field in the format {@code + * UUID@PID@hostname}, caching the PID and hostname once per JVM. */ - private static String getDefaultTaskValue() { - if (taskId == null) { - String identifier = UUID.randomUUID().toString(); - String pid = getProcessId(); + private static String createTaskValue() { + return UUID.randomUUID() + "@" + getPidAndHost(); + } - try { - String hostname = InetAddress.getLocalHost().getHostName(); - taskId = identifier + "@" + pid + "@" + hostname; - } catch (UnknownHostException e) { - logger.log(Level.INFO, "Unable to get the hostname.", e); - taskId = identifier + "@" + pid + "@localhost"; + private static String getPidAndHost() { + String pidAndHost = cachedPidAndHost; + if (pidAndHost != null) { + return pidAndHost; + } + synchronized (PID_AND_HOST_LOCK) { + if (cachedPidAndHost == null) { + String pid = getProcessId(); + String hostname; + try { + hostname = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + logger.log(Level.INFO, "Unable to get the hostname.", e); + hostname = "localhost"; + } + cachedPidAndHost = pid + "@" + hostname; } + return cachedPidAndHost; } - return taskId; } private static String getProcessId() { diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsTracer.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsTracer.java index a982a3f11ab5..cdaebbda8763 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsTracer.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsTracer.java @@ -35,7 +35,8 @@ class BuiltInMetricsTracer extends MetricsTracer implements ApiTracer { private final BuiltInMetricsRecorder builtInOpenTelemetryMetricsRecorder; - // These are RPC specific attributes and pertain to a specific API Trace + // These are RPC specific attributes and pertain to a specific API Trace. + // All accesses to this.* and super.* state are guarded by this instance's monitor. private final Map attributes = new HashMap<>(); private Float gfeLatency = null; private Float afeLatency = null; @@ -56,12 +57,42 @@ class BuiltInMetricsTracer extends MetricsTracer implements ApiTracer { this.currentSpan = currentSpan; } + @Override + public synchronized void operationSucceeded() { + super.operationSucceeded(); + } + + @Override + public synchronized void operationCancelled() { + super.operationCancelled(); + } + + @Override + public synchronized void operationFailed(Throwable error) { + super.operationFailed(error); + } + + @Override + public synchronized void attemptStarted(Object request, int attemptNumber) { + this.gfeLatency = null; + this.afeLatency = null; + this.isDirectPathUsed = false; + this.isAfeEnabled = false; + super.attemptStarted(request, attemptNumber); + } + + @Override + @SuppressWarnings("deprecation") + public synchronized void attemptStarted(int attemptNumber) { + attemptStarted(null, attemptNumber); + } + /** * Adds an annotation that the attempt succeeded. Successful attempt add "OK" value to the status * attribute key. */ @Override - public void attemptSucceeded() { + public synchronized void attemptSucceeded() { try (IScope s = this.traceWrapper.withSpan(this.currentSpan)) { super.attemptSucceeded(); attributes.put(STATUS_ATTRIBUTE, StatusCode.Code.OK.toString()); @@ -75,7 +106,7 @@ public void attemptSucceeded() { * to the status attribute key. */ @Override - public void attemptCancelled() { + public synchronized void attemptCancelled() { try (IScope s = this.traceWrapper.withSpan(this.currentSpan)) { super.attemptCancelled(); attributes.put(STATUS_ATTRIBUTE, StatusCode.Code.CANCELLED.toString()); @@ -93,7 +124,7 @@ public void attemptCancelled() { * key. */ @Override - public void attemptFailedDuration(Throwable error, java.time.Duration delay) { + public synchronized void attemptFailedDuration(Throwable error, java.time.Duration delay) { try (IScope s = this.traceWrapper.withSpan(this.currentSpan)) { super.attemptFailedDuration(error, delay); attributes.put(STATUS_ATTRIBUTE, extractStatus(error)); @@ -110,7 +141,7 @@ public void attemptFailedDuration(Throwable error, java.time.Duration delay) { * @param error the last error received before retries were exhausted. */ @Override - public void attemptFailedRetriesExhausted(Throwable error) { + public synchronized void attemptFailedRetriesExhausted(Throwable error) { try (IScope s = this.traceWrapper.withSpan(this.currentSpan)) { super.attemptFailedRetriesExhausted(error); attributes.put(STATUS_ATTRIBUTE, extractStatus(error)); @@ -127,7 +158,7 @@ public void attemptFailedRetriesExhausted(Throwable error) { * @param error the error that caused the final attempt to fail. */ @Override - public void attemptPermanentFailure(Throwable error) { + public synchronized void attemptPermanentFailure(Throwable error) { try (IScope s = this.traceWrapper.withSpan(this.currentSpan)) { super.attemptPermanentFailure(error); attributes.put(STATUS_ATTRIBUTE, extractStatus(error)); @@ -136,7 +167,7 @@ public void attemptPermanentFailure(Throwable error) { } } - public void recordServerTimingHeaderMetrics( + public synchronized void recordServerTimingHeaderMetrics( Float gfeLatency, Float afeLatency, boolean isDirectPathUsed, boolean isAfeEnabled) { this.gfeLatency = gfeLatency; this.isDirectPathUsed = isDirectPathUsed; @@ -145,13 +176,13 @@ public void recordServerTimingHeaderMetrics( } @Override - public void addAttributes(Map attributes) { + public synchronized void addAttributes(Map attributes) { super.addAttributes(attributes); this.attributes.putAll(attributes); } @Override - public void addAttributes(String key, String value) { + public synchronized void addAttributes(String key, String value) { super.addAttributes(key, value); this.attributes.put(key, value); } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DatabaseClient.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DatabaseClient.java index 694f5cb7f8bd..e0493d0862d5 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DatabaseClient.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DatabaseClient.java @@ -270,6 +270,11 @@ CommitResponse writeAtLeastOnceWithOptions( *

  • {@link Options#priority(com.google.cloud.spanner.Options.RpcPriority)}: The {@link * RpcPriority} to use for the batch write request. *
  • {@link Options#tag(String)}: The transaction tag to use for the batch write request. + *
  • {@link Options#excludeTxnFromChangeStreams()}: Excludes the transaction from change + * streams with the DDL option {@code allow_txn_exclusion=true}. + *
  • {@link Options#clientContext(com.google.spanner.v1.RequestOptions.ClientContext)}: The + * {@link com.google.spanner.v1.RequestOptions.ClientContext} to attach to the batch write + * request. * */ ServerStream batchWriteAtLeastOnce( diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DelayedMultiplexedSessionTransaction.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DelayedMultiplexedSessionTransaction.java index a691d5969dfc..4793742d0f9f 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DelayedMultiplexedSessionTransaction.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/DelayedMultiplexedSessionTransaction.java @@ -188,7 +188,7 @@ public ServerStream batchWriteAtLeastOnce( SessionReference sessionReference = getSessionReference(); try (MultiplexedSessionTransaction transaction = new MultiplexedSessionTransaction( - client, span, sessionReference, NO_CHANNEL_HINT, /* singleUse= */ true)) { + client, span, sessionReference, NO_CHANNEL_HINT, /* singleUse= */ false)) { return transaction.batchWriteAtLeastOnce(mutationGroups, options); } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java index 839202bb9fe3..64e4a8d318a4 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ForwardingStructReader.java @@ -32,7 +32,7 @@ /** Forwarding implements of StructReader */ public class ForwardingStructReader implements StructReader { - private Supplier delegate; + private volatile Supplier delegate; public ForwardingStructReader(StructReader delegate) { this.delegate = Suppliers.ofInstance(Preconditions.checkNotNull(delegate)); @@ -53,6 +53,10 @@ void replaceDelegate(StructReader newDelegate) { this.delegate = Suppliers.ofInstance(Preconditions.checkNotNull(newDelegate)); } + void replaceDelegateSupplier(Supplier newDelegate) { + this.delegate = Preconditions.checkNotNull(newDelegate); + } + /** * Called before each forwarding call to allow sub classes to do additional state checking. Sub * classes should throw an {@link Exception} if the current state is not valid for reading data @@ -152,11 +156,13 @@ public double getDouble(String columnName) { @Override public BigDecimal getBigDecimal(int columnIndex) { + checkValidState(); return delegate.get().getBigDecimal(columnIndex); } @Override public BigDecimal getBigDecimal(String columnName) { + checkValidState(); return delegate.get().getBigDecimal(columnName); } @@ -354,11 +360,13 @@ public List getDoubleList(String columnName) { @Override public List getBigDecimalList(int columnIndex) { + checkValidState(); return delegate.get().getBigDecimalList(columnIndex); } @Override public List getBigDecimalList(String columnName) { + checkValidState(); return delegate.get().getBigDecimalList(columnName); } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClient.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClient.java index 2291fb82e880..8aa4e7a7bdda 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClient.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClient.java @@ -40,6 +40,7 @@ import java.util.BitSet; import java.util.EnumSet; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -429,6 +430,18 @@ AtomicLong getNumSessionsReleased() { return this.numSessionsReleased; } + @VisibleForTesting + int getChannelUsageCardinality() { + synchronized (this.channelUsage) { + return this.channelUsage.cardinality(); + } + } + + @VisibleForTesting + int getNumCurrentSingleUseTransactions() { + return this.numCurrentSingleUseTransactions.get(); + } + @Override @Nullable public String getChannelPrimeSessionName() { @@ -650,8 +663,9 @@ public CommitResponse writeAtLeastOnceWithOptions( public ServerStream batchWriteAtLeastOnce( Iterable mutationGroups, TransactionOption... options) throws SpannerException { - return createMultiplexedSessionTransaction(/* singleUse= */ true) - .batchWriteAtLeastOnce(mutationGroups, options); + List materializedGroups = SessionImpl.materializeMutationGroups(mutationGroups); + return createMultiplexedSessionTransaction(/* singleUse= */ false) + .batchWriteAtLeastOnce(materializedGroups, options); } @Override diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java index e13245b1ef1d..f258682c7970 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/ResumableStreamIterator.java @@ -16,13 +16,10 @@ package com.google.cloud.spanner; -import static com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException; import static com.google.cloud.spanner.SpannerExceptionFactory.newSpannerExceptionForCancellation; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.api.client.util.BackOff; -import com.google.api.client.util.ExponentialBackOff; import com.google.api.core.InternalApi; import com.google.api.gax.grpc.GrpcStatusCode; import com.google.api.gax.retrying.RetrySettings; @@ -36,11 +33,12 @@ import com.google.spanner.v1.PartialResultSet; import io.grpc.Context; import io.opentelemetry.api.common.Attributes; -import java.io.IOException; +import java.time.Duration; import java.util.ArrayDeque; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; @@ -62,7 +60,11 @@ * token that differs from the last seen resume token) resets both, so a long-running stream that * regularly makes progress is not terminated by an occasional transient error. The default settings * have no maximum number of attempts or total timeout. Setting maxAttempts to 1 disables streaming - * retries. + * retries. Positive server-supplied retry delays are capped at {@link + * RetrySettings#getMaxRetryDelayDuration()} (defaulting to 32s when unset or non-positive) and + * floored at 1ms, and missing, malformed, or non-positive server retry delays fall back to + * exponential backoff. Client backoff applies [0.5x, 1.0x] jitter, so a delay never exceeds the + * effective max retry delay. * *

    These limits bound the number of streams that this iterator starts. Each (re)started stream is * a call through the underlying GAX callable, and GAX applies the same {@link RetrySettings} to @@ -89,8 +91,8 @@ abstract class ResumableStreamIterator extends AbstractIterator retryableCodes; + private static final Duration MIN_RETRY_DELAY = Duration.ofMillis(1L); private static final Logger logger = Logger.getLogger(ResumableStreamIterator.class.getName()); - @Nullable private BackOff backOff; private final ArrayDeque buffer = new ArrayDeque<>(); private final int maxBufferSize; private final ISpan span; @@ -181,74 +183,21 @@ protected ResumableStreamIterator( } /** - * Returns true if the number of consecutive failed attempts has reached the maximum number of - * attempts in the retry settings. {@link RetrySettings#getMaxAttempts()} equal to zero means that - * no maximum has been set, and that the number of attempts is unlimited. This is also the value - * in the default streaming retry settings, which means that only users who have explicitly opted - * in to a maximum number of attempts are affected by this limit. - */ - private boolean maxAttemptsExhausted() { - int maxAttempts = streamingRetrySettings.getMaxAttempts(); - return maxAttempts > 0 && attempts >= maxAttempts; - } - - /** - * Returns true if retrying after the proposed delay would exceed the total timeout in the retry - * settings. The total timeout limits the wall-clock time that is spent on a sequence of + * Returns true if retrying after {@code proposedDelay} would exceed the total timeout in the + * retry settings. The total timeout limits the wall-clock time that is spent on a sequence of * consecutive failed attempts without progress, measured from the first failure of the sequence. * It is only enforced for retry settings that set a positive total timeout: a total timeout of * zero means that no total timeout has been set, and that only maxAttempts (if set) limits the * retries. This mirrors the interpretation of these values in GAX. */ - private boolean totalTimeoutExceeded(long proposedDelayMillis) { - long totalTimeoutMillis = streamingRetrySettings.getTotalTimeout().toMillis(); - if (totalTimeoutMillis <= 0L) { - return false; - } - long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(nanoTime() - retrySequenceStartNanos); - if (elapsedMillis < 0L) { - elapsedMillis = 0L; - } - if (elapsedMillis >= totalTimeoutMillis) { - return true; - } - return Math.max(proposedDelayMillis, 0L) >= totalTimeoutMillis - elapsedMillis; - } - - private ExponentialBackOff newBackOff() { - return new ExponentialBackOff.Builder() - .setMultiplier(streamingRetrySettings.getRetryDelayMultiplier()) - // All of these values must be > 0. - .setInitialIntervalMillis( - Math.max( - 1, - (int) - Math.min( - streamingRetrySettings.getInitialRetryDelay().toMillis(), - Integer.MAX_VALUE))) - .setMaxIntervalMillis( - Math.max( - 1, - (int) - Math.min( - streamingRetrySettings.getMaxRetryDelay().toMillis(), Integer.MAX_VALUE))) - // The total timeout is enforced explicitly in computeNext(), based on the elapsed time - // since the first failure of the current retry sequence. Prevent the backoff from - // returning BackOff.STOP, as that would misinterpret a total timeout of zero (that is, no - // total timeout) as a total timeout of one millisecond. - .setMaxElapsedTimeMillis(Integer.MAX_VALUE) - .build(); - } - - private static long nextBackOffMillis(BackOff backoff) throws SpannerException { - try { - return backoff.nextBackOffMillis(); - } catch (IOException e) { - throw newSpannerException(ErrorCode.INTERNAL, e.getMessage(), e); - } + @VisibleForTesting + boolean totalTimeoutExceeded(Duration proposedDelay) { + return StreamingRetryHelper.isTotalTimeoutExceeded( + streamingRetrySettings, nanoTime() - retrySequenceStartNanos, proposedDelay); } - private void backoffSleep(Context context, long backoffMillis) throws SpannerException { + @VisibleForTesting + void backoffSleep(Context context, long backoffMillis) throws SpannerException { tracer.getCurrentSpan().addAnnotation("Backing off", "Delay", backoffMillis); final CountDownLatch latch = new CountDownLatch(1); final Context.CancellationListener listener = @@ -259,10 +208,6 @@ private void backoffSleep(Context context, long backoffMillis) throws SpannerExc context.addListener(listener, DirectExecutor.INSTANCE); try { - if (backoffMillis == BackOff.STOP) { - // Highly unlikely but we handle it just in case. - backoffMillis = streamingRetrySettings.getMaxRetryDelay().toMillis(); - } if (latch.await(backoffMillis, TimeUnit.MILLISECONDS)) { // Woken by context cancellation. throw newSpannerExceptionForCancellation(context, null); @@ -465,37 +410,44 @@ long nanoTime() { return System.nanoTime(); } + /** Random source in {@code [0.0, 1.0)}, overridable for deterministic backoff tests. */ + @VisibleForTesting + double nextJitterRandom() { + return ThreadLocalRandom.current().nextDouble(); + } + @VisibleForTesting long checkRetryBudgetAndGetDelay(SpannerException spannerException) { if (attempts == 0) { retrySequenceStartNanos = nanoTime(); } attempts++; - if (maxAttemptsExhausted()) { + if (StreamingRetryHelper.isMaxAttemptsExhausted(streamingRetrySettings, attempts)) { span.addAnnotation( "Stream broken. Not retrying because the maximum number of attempts has been" + " exhausted", spannerException); throw spannerException; } - // Determine the retry delay: either the delay that the server included in the error, or - // otherwise a delay determined by the exponential backoff. - long delayMillis = spannerException.getRetryDelayInMillis(); - if (delayMillis == -1L) { - if (this.backOff == null) { - this.backOff = newBackOff(); - } - delayMillis = nextBackOffMillis(this.backOff); - } + // Determine the retry delay: clamp any positive server-supplied retry delay to [1ms, + // effectiveMaxRetryDelay], or fall back to exponential backoff when absent, malformed, or + // non-positive. + Duration delay = + StreamingRetryHelper.computeRetryDelay( + streamingRetrySettings, + spannerException, + attempts, + this::nextJitterRandom, + MIN_RETRY_DELAY); // The total timeout budget applies regardless of whether the delay came from the server // or from the backoff. - if (totalTimeoutExceeded(delayMillis)) { + if (totalTimeoutExceeded(delay)) { span.addAnnotation( "Stream broken. Not retrying because the total timeout has been exhausted", spannerException); throw spannerException; } - return delayMillis; + return StreamingRetryHelper.saturatedDurationMillis(delay, 1L, Long.MAX_VALUE); } private void handleRetryableException(Context context, SpannerException spannerException) { @@ -670,7 +622,6 @@ private void bufferChunkLocked(PartialResultSet next) { if (!next.getResumeToken().equals(resumeToken)) { // The stream made progress, so reset the budget for consecutive failed attempts. attempts = 0; - backOff = null; retrySequenceStartNanos = -1L; } resumeToken = next.getResumeToken(); diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionImpl.java index ef882da9ed4a..d9ecb6f9a6df 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionImpl.java @@ -31,7 +31,9 @@ import com.google.cloud.spanner.SessionClient.SessionOption; import com.google.cloud.spanner.TransactionRunnerImpl.TransactionContextImpl; import com.google.cloud.spanner.spi.v1.SpannerRpc; +import com.google.common.base.Preconditions; import com.google.common.base.Ticker; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.ByteString; @@ -291,7 +293,7 @@ public CommitResponse writeAtLeastOnceWithOptions( .setNanos(options.maxCommitDelay().getNano()) .build()); } - RequestOptions commitRequestOptions = getRequestOptions(transactionOptions); + RequestOptions commitRequestOptions = getRequestOptions(options); if (commitRequestOptions != null) { requestBuilder.setRequestOptions(commitRequestOptions); @@ -311,19 +313,24 @@ public CommitResponse writeAtLeastOnceWithOptions( } } - private RequestOptions getRequestOptions(TransactionOption... transactionOptions) { - Options requestOptions = Options.fromTransactionOptions(transactionOptions); - if (requestOptions.hasPriority() || requestOptions.hasTag()) { - RequestOptions.Builder requestOptionsBuilder = RequestOptions.newBuilder(); - if (requestOptions.hasPriority()) { - requestOptionsBuilder.setPriority(requestOptions.priority()); - } - if (requestOptions.hasTag()) { - requestOptionsBuilder.setTransactionTag(requestOptions.tag()); + static ImmutableList materializeMutationGroups( + Iterable mutationGroups) { + return ImmutableList.copyOf(Preconditions.checkNotNull(mutationGroups)); + } + + private RequestOptions getRequestOptions(Options requestOptions) { + RequestOptions.Builder requestOptionsBuilder = + requestOptions.toRequestOptionsProto(/* isTransactionOption= */ true).toBuilder(); + RequestOptions.ClientContext defaultClientContext = spanner.getOptions().getClientContext(); + if (defaultClientContext != null) { + RequestOptions.ClientContext.Builder clientContextBuilder = defaultClientContext.toBuilder(); + if (requestOptionsBuilder.hasClientContext()) { + clientContextBuilder.mergeFrom(requestOptionsBuilder.getClientContext()); } - return requestOptionsBuilder.build(); + requestOptionsBuilder.setClientContext(clientContextBuilder.build()); } - return null; + RequestOptions built = requestOptionsBuilder.build(); + return built.equals(RequestOptions.getDefaultInstance()) ? null : built; } private Map getSingleUseWriteChannelHintOptions() { @@ -339,17 +346,19 @@ public ServerStream batchWriteAtLeastOnce( throws SpannerException { setActive(null); List mutationGroupsProto = - MutationGroup.toListProto(mutationGroups); + MutationGroup.toListProto(materializeMutationGroups(mutationGroups)); final BatchWriteRequest.Builder requestBuilder = BatchWriteRequest.newBuilder() .setSession(getName()) .addAllMutationGroups(mutationGroupsProto); - RequestOptions batchWriteRequestOptions = getRequestOptions(transactionOptions); Options allOptions = Options.fromTransactionOptions(transactionOptions); + RequestOptions batchWriteRequestOptions = getRequestOptions(allOptions); if (batchWriteRequestOptions != null) { requestBuilder.setRequestOptions(batchWriteRequestOptions); } - if (allOptions.withExcludeTxnFromChangeStreams() == Boolean.TRUE) { + if (allOptions.withExcludeTxnFromChangeStreams() == Boolean.TRUE + || (allOptions.withExcludeTxnFromChangeStreams() == null + && defaultTransactionOptions().getExcludeTxnFromChangeStreams())) { requestBuilder.setExcludeTxnFromChangeStreams(true); } ISpan span = tracer.spanBuilder(SpannerImpl.BATCH_WRITE); diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporter.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporter.java index be1b04f1df07..ebada43cc688 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporter.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporter.java @@ -30,6 +30,7 @@ import com.google.cloud.monitoring.v3.MetricServiceSettings; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.MoreExecutors; import com.google.monitoring.v3.CreateTimeSeriesRequest; @@ -46,6 +47,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -74,9 +76,11 @@ class SpannerCloudMonitoringExporter implements MetricExporter { private final Set spannerExportFailureLoggedProjects = ConcurrentHashMap.newKeySet(); private final MetricServiceClient client; private final Supplier fallbackProjectIdSupplier; + private final Map clientAttributes; static SpannerCloudMonitoringExporter create( Supplier fallbackProjectIdSupplier, + Map clientAttributes, @Nullable Credentials credentials, @Nullable String monitoringHost, String universeDomain) @@ -115,19 +119,30 @@ static SpannerCloudMonitoringExporter create( settingsBuilder.createServiceTimeSeriesSettings().setSimpleTimeoutNoRetriesDuration(timeout); return new SpannerCloudMonitoringExporter( - fallbackProjectIdSupplier, MetricServiceClient.create(settingsBuilder.build())); + fallbackProjectIdSupplier, + clientAttributes, + MetricServiceClient.create(settingsBuilder.build())); } @VisibleForTesting SpannerCloudMonitoringExporter(MetricServiceClient client) { - this(() -> null, client); + this(() -> null, Collections.emptyMap(), client); } @VisibleForTesting SpannerCloudMonitoringExporter( Supplier fallbackProjectIdSupplier, MetricServiceClient client) { + this(fallbackProjectIdSupplier, Collections.emptyMap(), client); + } + + @VisibleForTesting + SpannerCloudMonitoringExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + MetricServiceClient client) { this.client = client; this.fallbackProjectIdSupplier = fallbackProjectIdSupplier; + this.clientAttributes = ImmutableMap.copyOf(clientAttributes); } @Override @@ -156,7 +171,7 @@ private CompletableResultCode exportSpannerClientMetrics(Collection try { spannerTimeSeries = SpannerCloudMonitoringExporterUtils.convertToSpannerTimeSeries( - collection, fallbackProjectIdSupplier.get()); + collection, fallbackProjectIdSupplier.get(), this.clientAttributes); } catch (Throwable e) { logger.log( Level.WARNING, diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterUtils.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterUtils.java index 35ec4bf15ccf..39674c0e9d0c 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterUtils.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterUtils.java @@ -65,6 +65,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; @@ -79,7 +80,9 @@ class SpannerCloudMonitoringExporterUtils { private SpannerCloudMonitoringExporterUtils() {} static List convertToSpannerTimeSeries( - Collection collection, String fallbackProjectId) { + Collection collection, + String fallbackProjectId, + Map clientAttributes) { List allTimeSeries = new ArrayList<>(); for (MetricData metricData : collection) { @@ -109,7 +112,11 @@ static List convertToSpannerTimeSeries( .map( pointData -> convertPointToSpannerTimeSeries( - metricData, pointData, baseMonitoredResource, fallbackProjectId)) + metricData, + pointData, + baseMonitoredResource, + fallbackProjectId, + clientAttributes)) .filter(Objects::nonNull) .forEach(allTimeSeries::add); } @@ -121,7 +128,8 @@ private static TimeSeries convertPointToSpannerTimeSeries( MetricData metricData, PointData pointData, MonitoredResource baseMonitoredResource, - String fallbackProjectId) { + String fallbackProjectId, + Map clientAttributes) { MetricKind metricKind = convertMetricKind(metricData); TimeSeries.Builder builder = TimeSeries.newBuilder() @@ -154,7 +162,7 @@ private static TimeSeries convertPointToSpannerTimeSeries( } // Add common labels like "client_name" and "client_uid" for all the exported metrics. - metricBuilder.putAllLabels(BuiltInMetricsProvider.INSTANCE.createClientAttributes()); + metricBuilder.putAllLabels(clientAttributes); builder.setResource(monitoredResourceBuilder.build()); builder.setMetric(metricBuilder.build()); diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerException.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerException.java index d75fa6a735a8..aaa7fd27cba4 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerException.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerException.java @@ -23,10 +23,8 @@ import com.google.common.base.Strings; import com.google.protobuf.util.Durations; import com.google.rpc.ResourceInfo; -import com.google.rpc.RetryInfo; import io.grpc.Metadata; import io.grpc.Status; -import io.grpc.protobuf.ProtoUtils; import java.util.Map; import javax.annotation.Nullable; @@ -52,8 +50,6 @@ public String getResourceName() { } private static final long serialVersionUID = 20150916L; - private static final Metadata.Key KEY_RETRY_INFO = - ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); private static final String PG_ERR_CODE_KEY = "pg_sqlerrcode"; private final ErrorCode code; @@ -145,23 +141,9 @@ static long extractRetryDelay(Throwable cause) { } static long extractRetryDelay(Throwable cause, @Nullable ApiException apiException) { - ErrorDetails details = SpannerExceptionFactory.extractErrorDetails(cause, apiException); - if (details != null && details.getRetryInfo() != null) { - RetryInfo retryInfo = details.getRetryInfo(); - if (retryInfo.hasRetryDelay()) { - return Durations.toMillis(retryInfo.getRetryDelay()); - } - } - if (cause != null) { - Metadata trailers = Status.trailersFromThrowable(cause); - if (trailers != null && trailers.containsKey(KEY_RETRY_INFO)) { - RetryInfo retryInfo = trailers.get(KEY_RETRY_INFO); - if (retryInfo != null && retryInfo.hasRetryDelay()) { - return Durations.toMillis(retryInfo.getRetryDelay()); - } - } - } - return -1L; + com.google.protobuf.Duration delay = + StreamingRetryHelper.extractRawServerRetryDelay(cause, apiException); + return delay != null ? Durations.toMillis(delay) : -1L; } @Nullable diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java index 755b1acc8290..89a998b5804f 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java @@ -354,6 +354,8 @@ public void close() { } void close(long timeout, TimeUnit unit) { + final long deadlineNanos = + timeout == Long.MAX_VALUE ? 0L : System.nanoTime() + unit.toNanos(Math.max(0L, timeout)); List> closureFutures; synchronized (this) { checkClosed(); @@ -383,6 +385,16 @@ void close(long timeout, TimeUnit unit) { } catch (RuntimeException e) { logger.log(Level.WARNING, "Failed to close channels", e); } + try { + if (timeout == Long.MAX_VALUE) { + getOptions().closeBuiltInMetrics(); + } else { + long remainingNanos = Math.max(0L, deadlineNanos - System.nanoTime()); + getOptions().closeBuiltInMetrics(remainingNanos, TimeUnit.NANOSECONDS); + } + } catch (RuntimeException e) { + logger.log(Level.WARNING, "Failed to close built-in metrics", e); + } } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java index 7d2909f61841..8c6424a7eb15 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java @@ -36,6 +36,8 @@ import com.google.api.gax.tracing.ApiTracerFactory; import com.google.api.gax.tracing.BaseApiTracerFactory; import com.google.api.gax.tracing.OpencensusTracerFactory; +import com.google.auth.ApiKeyCredentials; +import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.NoCredentials; @@ -63,6 +65,7 @@ import com.google.cloud.spanner.v1.SpannerSettings; import com.google.cloud.spanner.v1.stub.SpannerStubSettings; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Ascii; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.base.Strings; @@ -118,7 +121,7 @@ import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jspecify.annotations.Nullable; /** Options for the Cloud Spanner service. */ public class SpannerOptions extends ServiceOptions { @@ -136,6 +139,7 @@ public class SpannerOptions extends ServiceOptions { private static final String API_SHORT_NAME = "Spanner"; private static final String SPANNER_SERVICE_NAME = "spanner"; private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com"; + private static final String GOOGLE_CLOUD_UNIVERSE_DOMAIN_ENV_VAR = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"; private static final int MAX_DNS_HOSTNAME_LENGTH = 253; private static final Pattern VALID_UNIVERSE_DOMAIN_PATTERN = Pattern.compile( @@ -323,7 +327,9 @@ static GcpChannelPoolOptions mergeWithDefaultChannelPoolOptions( private final boolean trackTransactionStarter; private final boolean enableGrpcGcpOtelMetrics; private final boolean enableChannelPoolBuiltInMetrics; - private final BuiltInMetricsProvider builtInMetricsProvider = BuiltInMetricsProvider.INSTANCE; + + // Per-options metrics provider; non-final so tests can inject doubles or observe arguments. + @VisibleForTesting BuiltInMetricsProvider builtInMetricsProvider = new BuiltInMetricsProvider(); /** * These are the default {@link QueryOptions} defined by the user on this {@link SpannerOptions}. @@ -460,8 +466,7 @@ public interface CallContextConfigurator { * ApiCallContext}. If null is returned, no changes to the default {@link * ApiCallContext} will be made. */ - @Nullable - ApiCallContext configure( + @Nullable ApiCallContext configure( ApiCallContext context, ReqT request, MethodDescriptor method); } @@ -509,6 +514,12 @@ boolean isMethod(ReqT request, MethodDescriptor metho return method == SpannerGrpc.getExecuteBatchDmlMethod(); } }, + BATCH_WRITE { + @Override + boolean isMethod(ReqT request, MethodDescriptor method) { + return method == SpannerGrpc.getBatchWriteMethod(); + } + }, PARTITION_QUERY { @Override @@ -578,6 +589,7 @@ public static class SpannerCallContextTimeoutConfigurator implements CallContext private Duration executeQueryTimeout; private Duration executeUpdateTimeout; private Duration batchUpdateTimeout; + private Duration batchWriteTimeout; private Duration readTimeout; private Duration partitionQueryTimeout; @@ -602,6 +614,12 @@ public ApiCallContext configure( return batchUpdateTimeout == null ? null : callContext.withTimeoutDuration(batchUpdateTimeout); + case BATCH_WRITE: + return batchWriteTimeout == null + ? null + : callContext + .withTimeoutDuration(batchWriteTimeout) + .withStreamWaitTimeoutDuration(batchWriteTimeout); case COMMIT: return commitTimeout == null ? null : callContext.withTimeoutDuration(commitTimeout); case EXECUTE_QUERY: @@ -818,6 +836,16 @@ public SpannerCallContextTimeoutConfigurator withPartitionReadTimeoutDuration( this.partitionReadTimeout = partitionReadTimeout; return this; } + + public Duration getBatchWriteTimeoutDuration() { + return batchWriteTimeout; + } + + public SpannerCallContextTimeoutConfigurator withBatchWriteTimeoutDuration( + Duration batchWriteTimeout) { + this.batchWriteTimeout = batchWriteTimeout; + return this; + } } /** Default implementation of {@code SpannerFactory}. */ @@ -990,18 +1018,20 @@ protected SpannerOptions(Builder builder) { databaseRole = builder.databaseRole; sessionLabels = builder.sessionLabels; try { - String resolvedUniversalDomain = getResolvedUniverseDomain(); + // Resolve and validate the universe domain explicitly so validation does not rely solely on + // ServiceOptions eagerly evaluating getDefaultHost(). + String resolvedUniverseDomain = getResolvedUniverseDomain(); spannerStubSettings = - builder.spannerStubSettingsBuilder.setUniverseDomain(resolvedUniversalDomain).build(); + builder.spannerStubSettingsBuilder.setUniverseDomain(resolvedUniverseDomain).build(); instanceAdminStubSettings = builder .instanceAdminStubSettingsBuilder - .setUniverseDomain(resolvedUniversalDomain) + .setUniverseDomain(resolvedUniverseDomain) .build(); databaseAdminStubSettings = builder .databaseAdminStubSettingsBuilder - .setUniverseDomain(resolvedUniversalDomain) + .setUniverseDomain(resolvedUniverseDomain) .build(); } catch (IOException e) { throw SpannerExceptionFactory.newSpannerException(e); @@ -1088,6 +1118,26 @@ protected SpannerOptions(Builder builder) { resolved = NoopMetricsProvider.INSTANCE; } enableBuiltInMetrics = false; + } else if (isEmulatorEnabled()) { + // The emulator has no Cloud Monitoring sink; report GCM as off so isEnableBuiltInMetrics() + // is truthful. + enableBuiltInMetrics = false; + } else if (builder.enableBuiltInMetrics + && !isDefaultUniverseHost(configuredHost) + && isBlank(getUniverseDomain()) + && isBlank(environment.getUniverseDomain()) + && isBlank(builder.monitoringHost)) { + // Fail closed for custom non-default hosts without an explicit metrics target so default-on + // Cloud Monitoring export never leaks credentials or telemetry to monitoring.googleapis.com. + enableBuiltInMetrics = false; + if (!builder.usePlainText) { + logger.log( + Level.WARNING, + "Disabling built-in Cloud Monitoring metrics because custom host {0} is configured" + + " without an explicit universeDomain, GOOGLE_CLOUD_UNIVERSE_DOMAIN, or" + + " monitoringHost.", + configuredHost); + } } else { enableBuiltInMetrics = builder.enableBuiltInMetrics; } @@ -1113,12 +1163,41 @@ protected SpannerOptions(Builder builder) { autoTaggingTracerLimit = builder.autoTaggingTracerLimit; } + /** + * Returns {@code true} if {@code host} is unset (meaning the default endpoint will be used) or is + * a valid URL targeting a subdomain of {@code googleapis.com} (for example, {@code + * https://spanner.googleapis.com}). + * + *

    Returns {@code false} for any custom host, bare {@code googleapis.com}, or URL without a + * valid scheme/hostname (for example, {@code spanner.googleapis.com:443}), so built-in Cloud + * Monitoring export is safely disabled unless a monitoring target is explicitly configured. + */ + private static boolean isDefaultUniverseHost(@Nullable String host) { + if (Strings.isNullOrEmpty(host)) { + return true; + } + try { + String normalized = Ascii.toLowerCase(new URL(host).getHost()); + String defaultUniverseSuffix = "." + GOOGLE_DEFAULT_UNIVERSE; + return normalized.length() > defaultUniverseSuffix.length() + && normalized.endsWith(defaultUniverseSuffix); + } catch (MalformedURLException e) { + return false; + } + } + + /** Returns {@code true} if {@code value} is null or contains only whitespace characters. */ + private static boolean isBlank(@Nullable String value) { + return value == null || value.trim().isEmpty(); + } + /** * Validates that a non-empty universe domain is a valid RFC 1123 DNS domain name so it cannot * inject URL components (such as userinfo, port, path, query, or fragment) into constructed * endpoint URLs. */ - private static void validateUniverseDomain(@Nullable String universeDomain) { + @InternalApi + public static void validateUniverseDomain(@Nullable String universeDomain) { if (Strings.isNullOrEmpty(universeDomain)) { return; } @@ -1129,8 +1208,23 @@ private static void validateUniverseDomain(@Nullable String universeDomain) { universeDomain); } - private String getResolvedUniverseDomain() { - String universeDomain = getUniverseDomain(); + /** + * Resolves the effective universe domain using the precedence: explicit configuration, then + * {@link SpannerEnvironment#getUniverseDomain()} ({@code GOOGLE_CLOUD_UNIVERSE_DOMAIN}), then + * {@code "googleapis.com"}. Validates any non-empty domain against RFC 1123 hostname constraints. + */ + @InternalApi + public static String resolveUniverseDomain(@Nullable String configuredUniverseDomain) { + return resolveUniverseDomain(configuredUniverseDomain, environment.getUniverseDomain()); + } + + @VisibleForTesting + static String resolveUniverseDomain( + @Nullable String configuredUniverseDomain, @Nullable String envUniverseDomain) { + String universeDomain = + !Strings.isNullOrEmpty(configuredUniverseDomain) + ? configuredUniverseDomain + : envUniverseDomain; if (Strings.isNullOrEmpty(universeDomain)) { return GOOGLE_DEFAULT_UNIVERSE; } @@ -1138,6 +1232,29 @@ private String getResolvedUniverseDomain() { return universeDomain; } + @VisibleForTesting + String getResolvedUniverseDomain() { + return resolveUniverseDomain(getUniverseDomain()); + } + + /** + * Validates that the credentials' universe domain matches the resolved universe domain (explicit + * configuration, {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN}, or {@code "googleapis.com"}). Validation + * is skipped for {@link ApiKeyCredentials} because API keys carry no universe domain metadata. + */ + @InternalApi + @Override + public boolean hasValidUniverseDomain() throws IOException { + Credentials credentials = getCredentials(); + // API keys carry no universe domain metadata (mirrors ServiceOptions#hasValidUniverseDomain). + if (credentials instanceof ApiKeyCredentials) { + return true; + } + String credentialsUniverseDomain = + credentials != null ? credentials.getUniverseDomain() : GOOGLE_DEFAULT_UNIVERSE; + return getResolvedUniverseDomain().equals(credentialsUniverseDomain); + } + /** Returns the default {@link RequestOptions.ClientContext} for this {@link SpannerOptions}. */ public RequestOptions.ClientContext getClientContext() { return clientContext; @@ -1229,6 +1346,14 @@ default String getMonitoringHost() { default GoogleCredentials getDefaultSpannerOmniCredentials() { return null; } + + /** + * Returns the universe domain configured in the environment (for example via {@code + * GOOGLE_CLOUD_UNIVERSE_DOMAIN}), or {@code null} if not set. + */ + default @Nullable String getUniverseDomain() { + return null; + } } static final String DEFAULT_SPANNER_OMNI_CREDENTIALS = "SPANNER_OMNI_AUTH_TOKEN"; @@ -1358,6 +1483,11 @@ public String getMonitoringHost() { public GoogleCredentials getDefaultSpannerOmniCredentials() { return getOAuthTokenFromFile(System.getenv(DEFAULT_SPANNER_OMNI_CREDENTIALS)); } + + @Override + public @Nullable String getUniverseDomain() { + return System.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN_ENV_VAR); + } } /** Builder for {@link SpannerOptions} instances. */ @@ -2964,7 +3094,8 @@ private boolean usesNoCredentials() { && System.getProperty("jmh.enabled").equals("true")) { return false; } - return Objects.equals(getCredentials(), NoCredentials.getInstance()); + Credentials credentials = getCredentials(); + return credentials == null || credentials instanceof NoCredentials; } public String getCompressorName() { @@ -3021,11 +3152,19 @@ public ApiTracerFactory getApiTracerFactory() { return createApiTracerFactory(false, false); } - /** Returns the internal OpenTelemetry instance used for built-in metrics. */ + /** + * Returns the internal OpenTelemetry instance used for built-in metrics, or {@code null} when + * Cloud Monitoring built-in metrics are disabled, no credentials are configured, or it could not + * be initialized. + */ @InternalApi + @Nullable public OpenTelemetry getBuiltInOpenTelemetry() { + if (!isEnableBuiltInMetrics() || usesNoCredentials()) { + return null; + } return this.builtInMetricsProvider.getOrCreateOpenTelemetry( - this.getProjectId(), getCredentials(), this.monitoringHost, getUniverseDomain()); + this.getProjectId(), getCredentials(), this.monitoringHost, getResolvedUniverseDomain()); } /** @@ -3043,10 +3182,10 @@ public void enablegRPCMetrics(InstantiatingGrpcChannelProvider.Builder channelPr /** * Wires gRPC-layer built-in metrics into the given channel provider builder for each active - * metrics sink: the Cloud Monitoring (GCM) sink when {@link #isEnableBuiltInMetrics()} is true, - * and the caller-owned OpenTelemetry sink when a {@link CustomOpenTelemetryMetricsProvider} is - * configured. Does nothing when {@code isEmulatorEnabled} is true or gRPC built-in metrics are - * disabled via the environment. + * metrics sink: the Cloud Monitoring (GCM) sink when {@link #isEnableBuiltInMetrics()} is true + * and credentials are configured, and the caller-owned OpenTelemetry sink when a {@link + * CustomOpenTelemetryMetricsProvider} is configured. Does nothing when {@code isEmulatorEnabled} + * is true or gRPC built-in metrics are disabled via the environment. */ @InternalApi public void enablegRPCMetrics( @@ -3059,13 +3198,13 @@ public void enablegRPCMetrics( // records each instrument once per GrpcOpenTelemetry instance, so wiring two instances onto one // channel does not double-count attempt/operation metrics (verified by // GrpcMetricsDualWireTest). - if (isEnableBuiltInMetrics()) { + if (isEnableBuiltInMetrics() && !usesNoCredentials()) { this.builtInMetricsProvider.enableGrpcMetrics( channelProviderBuilder, this.getProjectId(), getCredentials(), this.monitoringHost, - getUniverseDomain()); + getResolvedUniverseDomain()); } if (usesCustomMetricsProvider()) { OpenTelemetry customOpenTelemetry = @@ -3088,6 +3227,16 @@ void initializeBuiltInMetrics(DatabaseId databaseId) { } } + /** Closes the built-in metrics provider with the default bounded shutdown timeout. */ + void closeBuiltInMetrics() { + this.builtInMetricsProvider.close(); + } + + /** Closes the built-in metrics provider, waiting at most {@code timeout} for the final flush. */ + void closeBuiltInMetrics(long timeout, TimeUnit unit) { + this.builtInMetricsProvider.close(timeout, unit); + } + public ApiTracerFactory getApiTracerFactory(boolean isAdminClient, boolean isEmulatorEnabled) { return createApiTracerFactory(isAdminClient, isEmulatorEnabled); } @@ -3139,9 +3288,8 @@ private ApiTracerFactory getDefaultApiTracerFactory() { /** * Records client metrics on the caller-provided OpenTelemetry with the custom-export namespace. - * This deliberately does not touch the process-wide BuiltInMetricsProvider singleton, so a client - * with a client-metrics sink can coexist with clients that export to Cloud Monitoring in the same - * JVM. + * Only reads this client's {@code client_name}/{@code client_uid} from its own {@link + * BuiltInMetricsProvider}, so it never creates the Cloud Monitoring exporter. */ private ApiTracerFactory createCustomMetricsTracerFactory() { OpenTelemetry customOpenTelemetry = @@ -3157,14 +3305,17 @@ private ApiTracerFactory createCustomMetricsTracerFactory() { } /** - * Records built-in metrics on the process-wide Cloud Monitoring OpenTelemetry with the reserved - * {@code spanner.googleapis.com} namespace. Returns {@code null} when the Cloud Monitoring - * OpenTelemetry could not be created. + * Records built-in metrics on this client's Cloud Monitoring OpenTelemetry (owned by its {@link + * BuiltInMetricsProvider}) with the reserved {@code spanner.googleapis.com} namespace. Returns + * {@code null} when the Cloud Monitoring OpenTelemetry could not be created. */ private ApiTracerFactory createCloudMonitoringMetricsTracerFactory() { OpenTelemetry openTelemetry = this.builtInMetricsProvider.getOrCreateOpenTelemetry( - this.getProjectId(), getCredentials(), this.monitoringHost, getUniverseDomain()); + this.getProjectId(), + getCredentials(), + this.monitoringHost, + getResolvedUniverseDomain()); return openTelemetry != null ? new BuiltInMetricsTracerFactory( @@ -3196,9 +3347,13 @@ public boolean isEnableApiTracing() { /** * Returns true if built-in metrics are exported to the default Cloud Monitoring (GCM) - * destination. Always false for {@link InstanceType#OMNI} clients, where the GCM sink is - * unavailable. This flag does not affect a caller-owned client-metrics destination configured - * with {@link Builder#setClientMetricsProvider(MetricsProvider)}. + * destination. Always false for {@link InstanceType#OMNI} clients and when the emulator is + * enabled, where the GCM sink is unavailable, and automatically disabled when a custom non-{@code + * *.googleapis.com} host (including a scheme-less host) is configured via {@link + * Builder#setHost(String)} without an explicit {@code universeDomain}, {@code + * GOOGLE_CLOUD_UNIVERSE_DOMAIN}, or {@code monitoringHost}. This flag does not affect a + * caller-owned client-metrics destination configured with {@link + * Builder#setClientMetricsProvider(MetricsProvider)}. */ public boolean isEnableBuiltInMetrics() { return enableBuiltInMetrics; diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/StreamingRetryHelper.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/StreamingRetryHelper.java new file mode 100644 index 000000000000..33b1fd2b79f8 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/StreamingRetryHelper.java @@ -0,0 +1,261 @@ +/* + * 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 com.google.api.core.InternalApi; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ErrorDetails; +import com.google.api.gax.rpc.ProtocolBufferParsingException; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.protobuf.util.Durations; +import com.google.rpc.RetryInfo; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; +import java.time.Duration; +import java.util.function.DoubleSupplier; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +/** + * Shared internal retry delay sanitization, exponential backoff, and budget enforcement utilities + * for Cloud Spanner streaming RPCs. + */ +@InternalApi +@NullMarked +public final class StreamingRetryHelper { + + /** Default upper bound for retry delays when {@code maxRetryDelayDuration} is unset. */ + static final Duration DEFAULT_MAX_RETRY_DELAY = Duration.ofSeconds(32L); + + private static final Metadata.Key KEY_RETRY_INFO = + ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + + private StreamingRetryHelper() {} + + /** + * Returns {@code true} if {@code completedAttempts} has reached or exceeded {@link + * RetrySettings#getMaxAttempts()} when a positive attempt limit is configured. A configured + * {@code maxAttempts} of zero means unlimited retries (GAX convention); {@code 1} disables + * retries. + */ + public static boolean isMaxAttemptsExhausted(RetrySettings retrySettings, int completedAttempts) { + Preconditions.checkNotNull(retrySettings, "retrySettings must not be null"); + int maxAttempts = retrySettings.getMaxAttempts(); + return maxAttempts > 0 && completedAttempts >= maxAttempts; + } + + /** + * Returns {@code true} if retrying after {@code proposedDelay} would reach or exceed {@link + * RetrySettings#getTotalTimeoutDuration()} given {@code elapsedNanos} since the retry sequence + * started. A non-positive total timeout means no total timeout is enforced. + */ + public static boolean isTotalTimeoutExceeded( + RetrySettings retrySettings, long elapsedNanos, @Nullable Duration proposedDelay) { + Preconditions.checkNotNull(retrySettings, "retrySettings must not be null"); + Duration totalTimeout = retrySettings.getTotalTimeoutDuration(); + if (!isPositive(totalTimeout)) { + return false; + } + Duration elapsed = Duration.ofNanos(Math.max(0L, elapsedNanos)); + if (elapsed.compareTo(totalTimeout) >= 0) { + return true; + } + Duration effectiveDelay = + proposedDelay != null && !proposedDelay.isNegative() ? proposedDelay : Duration.ZERO; + return totalTimeout.minus(elapsed).compareTo(effectiveDelay) <= 0; + } + + /** + * Extracts a validated protobuf {@link com.google.protobuf.Duration} from {@code RetryInfo} + * attached to {@code error} or {@code apiException}, returning {@code null} when absent or + * malformed. + * + *

    Uses two independent exception-guarded lookups so that malformed {@code ErrorDetails} + * (including corrupt {@code Any} payloads inside {@code grpc-status-details-bin}) still falls + * through to a valid {@code google.rpc.retryinfo-bin} trailer. + */ + static com.google.protobuf.@Nullable Duration extractRawServerRetryDelay( + @Nullable Throwable error, @Nullable ApiException apiException) { + try { + ErrorDetails details = SpannerExceptionFactory.extractErrorDetails(error, apiException); + if (details != null) { + com.google.protobuf.Duration protoDelay = + extractValidatedProtoDelay(details.getRetryInfo()); + if (protoDelay != null) { + return protoDelay; + } + } + } catch (ProtocolBufferParsingException + | IllegalArgumentException + | ArithmeticException ignored) { + // Fall through to raw gRPC trailers if ErrorDetails is malformed or out of range. + } + + if (error == null) { + return null; + } + try { + Metadata trailers = Status.trailersFromThrowable(error); + if (trailers != null) { + com.google.protobuf.Duration protoDelay = + extractValidatedProtoDelay(trailers.get(KEY_RETRY_INFO)); + if (protoDelay != null) { + return protoDelay; + } + } + } catch (IllegalArgumentException | ArithmeticException ignored) { + // Ignore corrupted or out-of-range RetryInfo trailers. + } + return null; + } + + /** + * Extracts any positive server-supplied retry delay ({@code > 0}) from {@code error}, returning + * {@code null} when absent, malformed, zero, or negative. + */ + @VisibleForTesting + public static @Nullable Duration extractServerRetryDelay(@Nullable Throwable error) { + com.google.protobuf.Duration rawDelay = extractRawServerRetryDelay(error, null); + if (rawDelay != null + && (rawDelay.getSeconds() > 0L + || (rawDelay.getSeconds() == 0L && rawDelay.getNanos() > 0))) { + return Duration.ofSeconds(rawDelay.getSeconds(), rawDelay.getNanos()); + } + return null; + } + + /** + * Returns the effective upper bound for retry delays: {@link + * RetrySettings#getMaxRetryDelayDuration()} when positive, or {@link #DEFAULT_MAX_RETRY_DELAY} + * otherwise, floored at {@code minDelay}. + */ + static Duration effectiveMaxRetryDelay(RetrySettings retrySettings, Duration minDelay) { + Preconditions.checkNotNull(retrySettings, "retrySettings must not be null"); + Preconditions.checkNotNull(minDelay, "minDelay must not be null"); + Preconditions.checkArgument(!minDelay.isNegative(), "minDelay must not be negative"); + Duration configuredMax = retrySettings.getMaxRetryDelayDuration(); + Duration maxDelay = isPositive(configuredMax) ? configuredMax : DEFAULT_MAX_RETRY_DELAY; + return maxDelay.compareTo(minDelay) < 0 ? minDelay : maxDelay; + } + + /** + * Computes the next retry delay by clamping any positive server-supplied {@code RetryInfo} delay + * to {@code [minDelay, effectiveMaxRetryDelay]}, or falling back to stateless exponential backoff + * with {@code [0.5x, 1.0x]} full-band jitter. + * + *

    When {@code initialRetryDelayDuration} is non-positive, returns {@link Duration#ZERO} if + * {@code minDelay} is zero (preserving explicit zero-delay configurations), or uses {@code + * minDelay} as the initial interval otherwise so millisecond-sleeping callers cannot busy-spin. + */ + public static Duration computeRetryDelay( + RetrySettings retrySettings, + @Nullable Throwable error, + int completedAttempts, + DoubleSupplier jitterRandom, + Duration minDelay) { + Preconditions.checkNotNull(jitterRandom, "jitterRandom must not be null"); + Duration effectiveMaxDelay = effectiveMaxRetryDelay(retrySettings, minDelay); + Duration serverRetryDelay = extractServerRetryDelay(error); + if (serverRetryDelay != null) { + if (serverRetryDelay.compareTo(minDelay) < 0) { + return minDelay; + } + return serverRetryDelay.compareTo(effectiveMaxDelay) > 0 + ? effectiveMaxDelay + : serverRetryDelay; + } + + Duration initialDelay = retrySettings.getInitialRetryDelayDuration(); + if (!isPositive(initialDelay)) { + if (minDelay.isZero()) { + return Duration.ZERO; + } + initialDelay = minDelay; + } else if (initialDelay.compareTo(minDelay) < 0) { + initialDelay = minDelay; + } + + double initialNanos = toNanosDouble(initialDelay); + double maxNanos = toNanosDouble(effectiveMaxDelay); + double multiplier = Math.max(1.0, retrySettings.getRetryDelayMultiplier()); + + double unclamped = initialNanos * Math.pow(multiplier, Math.max(0, completedAttempts - 1)); + double capped = Math.min(maxNanos, unclamped); + // Apply jitter in [0.5, 1.0] of the capped delay so retries spread out + // without ever exceeding effectiveMaxDelay. + double rawRandom = jitterRandom.getAsDouble(); + double clampedRandom = + Double.isFinite(rawRandom) ? Math.min(1.0, Math.max(0.0, rawRandom)) : 1.0; + double jitterFactor = 0.5 + (0.5 * clampedRandom); + Duration backoffDelay = fromNanosDouble(capped * jitterFactor); + return backoffDelay.compareTo(minDelay) < 0 ? minDelay : backoffDelay; + } + + /** + * Converts {@code duration} to positive milliseconds (floored at 1ms for positive sub-millisecond + * durations and saturated at {@code maxMillis} on overflow), or returns {@code + * nonPositiveDefaultMillis} when {@code duration} is null, zero, or negative. + */ + public static long saturatedDurationMillis( + @Nullable Duration duration, long nonPositiveDefaultMillis, long maxMillis) { + if (!isPositive(duration)) { + return nonPositiveDefaultMillis; + } + try { + return Math.max(1L, Math.min(duration.toMillis(), maxMillis)); + } catch (ArithmeticException overflow) { + return maxMillis; + } + } + + /** Converts {@code duration} to nanoseconds, saturating to {@code Long.MIN_VALUE}/{@code MAX}. */ + public static long toSaturatedNanos(Duration duration) { + try { + return duration.toNanos(); + } catch (ArithmeticException overflow) { + return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE; + } + } + + private static com.google.protobuf.@Nullable Duration extractValidatedProtoDelay( + @Nullable RetryInfo retryInfo) { + if (retryInfo != null && retryInfo.hasRetryDelay()) { + com.google.protobuf.Duration protoDelay = retryInfo.getRetryDelay(); + Durations.checkValid(protoDelay); + return protoDelay; + } + return null; + } + + private static boolean isPositive(@Nullable Duration duration) { + return duration != null && !duration.isZero() && !duration.isNegative(); + } + + private static double toNanosDouble(Duration duration) { + return (duration.getSeconds() * 1_000_000_000.0) + duration.getNano(); + } + + private static Duration fromNanosDouble(double nanos) { + if (nanos >= (double) Long.MAX_VALUE) { + return Duration.ofNanos(Long.MAX_VALUE); + } + return Duration.ofNanos((long) nanos); + } +} diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverter.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverter.java index 1cd04433abcc..b5fe356bfa63 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverter.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverter.java @@ -32,4 +32,12 @@ interface ClientSideStatementValueConverter { * converted. */ T convert(String value); + + /** + * Returns {@code true} if the given non-null typed value is valid for properties using this + * converter. + */ + default boolean isValid(T value) { + return true; + } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverters.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverters.java index 7735623191d5..1e6c8caac3f7 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverters.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ClientSideStatementValueConverters.java @@ -180,6 +180,11 @@ public Integer convert(String value) { return null; } } + + @Override + public boolean isValid(Integer value) { + return value != null && value >= 0; + } } /** Converter from string to a long. */ @@ -209,6 +214,12 @@ public Long convert(String value) { return null; } } + + @Override + public boolean isValid(Long value) { + // Match convert(String), which only accepts non-negative values. + return value != null && value >= 0; + } } /** Converter from string to {@link Duration}. */ @@ -265,6 +276,12 @@ public Duration convert(String value) { } return null; } + + @Override + public boolean isValid(Duration value) { + // Match convert(String), which only accepts non-negative durations. + return value != null && !value.isNegative(); + } } /** Converter from string to {@link Duration}. */ diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionOptions.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionOptions.java index efde0d178296..6962f2f659ed 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionOptions.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionOptions.java @@ -90,6 +90,7 @@ import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.cloud.spanner.SpannerOptions; +import com.google.cloud.spanner.connection.ConnectionProperty.Context; import com.google.cloud.spanner.connection.StatementExecutor.StatementExecutorType; import com.google.cloud.spanner.omni.SpannerOmniCredentials; import com.google.common.annotations.VisibleForTesting; @@ -107,13 +108,17 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -215,11 +220,6 @@ public class ConnectionOptions { private static final String PLAIN_TEXT_PROTOCOL = "http:"; private static final String HOST_PROTOCOL = "https:"; private static final String SPANNER_SERVICE_NAME = "spanner"; - private static final int MAX_DNS_HOSTNAME_LENGTH = 253; - private static final Pattern VALID_UNIVERSE_DOMAIN_PATTERN = - Pattern.compile( - "^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?" - + "(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"); private static final String SPANNER_EMULATOR_HOST_ENV_VAR = "SPANNER_EMULATOR_HOST"; private static final String DEFAULT_EMULATOR_HOST = "http://localhost:9010"; @@ -451,6 +451,31 @@ public static void closeSpanner() { SpannerPool.INSTANCE.checkAndCloseSpanners(); } + /** + * Policy controlling how {@link Context#STARTUP} properties found in the connection URI string + * are handled. + * + *

    This policy governs property key/value parameters in the connection URI (for example {@code + * ?endpoint=...;minSessions=...}). It does not restrict the URI host authority ({@code //host}), + * Omni URI format, or {@code /projects/} path. Callers accepting full untrusted URIs should + * validate or construct those URI components separately. + * + *

    This policy can only be configured programmatically via {@link Builder}; it is never parsed + * from the connection URI string itself. + */ + public enum StartupPropertyPolicy { + /** Allow {@link Context#STARTUP} properties in the connection URI. */ + ALLOW, + /** + * Reject {@link Context#STARTUP} properties in the connection URI by throwing a {@link + * SpannerException} with {@link ErrorCode#INVALID_ARGUMENT}. Applications that accept + * connection URIs from untrusted sources should set this policy to {@code REJECT} so callers + * cannot modify {@link Context#STARTUP} settings such as endpoints, credentials, or session + * pool configuration via the URI. + */ + REJECT, + } + /** * {@link SpannerOptionsConfigurator} can be used to add additional configuration for a {@link * Spanner} instance. Intended for tests. @@ -482,12 +507,13 @@ public static class Builder { private SpannerOptionsConfigurator configurator; private OpenTelemetry openTelemetry; private Ticker ticker = Deadline.getSystemTicker(); + private StartupPropertyPolicy startupPropertyPolicy = StartupPropertyPolicy.ALLOW; private Builder() {} /** Spanner {@link ConnectionOptions} URI format. */ public static final String SPANNER_URI_FORMAT = - "(?:(?:spanner|cloudspanner):)(?//[\\w.-]+(?:\\.[\\w\\.-]+)*[\\w\\-\\._~:/?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=.]+)?/projects/(?(([a-z]|[-.:]|[0-9])+|(DEFAULT_PROJECT_ID)))(/instances/(?([a-z]|[-]|[0-9])+)(/databases/(?([a-z]|[-]|[_]|[0-9])+))?)?(?:[?|;].*)?"; + "(?:(?:spanner|cloudspanner):)(?//(?:[\\w.-]+|\\[[0-9a-fA-F:]+\\])(?::\\d+)?)?/projects/(?(([a-z]|[-.:]|[0-9])+|(DEFAULT_PROJECT_ID)))(/instances/(?([a-z]|[-]|[0-9])+)(/databases/(?([a-z]|[-]|[_]|[0-9])+))?)?(?:[?;].*)?"; public static final String EXTERNAL_HOST_FORMAT = "(?:(?:spanner|cloudspanner):)(?//[\\w.-]+(?::\\d+)?)(/instances/(?[a-z0-9-]+))?(/databases/(?[a-z0-9_-]+))(?:[?;].*)?"; @@ -569,6 +595,10 @@ private boolean isValidSpannerOmniUri(String uri) { * or any region (false) in read/write transactions and Partitioned DML. Default is true. * * + *

    When {@link StartupPropertyPolicy#REJECT} is configured on this {@link Builder}, {@link + * Context#STARTUP} properties in the URI property string are rejected with {@link + * ErrorCode#INVALID_ARGUMENT}. + * * @param uri The URI of the Spanner database to connect to. * @return this builder */ @@ -580,20 +610,62 @@ public Builder setUri(String uri) { + " the format" + " \"cloudspanner:[//host[:port]]/projects/project-id[/instances/instance-id[/databases/database-name]][\\?property-name=property-value[;property-name=property-value]*]?\""); } - ConnectionPropertyValue value = - cast(ConnectionProperties.parseValues(uri).get(LENIENT.getKey())); - checkValidProperties(value != null && value.getValue(), uri); + ParsedUriProperties parsedProperties = parseUriProperties(uri); + checkValidProperties( + isLenient(parsedProperties), parsedProperties, this.startupPropertyPolicy); + ConnectionProperties.validateValues(parsedProperties); this.uri = uri; return this; } - Builder setConnectionPropertyValue( - com.google.cloud.spanner.connection.ConnectionProperty property, T value) { - this.connectionPropertyValues.put( - property.getKey(), new ConnectionPropertyValue<>(property, value, value)); + private boolean isLenient(ParsedUriProperties parsedProperties) { + ConnectionPropertyValue value = + cast(this.connectionPropertyValues.get(LENIENT.getKey())); + if (value != null) { + return Boolean.TRUE.equals(value.getValue()); + } + if (this.startupPropertyPolicy == StartupPropertyPolicy.ALLOW) { + ConnectionPropertyValue uriLenient = + LENIENT.convert(parsedProperties.getValue(LENIENT.getKey())); + return uriLenient != null && Boolean.TRUE.equals(uriLenient.getValue()); + } + return false; + } + + /** + * Sets the {@link StartupPropertyPolicy} controlling how {@link Context#STARTUP} properties in + * the connection URI string are handled. Defaults to {@link StartupPropertyPolicy#ALLOW}. + * + *

    Applications that accept connection URIs from untrusted sources should set this to {@link + * StartupPropertyPolicy#REJECT} so callers cannot modify {@link Context#STARTUP} settings such + * as endpoints, credentials, or session pool configuration via the URI. + */ + public Builder setStartupPropertyPolicy(StartupPropertyPolicy startupPropertyPolicy) { + this.startupPropertyPolicy = + Preconditions.checkNotNull( + startupPropertyPolicy, "startupPropertyPolicy must not be null"); return this; } + StartupPropertyPolicy getStartupPropertyPolicy() { + return this.startupPropertyPolicy; + } + + /** + * Programmatically sets a {@link ConnectionPropertyValue}. All {@link + * ConnectionProperties#VALID_CONNECTION_PROPERTIES} are allowed when set programmatically, and + * take precedence over properties parsed from the connection URI. + */ + public Builder setConnectionPropertyValue(ConnectionPropertyValue value) { + Preconditions.checkNotNull(value, "value must not be null"); + this.connectionPropertyValues.put(value.getProperty().getKey(), value.copy()); + return this; + } + + Builder setConnectionPropertyValue(ConnectionProperty property, T value) { + return setConnectionPropertyValue(ConnectionPropertyValue.of(property, value)); + } + /** Sets the {@link SessionPoolOptions} to use for the connection. */ public Builder setSessionPoolOptions(SessionPoolOptions sessionPoolOptions) { Preconditions.checkNotNull(sessionPoolOptions); @@ -743,17 +815,21 @@ private ConnectionOptions(Builder builder) { Preconditions.checkArgument( matcher.find(), String.format("Invalid connection URI specified: %s", builder.uri)); + ParsedUriProperties parsedProperties = parseUriProperties(builder.uri); + this.warnings = + checkValidProperties( + builder.isLenient(parsedProperties), parsedProperties, builder.startupPropertyPolicy); + ImmutableMap> urlPropertyValues = + ConnectionProperties.parseValues(parsedProperties); ImmutableMap> connectionPropertyValues = ImmutableMap.>builder() - .putAll(ConnectionProperties.parseValues(builder.uri)) + .putAll(urlPropertyValues) .putAll(builder.connectionPropertyValues) .buildKeepingLast(); this.uri = builder.uri; this.typeExplicitlySet = - ConnectionProperties.parseValues(builder.uri).containsKey(TYPE_PROPERTY_NAME) + urlPropertyValues.containsKey(TYPE.getKey()) || builder.connectionPropertyValues.containsKey(TYPE.getKey()); - ConnectionPropertyValue value = cast(connectionPropertyValues.get(LENIENT.getKey())); - this.warnings = checkValidProperties(value != null && value.getValue(), uri); this.fixedCredentials = builder.credentials; this.statementExecutorType = builder.statementExecutorType; @@ -765,7 +841,9 @@ private ConnectionOptions(Builder builder) { // Create the initial connection state from the parsed properties in the connection URL. this.initialConnectionState = new ConnectionState(connectionPropertyValues); - validateUniverseDomain(getUniverseDomain()); + // Validate the effective universe domain (explicit property or GOOGLE_CLOUD_UNIVERSE_DOMAIN) + // eagerly so malformed values fail closed during construction, even with a custom host. + SpannerOptions.resolveUniverseDomain(getUniverseDomain()); checkGuardedProperty( getInitialConnectionPropertyValue(ENCODED_CREDENTIALS), @@ -998,52 +1076,152 @@ private static void checkGuardedProperty( } } + static final class ParsedUriProperties { + private static final ParsedUriProperties EMPTY = + new ParsedUriProperties(Collections.emptyList(), Collections.emptyMap()); + + private final List> tokens; + private final Map propertyValues; + + private ParsedUriProperties( + List> tokens, Map propertyValues) { + this.tokens = tokens; + this.propertyValues = propertyValues; + } + + List> getTokens() { + return tokens; + } + + Map getPropertyValues() { + return propertyValues; + } + + @Nullable + String getValue(String property) { + return propertyValues.get(property.toLowerCase(Locale.ENGLISH)); + } + } + + static ParsedUriProperties parseUriProperties(String uri) { + if (Strings.isNullOrEmpty(uri)) { + return ParsedUriProperties.EMPTY; + } + int startIndex = findNextPropertyDelimiterIndex(uri, 0); + if (startIndex < 0 || startIndex + 1 >= uri.length()) { + return ParsedUriProperties.EMPTY; + } + List> tokens = new ArrayList<>(); + Map values = new LinkedHashMap<>(); + int index = startIndex + 1; + int length = uri.length(); + while (index < length) { + int end = findNextPropertyDelimiterIndex(uri, index); + if (end < 0) { + end = length; + } + if (end > index) { + parsePropertyToken(uri.substring(index, end), tokens, values); + } + index = end + 1; + } + return new ParsedUriProperties( + Collections.unmodifiableList(tokens), Collections.unmodifiableMap(values)); + } + + private static void parsePropertyToken( + String token, List> tokens, Map values) { + int equalsIndex = token.indexOf('='); + if (equalsIndex <= 0) { + // Malformed token (no '=' or empty key): surface as an invalid token during validation. + tokens.add(new SimpleImmutableEntry<>(token, null)); + return; + } + String rawName = token.substring(0, equalsIndex); + String rawValue = token.substring(equalsIndex + 1); + tokens.add(new SimpleImmutableEntry<>(rawName, rawValue)); + values.putIfAbsent(rawName.toLowerCase(Locale.ENGLISH), rawValue); + } + + private static int findNextPropertyDelimiterIndex(String uri, int fromIndex) { + for (int i = fromIndex; i < uri.length(); i++) { + char currentChar = uri.charAt(i); + if (currentChar == '?' || currentChar == ';') { + return i; + } + } + return -1; + } + @VisibleForTesting static String parseUriProperty(String uri, String property) { - Pattern pattern = Pattern.compile(String.format("(?is)(?:;|\\?)%s=(.*?)(?:;|$)", property)); - Matcher matcher = pattern.matcher(uri); - if (matcher.find() && matcher.groupCount() == 1) { - return matcher.group(1); - } - return null; + return parseUriProperties(uri).getValue(property); } /** Check that only valid properties have been specified. */ @VisibleForTesting static String checkValidProperties(boolean lenient, String uri) { - StringBuilder invalidProperties = new StringBuilder(); - List properties = parseProperties(uri); - for (String property : properties) { - if (!ConnectionProperties.CONNECTION_PROPERTIES.containsKey( - property.toLowerCase(Locale.ENGLISH))) { - if (invalidProperties.length() > 0) { + return checkValidProperties(lenient, uri, StartupPropertyPolicy.ALLOW); + } + + static String checkValidProperties( + boolean lenient, String uri, StartupPropertyPolicy startupPropertyPolicy) { + return checkValidProperties(lenient, parseUriProperties(uri), startupPropertyPolicy); + } + + static String checkValidProperties( + boolean lenient, + ParsedUriProperties parsedProperties, + StartupPropertyPolicy startupPropertyPolicy) { + Set startupPropertiesInUri = null; + StringBuilder invalidProperties = null; + for (Map.Entry token : parsedProperties.getTokens()) { + String property = token.getKey(); + ConnectionProperty connectionProperty = + token.getValue() == null + ? null + : ConnectionProperties.CONNECTION_PROPERTIES.get( + property.toLowerCase(Locale.ENGLISH)); + if (connectionProperty == null) { + if (invalidProperties == null) { + invalidProperties = new StringBuilder(); + } else { invalidProperties.append(", "); } invalidProperties.append(property); + } else if (startupPropertyPolicy == StartupPropertyPolicy.REJECT + && connectionProperty.getContext() == Context.STARTUP) { + if (startupPropertiesInUri == null) { + startupPropertiesInUri = new LinkedHashSet<>(); + } + startupPropertiesInUri.add(property); } } - if (lenient) { - return String.format("Invalid properties found in connection URI: %s", invalidProperties); - } else { - Preconditions.checkArgument( - invalidProperties.length() == 0, - String.format( - "Invalid properties found in connection URI. Add lenient=true to the connection" - + " string to ignore unknown properties. Invalid properties: %s", - invalidProperties)); + if (startupPropertiesInUri != null) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.INVALID_ARGUMENT, + "Startup properties are not allowed in connection URI: " + + String.join(", ", startupPropertiesInUri)); + } + if (invalidProperties == null) { return null; } + Preconditions.checkArgument( + lenient, + "Invalid properties found in connection URI. Add lenient=true to the connection" + + " string to ignore unknown properties. Invalid properties: %s", + invalidProperties); + return String.format("Invalid properties found in connection URI: %s", invalidProperties); } @VisibleForTesting static List parseProperties(String uri) { - Pattern pattern = Pattern.compile("(?is)(?:\\?|;)(?.*?)=(?:.*?)"); - Matcher matcher = pattern.matcher(uri); - List res = new ArrayList<>(); - while (matcher.find() && matcher.group("PROPERTY") != null) { - res.add(matcher.group("PROPERTY")); + List> tokens = parseUriProperties(uri).getTokens(); + List names = new ArrayList<>(tokens.size()); + for (Map.Entry token : tokens) { + names.add(token.getKey()); } - return res; + return names; } static long tryParseLong(String value, long defaultValue) { @@ -1190,33 +1368,13 @@ public Integer getDcpConcurrentStreamsLowWatermark() { return getInitialConnectionPropertyValue(DCP_CONCURRENT_STREAMS_LOW_WATERMARK); } - /** - * Validates that a non-empty universe domain is a valid RFC 1123 DNS domain name so it cannot - * inject URL components (such as userinfo, port, path, query, or fragment) into constructed - * endpoint URLs. - */ - private static void validateUniverseDomain(@Nullable String universeDomain) { - if (Strings.isNullOrEmpty(universeDomain)) { - return; - } - Preconditions.checkArgument( - SPANNER_SERVICE_NAME.length() + 1 + universeDomain.length() <= MAX_DNS_HOSTNAME_LENGTH - && VALID_UNIVERSE_DOMAIN_PATTERN.matcher(universeDomain).matches(), - "Invalid universe domain: %s", - universeDomain); - } - /** * Returns the default host URL derived from the configured universe domain, falling back to - * {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} when null or empty. + * {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} and then {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} when + * null or empty. */ private String getDefaultHost() { - String universeDomain = getUniverseDomain(); - if (Strings.isNullOrEmpty(universeDomain)) { - universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; - } else { - validateUniverseDomain(universeDomain); - } + String universeDomain = SpannerOptions.resolveUniverseDomain(getUniverseDomain()); return String.format("%s//%s.%s", HOST_PROTOCOL, SPANNER_SERVICE_NAME, universeDomain); } @@ -1372,8 +1530,13 @@ Boolean isEnableDirectAccess() { return getInitialConnectionPropertyValue(ENABLE_DIRECT_ACCESS); } + /** + * Returns the explicitly configured universe domain, normalizing an empty string to {@code null} + * so omitted and empty values are treated identically across callers and connection pooling. + */ + @Nullable String getUniverseDomain() { - return getInitialConnectionPropertyValue(UNIVERSE_DOMAIN); + return Strings.emptyToNull(getInitialConnectionPropertyValue(UNIVERSE_DOMAIN)); } String getClientCertificate() { diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperties.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperties.java index 051ba62a2aa9..d917669a3ddb 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperties.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperties.java @@ -124,8 +124,8 @@ import static com.google.cloud.spanner.connection.ConnectionOptions.USE_PLAIN_TEXT_PROPERTY_NAME; import static com.google.cloud.spanner.connection.ConnectionOptions.USE_VIRTUAL_GRPC_TRANSPORT_THREADS_PROPERTY_NAME; import static com.google.cloud.spanner.connection.ConnectionOptions.USE_VIRTUAL_THREADS_PROPERTY_NAME; -import static com.google.cloud.spanner.connection.ConnectionProperty.castProperty; +import com.google.api.core.InternalApi; import com.google.api.core.ObsoleteApi; import com.google.api.gax.grpc.GrpcInterceptorProvider; import com.google.cloud.spanner.Dialect; @@ -157,9 +157,12 @@ import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; import java.time.Duration; import java.util.Arrays; +import java.util.Map; import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; /** Utility class that defines all known connection properties. */ +@InternalApi public class ConnectionProperties { private static final ImmutableMap.Builder> CONNECTION_PROPERTIES_BUILDER = ImmutableMap.builder(); @@ -167,7 +170,7 @@ public class ConnectionProperties { private static final Boolean[] BOOLEANS = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; static final ConnectionProperty CONNECTION_STATE_TYPE = - create( + createNullable( "connection_state_type", "The type of connection state to use for this connection. Can only be set at start up. " + "If no value is set, then the database dialect default will be used, " @@ -176,24 +179,24 @@ public class ConnectionProperties { ConnectionState.Type.values(), ConnectionStateTypeConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty TRACING_PREFIX = - create( + public static final ConnectionProperty TRACING_PREFIX = + createNonNull( "tracing_prefix", "The prefix that will be prepended to all OpenTelemetry traces that are " + "generated by a Connection.", "CloudSpanner", StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty LENIENT = - create( + public static final ConnectionProperty LENIENT = + createNonNull( LENIENT_PROPERTY_NAME, "Silently ignore unknown properties in the connection string/properties (true/false)", DEFAULT_LENIENT, BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENDPOINT = - create( + public static final ConnectionProperty ENDPOINT = + createNullable( ENDPOINT_PROPERTY_NAME, "The endpoint that the JDBC driver should connect to. The default is the default Spanner" + " production endpoint when autoConfigEmulator=false, and the default Spanner" @@ -202,8 +205,8 @@ public class ConnectionProperties { DEFAULT_ENDPOINT, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty AUTO_CONFIG_EMULATOR = - create( + public static final ConnectionProperty AUTO_CONFIG_EMULATOR = + createNonNull( "autoConfigEmulator", "Automatically configure the connection to try to connect to the Cloud Spanner emulator" + " (true/false). The instance and database in the connection string will" @@ -214,8 +217,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_DIRECT_ACCESS = - create( + public static final ConnectionProperty ENABLE_DIRECT_ACCESS = + createNullable( "enableDirectAccess", "Configure the connection to try to connect to Spanner using " + "DirectPath (true/false). The client will try to connect to Spanner " @@ -228,16 +231,18 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty UNIVERSE_DOMAIN = - create( + public static final ConnectionProperty UNIVERSE_DOMAIN = + createNullable( "universeDomain", "Configure the connection to try to connect to Spanner using " - + "a different partner Google Universe than GDU (googleapis.com).", - "googleapis.com", + + "a different partner Google Universe than GDU (googleapis.com). " + + "If not set, the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable is used, " + + "falling back to googleapis.com.", + null, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USE_AUTO_SAVEPOINTS_FOR_EMULATOR = - create( + public static final ConnectionProperty USE_AUTO_SAVEPOINTS_FOR_EMULATOR = + createNonNull( "useAutoSavepointsForEmulator", "Automatically creates savepoints for each statement in a read/write transaction when" + " using the Emulator. This is no longer needed when using Emulator version 1.5.23" @@ -246,8 +251,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USE_PLAIN_TEXT = - create( + public static final ConnectionProperty USE_PLAIN_TEXT = + createNonNull( USE_PLAIN_TEXT_PROPERTY_NAME, "Use a plain text communication channel (i.e. non-TLS) for communicating with the server" + " (true/false). Set this value to true for communication with the Cloud Spanner" @@ -256,8 +261,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty GRPC_KEEPALIVE_TIME = - create( + public static final ConnectionProperty GRPC_KEEPALIVE_TIME = + createNullable( GRPC_KEEPALIVE_TIME_PROPERTY_NAME, "The keepalive time for gRPC connections (e.g. '120s', '20s'). " + "Setting a lower keep-alive time (minimum 10s enforced by the gRPC library) " @@ -265,8 +270,8 @@ public class ConnectionProperties { null, DurationConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty GRPC_KEEPALIVE_TIMEOUT = - create( + public static final ConnectionProperty GRPC_KEEPALIVE_TIMEOUT = + createNullable( GRPC_KEEPALIVE_TIMEOUT_PROPERTY_NAME, "The keepalive timeout for gRPC connections (e.g. '20s', '5s'). This determines how long" + " the client waits for a keep-alive ping response before terminating the" @@ -280,8 +285,8 @@ public class ConnectionProperties { */ @ObsoleteApi("Use TYPE with value \"omni\" instead") @Deprecated - static final ConnectionProperty IS_EXPERIMENTAL_HOST = - create( + public static final ConnectionProperty IS_EXPERIMENTAL_HOST = + createNonNull( IS_EXPERIMENTAL_HOST_PROPERTY_NAME, "Set this value to true for communication with a Experimental Host.", DEFAULT_IS_EXPERIMENTAL_HOST, @@ -289,8 +294,8 @@ public class ConnectionProperties { BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty TYPE = - create( + public static final ConnectionProperty TYPE = + createNonNull( TYPE_PROPERTY_NAME, "Specifies the type of Spanner instance to connect to (cloud or omni). Setting it to omni" + " is mandatory when connecting to a Spanner Omni instance.", @@ -300,45 +305,45 @@ public class ConnectionProperties { }, InstanceTypeConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USERNAME = - create( + public static final ConnectionProperty USERNAME = + createNonNull( ConnectionOptions.USERNAME_PROPERTY_NAME, "The username to use for OPAQUE login.", ConnectionOptions.DEFAULT_USERNAME, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty PASSWORD = - create( + public static final ConnectionProperty PASSWORD = + createNonNull( ConnectionOptions.PASSWORD_PROPERTY_NAME, "The password to use for OPAQUE login.", ConnectionOptions.DEFAULT_PASSWORD, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CLIENT_CERTIFICATE = - create( + public static final ConnectionProperty CLIENT_CERTIFICATE = + createNullable( CLIENT_CERTIFICATE_PROPERTY_NAME, "Specifies the file path to the client certificate required for establishing an mTLS" + " connection.", DEFAULT_CLIENT_CERTIFICATE, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CLIENT_KEY = - create( + public static final ConnectionProperty CLIENT_KEY = + createNullable( CLIENT_KEY_PROPERTY_NAME, "Specifies the file path to the client private key required for establishing an mTLS" + " connection.", DEFAULT_CLIENT_KEY, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CA_CERTIFICATE = - create( + public static final ConnectionProperty CA_CERTIFICATE = + createNullable( CA_CERTIFICATE_PROPERTY_NAME, "Specifies the file path to the server root CA certificate for SSL/TLS validation.", DEFAULT_CA_CERTIFICATE, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CREDENTIALS_URL = - create( + public static final ConnectionProperty CREDENTIALS_URL = + createNullable( CREDENTIALS_PROPERTY_NAME, "The location of the credentials file to use for this connection. If neither this" + " property or encoded credentials are set, the connection will use the default" @@ -350,8 +355,8 @@ public class ConnectionProperties { DEFAULT_CREDENTIALS, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENCODED_CREDENTIALS = - create( + public static final ConnectionProperty ENCODED_CREDENTIALS = + createNullable( ENCODED_CREDENTIALS_PROPERTY_NAME, "Base64-encoded credentials to use for this connection. If neither this property or a" + " credentials location are set, the connection will use the default Google Cloud" @@ -363,24 +368,24 @@ public class ConnectionProperties { null, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty OAUTH_TOKEN = - create( + public static final ConnectionProperty OAUTH_TOKEN = + createNullable( OAUTH_TOKEN_PROPERTY_NAME, "A valid pre-existing OAuth token to use for authentication for this connection. Setting" + " this property will take precedence over any value set for a credentials file.", DEFAULT_OAUTH_TOKEN, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CREDENTIALS_PROVIDER = - create( + public static final ConnectionProperty CREDENTIALS_PROVIDER = + createNullable( CREDENTIALS_PROVIDER_PROPERTY_NAME, "The class name of the com.google.api.gax.core.CredentialsProvider implementation that" + " should be used to obtain credentials for connections.", null, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty GRPC_INTERCEPTOR_PROVIDER = - create( + public static final ConnectionProperty GRPC_INTERCEPTOR_PROVIDER = + createNullable( GRPC_INTERCEPTOR_PROVIDER_PROPERTY_NAME, "The class name of a " + GrpcInterceptorProvider.class.getName() @@ -397,8 +402,8 @@ public class ConnectionProperties { StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USER_AGENT = - create( + public static final ConnectionProperty USER_AGENT = + createNullable( USER_AGENT_PROPERTY_NAME, "The custom user-agent property name to use when communicating with Cloud Spanner. This" + " property is intended for internal library usage, and should not be set by" @@ -406,16 +411,16 @@ public class ConnectionProperties { DEFAULT_USER_AGENT, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DIALECT = - create( + public static final ConnectionProperty DIALECT = + createNonNull( DIALECT_PROPERTY_NAME, "Sets the dialect to use for new databases that are created by this connection.", Dialect.GOOGLE_STANDARD_SQL, Dialect.values(), DialectConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty TRACK_SESSION_LEAKS = - create( + public static final ConnectionProperty TRACK_SESSION_LEAKS = + createNonNull( TRACK_SESSION_LEAKS_PROPERTY_NAME, "Capture the call stack of the thread that checked out a session of the session pool." + " This will pre-create a LeakedSessionException already when a session is checked" @@ -428,8 +433,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty TRACK_CONNECTION_LEAKS = - create( + public static final ConnectionProperty TRACK_CONNECTION_LEAKS = + createNonNull( TRACK_CONNECTION_LEAKS_PROPERTY_NAME, "Capture the call stack of the thread that created a connection. This will pre-create a" + " LeakedConnectionException already when a connection is created. This can be" @@ -441,8 +446,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ROUTE_TO_LEADER = - create( + public static final ConnectionProperty ROUTE_TO_LEADER = + createNonNull( ROUTE_TO_LEADER_PROPERTY_NAME, "Should read/write transactions and partitioned DML be routed to leader region" + " (true/false)", @@ -450,8 +455,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USE_VIRTUAL_THREADS = - create( + public static final ConnectionProperty USE_VIRTUAL_THREADS = + createNonNull( USE_VIRTUAL_THREADS_PROPERTY_NAME, "Use a virtual thread instead of a platform thread for each connection (true/false). This" + " option only has any effect if the application is running on Java 21 or higher. In" @@ -460,8 +465,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty USE_VIRTUAL_GRPC_TRANSPORT_THREADS = - create( + public static final ConnectionProperty USE_VIRTUAL_GRPC_TRANSPORT_THREADS = + createNonNull( USE_VIRTUAL_GRPC_TRANSPORT_THREADS_PROPERTY_NAME, "Use a virtual thread instead of a platform thread for the gRPC executor (true/false)." + " This option only has any effect if the application is running on Java 21 or" @@ -470,8 +475,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_EXTENDED_TRACING = - create( + public static final ConnectionProperty ENABLE_EXTENDED_TRACING = + createNullable( ENABLE_EXTENDED_TRACING_PROPERTY_NAME, "Include the SQL string in the OpenTelemetry traces that are generated " + "by this connection. The SQL string is added as the standard OpenTelemetry " @@ -480,8 +485,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_API_TRACING = - create( + public static final ConnectionProperty ENABLE_API_TRACING = + createNullable( ENABLE_API_TRACING_PROPERTY_NAME, "Add OpenTelemetry traces for each individual RPC call. Enable this " + "to get a detailed view of each RPC that is being executed by your application, " @@ -491,8 +496,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_END_TO_END_TRACING = - create( + public static final ConnectionProperty ENABLE_END_TO_END_TRACING = + createNonNull( ENABLE_END_TO_END_TRACING_PROPERTY_NAME, "Enable end-to-end tracing (true/false) to generate traces for both the time that is" + " spent in the client, as well as time that is spent in the Spanner server. Server" @@ -503,29 +508,29 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty MIN_SESSIONS = - create( + public static final ConnectionProperty MIN_SESSIONS = + createNullable( MIN_SESSIONS_PROPERTY_NAME, "The minimum number of sessions in the backing session pool. The default is 100.", DEFAULT_MIN_SESSIONS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty MAX_SESSIONS = - create( + public static final ConnectionProperty MAX_SESSIONS = + createNullable( MAX_SESSIONS_PROPERTY_NAME, "The maximum number of sessions in the backing session pool. The default is 400.", DEFAULT_MAX_SESSIONS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty NUM_CHANNELS = - create( + public static final ConnectionProperty NUM_CHANNELS = + createNullable( NUM_CHANNELS_PROPERTY_NAME, "The number of gRPC channels to use to communicate with Cloud Spanner. The default is 4.", DEFAULT_NUM_CHANNELS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_DYNAMIC_CHANNEL_POOL = - create( + public static final ConnectionProperty ENABLE_DYNAMIC_CHANNEL_POOL = + createNullable( ENABLE_DYNAMIC_CHANNEL_POOL_PROPERTY_NAME, "Enable dynamic channel pooling for automatic gRPC channel scaling. When enabled, the " + "client will automatically scale the number of channels based on load. Setting " @@ -536,8 +541,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty ENABLE_GRPC_GCP = - create( + public static final ConnectionProperty ENABLE_GRPC_GCP = + createNullable( ENABLE_GRPC_GCP_PROPERTY_NAME, "Enable or disable grpc-gcp channel pool (true/false). Setting this to false will disable" + " grpc-gcp and use the Gax gRPC channel pool. Disabling grpc-gcp also automatically" @@ -548,8 +553,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_MIN_CHANNELS = - create( + public static final ConnectionProperty DCP_MIN_CHANNELS = + createNullable( DCP_MIN_CHANNELS_PROPERTY_NAME, "The minimum number of channels in the dynamic channel pool. Only used when " + "enableDynamicChannelPool is true. The default is " @@ -557,8 +562,8 @@ public class ConnectionProperties { DEFAULT_DCP_MIN_CHANNELS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_MAX_CHANNELS = - create( + public static final ConnectionProperty DCP_MAX_CHANNELS = + createNullable( DCP_MAX_CHANNELS_PROPERTY_NAME, "The maximum number of channels in the dynamic channel pool. Only used when " + "enableDynamicChannelPool is true. The default is " @@ -566,8 +571,8 @@ public class ConnectionProperties { DEFAULT_DCP_MAX_CHANNELS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_INITIAL_CHANNELS = - create( + public static final ConnectionProperty DCP_INITIAL_CHANNELS = + createNullable( DCP_INITIAL_CHANNELS_PROPERTY_NAME, "The initial number of channels in the dynamic channel pool. Only used when " + "enableDynamicChannelPool is true. The default is " @@ -575,8 +580,8 @@ public class ConnectionProperties { DEFAULT_DCP_INITIAL_CHANNELS, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_MIN_RPC_PER_CHANNEL = - create( + public static final ConnectionProperty DCP_MIN_RPC_PER_CHANNEL = + createNullable( DCP_MIN_RPC_PER_CHANNEL_PROPERTY_NAME, "The minimum number of desired RPCs per channel in the dynamic channel pool. Only used" + " when enableDynamicChannelPool is true. The default is " @@ -585,8 +590,8 @@ public class ConnectionProperties { DEFAULT_DCP_MIN_RPC_PER_CHANNEL, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_MAX_RPC_PER_CHANNEL = - create( + public static final ConnectionProperty DCP_MAX_RPC_PER_CHANNEL = + createNullable( DCP_MAX_RPC_PER_CHANNEL_PROPERTY_NAME, "The maximum number of desired RPCs per channel in the dynamic channel pool. Only used" + " when enableDynamicChannelPool is true. The default is " @@ -595,16 +600,16 @@ public class ConnectionProperties { DEFAULT_DCP_MAX_RPC_PER_CHANNEL, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DCP_CONCURRENT_STREAMS_LOW_WATERMARK = - create( + public static final ConnectionProperty DCP_CONCURRENT_STREAMS_LOW_WATERMARK = + createNullable( DCP_CONCURRENT_STREAMS_LOW_WATERMARK_PROPERTY_NAME, "The concurrent streams low watermark in the dynamic channel pool. Only used when " + "enableDynamicChannelPool is true.", DEFAULT_DCP_CONCURRENT_STREAMS_LOW_WATERMARK, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty CHANNEL_PROVIDER = - create( + public static final ConnectionProperty CHANNEL_PROVIDER = + createNullable( CHANNEL_PROVIDER_PROPERTY_NAME, "The name of the channel provider class. The name must reference an implementation of" + " ExternalChannelProvider. If this property is not set, the connection will use the" @@ -612,8 +617,8 @@ public class ConnectionProperties { DEFAULT_CHANNEL_PROVIDER, StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty DATABASE_ROLE = - create( + public static final ConnectionProperty DATABASE_ROLE = + createNullable( DATABASE_ROLE_PROPERTY_NAME, "Sets the database role to use for this connection. The default is privileges assigned to" + " IAM role", @@ -621,24 +626,24 @@ public class ConnectionProperties { StringValueConverter.INSTANCE, Context.STARTUP); - static final ConnectionProperty AUTOCOMMIT = - create( + public static final ConnectionProperty AUTOCOMMIT = + createNonNull( AUTOCOMMIT_PROPERTY_NAME, "Should the connection start in autocommit (true/false)", DEFAULT_AUTOCOMMIT, BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty READONLY = - create( + public static final ConnectionProperty READONLY = + createNonNull( READONLY_PROPERTY_NAME, "Should the connection start in read-only mode (true/false)", DEFAULT_READONLY, BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty DEFAULT_ISOLATION_LEVEL = - create( + public static final ConnectionProperty DEFAULT_ISOLATION_LEVEL = + createNonNull( "default_isolation_level", "The transaction isolation level that is used by default for read/write transactions. The" + " default is isolation_level_unspecified, which means that the connection will use" @@ -651,8 +656,8 @@ public class ConnectionProperties { }, IsolationLevelConverter.INSTANCE, Context.USER); - static final ConnectionProperty READ_LOCK_MODE = - create( + public static final ConnectionProperty READ_LOCK_MODE = + createNonNull( "read_lock_mode", "This option controls the locking behavior for read operations and queries within a" + " read/write transaction. It works in conjunction with the transaction's isolation" @@ -683,25 +688,23 @@ public class ConnectionProperties { .toArray(new ReadLockMode[0]), ReadLockModeConverter.INSTANCE, Context.USER); - static final ConnectionProperty STATEMENT_TIMEOUT = - create( + public static final ConnectionProperty STATEMENT_TIMEOUT = + createNullable( "statement_timeout", "Adds a timeout to all statements executed on this connection. " + "This property is only used when a statement timeout is specified.", null, - null, DurationConverter.INSTANCE, Context.USER); - static final ConnectionProperty TRANSACTION_TIMEOUT = - create( + public static final ConnectionProperty TRANSACTION_TIMEOUT = + createNullable( "transaction_timeout", "Timeout for read/write transactions.", null, - null, DurationConverter.INSTANCE, Context.USER); - static final ConnectionProperty AUTOCOMMIT_DML_MODE = - create( + public static final ConnectionProperty AUTOCOMMIT_DML_MODE = + createNullable( "autocommit_dml_mode", "Determines the transaction type that is used to execute " + "DML statements when the connection is in auto-commit mode.", @@ -710,8 +713,8 @@ public class ConnectionProperties { Arrays.copyOf(AutocommitDmlMode.values(), AutocommitDmlMode.values().length + 1), AutocommitDmlModeConverter.INSTANCE, Context.USER); - static final ConnectionProperty RETRY_ABORTS_INTERNALLY = - create( + public static final ConnectionProperty RETRY_ABORTS_INTERNALLY = + createNonNull( // TODO: Add support for synonyms for connection properties. // retryAbortsInternally / retry_aborts_internally is currently not consistent. // The connection URL property is retryAbortsInternally. The SET statement assumes @@ -723,16 +726,16 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty RETURN_COMMIT_STATS = - create( + public static final ConnectionProperty RETURN_COMMIT_STATS = + createNonNull( "returnCommitStats", "Request that Spanner returns commit statistics for read/write transactions (true/false)", DEFAULT_RETURN_COMMIT_STATS, BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE = - create( + public static final ConnectionProperty DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE = + createNonNull( DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE_NAME, "Enabling this option will delay the actual start of a read/write transaction until the" + " first write operation is seen in that transaction. All reads that happen before" @@ -747,8 +750,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty KEEP_TRANSACTION_ALIVE = - create( + public static final ConnectionProperty KEEP_TRANSACTION_ALIVE = + createNonNull( KEEP_TRANSACTION_ALIVE_PROPERTY_NAME, "Enabling this option will trigger the connection to keep read/write transactions alive" + " by executing a SELECT 1 query once every 10 seconds if no other statements are" @@ -761,15 +764,15 @@ public class ConnectionProperties { BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty READ_ONLY_STALENESS = - create( + public static final ConnectionProperty READ_ONLY_STALENESS = + createNonNull( "read_only_staleness", "The read-only staleness to use for read-only transactions and single-use queries.", TimestampBound.strong(), ReadOnlyStalenessConverter.INSTANCE, Context.USER); - static final ConnectionProperty AUTO_PARTITION_MODE = - create( + public static final ConnectionProperty AUTO_PARTITION_MODE = + createNonNull( AUTO_PARTITION_MODE_PROPERTY_NAME, "Execute all queries on this connection as partitioned queries. " + "Executing a query that cannot be partitioned will fail. " @@ -778,8 +781,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty DATA_BOOST_ENABLED = - create( + public static final ConnectionProperty DATA_BOOST_ENABLED = + createNonNull( DATA_BOOST_ENABLED_PROPERTY_NAME, "Enable data boost for all partitioned queries that are executed by this connection. This" + " setting is only used for partitioned queries and is ignored by all other" @@ -788,16 +791,16 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty MAX_PARTITIONS = - create( + public static final ConnectionProperty MAX_PARTITIONS = + createNonNull( MAX_PARTITIONS_PROPERTY_NAME, "The max partitions hint value to use for partitioned queries. " + "Use 0 if you do not want to specify a hint.", DEFAULT_MAX_PARTITIONS, NonNegativeIntegerConverter.INSTANCE, Context.USER); - static final ConnectionProperty MAX_PARTITIONED_PARALLELISM = - create( + public static final ConnectionProperty MAX_PARTITIONED_PARALLELISM = + createNonNull( MAX_PARTITIONED_PARALLELISM_PROPERTY_NAME, "The max partitions hint value to use for partitioned queries. " + "Use 0 if you do not want to specify a hint.", @@ -805,29 +808,29 @@ public class ConnectionProperties { NonNegativeIntegerConverter.INSTANCE, Context.USER); - static final ConnectionProperty DIRECTED_READ = - create( + public static final ConnectionProperty DIRECTED_READ = + createNullable( "directed_read", "The directed read options to apply to read-only transactions.", null, DirectedReadOptionsConverter.INSTANCE, Context.USER); - static final ConnectionProperty OPTIMIZER_VERSION = - create( + public static final ConnectionProperty OPTIMIZER_VERSION = + createNonNull( OPTIMIZER_VERSION_PROPERTY_NAME, "Sets the default query optimizer version to use for this connection.", DEFAULT_OPTIMIZER_VERSION, StringValueConverter.INSTANCE, Context.USER); - static final ConnectionProperty OPTIMIZER_STATISTICS_PACKAGE = - create( + public static final ConnectionProperty OPTIMIZER_STATISTICS_PACKAGE = + createNonNull( OPTIMIZER_STATISTICS_PACKAGE_PROPERTY_NAME, "Sets the query optimizer statistics package to use for this connection.", DEFAULT_OPTIMIZER_STATISTICS_PACKAGE, StringValueConverter.INSTANCE, Context.USER); - static final ConnectionProperty RPC_PRIORITY = - create( + public static final ConnectionProperty RPC_PRIORITY = + createNullable( RPC_PRIORITY_NAME, "Sets the priority for all RPC invocations from this connection (HIGH/MEDIUM/LOW). The" + " default is HIGH.", @@ -836,24 +839,24 @@ public class ConnectionProperties { Arrays.copyOf(RpcPriority.values(), RpcPriority.values().length + 1), RpcPriorityConverter.INSTANCE, Context.USER); - static final ConnectionProperty SAVEPOINT_SUPPORT = - create( + public static final ConnectionProperty SAVEPOINT_SUPPORT = + createNonNull( "savepoint_support", "Determines the behavior of the connection when savepoints are used.", SavepointSupport.FAIL_AFTER_ROLLBACK, SavepointSupport.values(), SavepointSupportConverter.INSTANCE, Context.USER); - static final ConnectionProperty DDL_IN_TRANSACTION_MODE = - create( + public static final ConnectionProperty DDL_IN_TRANSACTION_MODE = + createNonNull( DDL_IN_TRANSACTION_MODE_PROPERTY_NAME, "Determines how the connection should handle DDL statements in a read/write transaction.", DEFAULT_DDL_IN_TRANSACTION_MODE, DdlInTransactionMode.values(), DdlInTransactionModeConverter.INSTANCE, Context.USER); - static final ConnectionProperty DEFAULT_SEQUENCE_KIND = - create( + public static final ConnectionProperty DEFAULT_SEQUENCE_KIND = + createNullable( DEFAULT_SEQUENCE_KIND_PROPERTY_NAME, "The default sequence kind that should be used for the database. " + "This property is only used when a DDL statement that requires a default " @@ -861,15 +864,15 @@ public class ConnectionProperties { DEFAULT_DEFAULT_SEQUENCE_KIND, StringValueConverter.INSTANCE, Context.USER); - static final ConnectionProperty MAX_COMMIT_DELAY = - create( + public static final ConnectionProperty MAX_COMMIT_DELAY = + createNullable( "maxCommitDelay", "The max delay that Spanner may apply to commit requests to improve throughput.", null, DurationConverter.INSTANCE, Context.USER); - static final ConnectionProperty AUTO_BATCH_DML = - create( + public static final ConnectionProperty AUTO_BATCH_DML = + createNonNull( AUTO_BATCH_DML_PROPERTY_NAME, "Automatically buffer DML statements that are executed on this connection and execute" + " them as one batch when a non-DML statement is executed, or when the current" @@ -883,8 +886,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty AUTO_BATCH_DML_UPDATE_COUNT = - create( + public static final ConnectionProperty AUTO_BATCH_DML_UPDATE_COUNT = + createNonNull( AUTO_BATCH_DML_UPDATE_COUNT_PROPERTY_NAME, "DML statements that are executed when " + AUTO_BATCH_DML_PROPERTY_NAME @@ -897,8 +900,8 @@ public class ConnectionProperties { DEFAULT_AUTO_BATCH_DML_UPDATE_COUNT, LongConverter.INSTANCE, Context.USER); - static final ConnectionProperty AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION = - create( + public static final ConnectionProperty AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION = + createNonNull( AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION_PROPERTY_NAME, "The update count that is returned for DML statements that are buffered during " + "an automatic DML batch is by default " @@ -917,8 +920,8 @@ public class ConnectionProperties { BOOLEANS, BooleanConverter.INSTANCE, Context.USER); - static final ConnectionProperty BATCH_DML_UPDATE_COUNT = - create( + public static final ConnectionProperty BATCH_DML_UPDATE_COUNT = + createNonNull( BATCH_DML_UPDATE_COUNT_PROPERTY_NAME, "The update count that is returned for DML statements that are executed in an " + "explicit DML batch. The default is " @@ -927,7 +930,7 @@ public class ConnectionProperties { LongConverter.INSTANCE, Context.USER); public static final ConnectionProperty UNKNOWN_LENGTH = - create( + createNonNull( "unknownLength", "Spanner does not return the length of the selected columns in query results. When" + " returning meta-data about these columns through functions like" @@ -946,14 +949,52 @@ public class ConnectionProperties { public static ImmutableList> VALID_CONNECTION_PROPERTIES = ImmutableList.copyOf(ConnectionProperties.CONNECTION_PROPERTIES.values()); - /** Utility method for creating a new core {@link ConnectionProperty}. */ - private static ConnectionProperty create( + /** Utility method for creating a new core {@link ConnectionProperty} that allows null values. */ + private static ConnectionProperty createNullable( + String name, + String description, + T defaultValue, + ClientSideStatementValueConverter converter, + Context context) { + return create(name, description, defaultValue, null, true, converter, context); + } + + /** Utility method for creating a new core {@link ConnectionProperty} that allows null values. */ + private static ConnectionProperty createNullable( + String name, + String description, + T defaultValue, + T[] validValues, + ClientSideStatementValueConverter converter, + Context context) { + return create(name, description, defaultValue, validValues, true, converter, context); + } + + /** + * Utility method for creating a new core {@link ConnectionProperty} that does not allow null + * values. + */ + private static ConnectionProperty createNonNull( + String name, + String description, + T defaultValue, + ClientSideStatementValueConverter converter, + Context context) { + return create(name, description, defaultValue, null, false, converter, context); + } + + /** + * Utility method for creating a new core {@link ConnectionProperty} that does not allow null + * values. + */ + private static ConnectionProperty createNonNull( String name, String description, T defaultValue, + T[] validValues, ClientSideStatementValueConverter converter, Context context) { - return create(name, description, defaultValue, null, converter, context); + return create(name, description, defaultValue, validValues, false, converter, context); } /** Utility method for creating a new core {@link ConnectionProperty}. */ @@ -962,34 +1003,49 @@ private static ConnectionProperty create( String description, T defaultValue, T[] validValues, + boolean nullAllowed, ClientSideStatementValueConverter converter, Context context) { ConnectionProperty property = - ConnectionProperty.create(name, description, defaultValue, validValues, converter, context); + ConnectionProperty.create( + name, description, defaultValue, validValues, nullAllowed, converter, context); CONNECTION_PROPERTIES_BUILDER.put(property.getKey(), property); return property; } /** Parse the connection properties that can be found in the given connection URL. */ static ImmutableMap> parseValues(String url) { + return parseValues(ConnectionOptions.parseUriProperties(url)); + } + + /** Parse and convert the connection properties from an already-parsed URI property map. */ + static ImmutableMap> parseValues( + ConnectionOptions.ParsedUriProperties parsedUriProperties) { ImmutableMap.Builder> builder = ImmutableMap.builder(); - for (ConnectionProperty property : CONNECTION_PROPERTIES.values()) { - ConnectionPropertyValue value = parseValue(castProperty(property), url); - if (value != null) { - builder.put(property.getKey(), value); - } - } + collectValues(parsedUriProperties, builder); return builder.build(); } /** - * Parse and convert the value of the specific connection property from a connection URL (e.g. - * readonly=true). + * Validates the values of known connection properties in an already-parsed URI property map + * without allocating a result map. */ - private static ConnectionPropertyValue parseValue( - ConnectionProperty property, String url) { - String stringValue = ConnectionOptions.parseUriProperty(url, property.getKey()); - return property.convert(stringValue); + static void validateValues(ConnectionOptions.ParsedUriProperties parsedUriProperties) { + collectValues(parsedUriProperties, null); + } + + private static void collectValues( + ConnectionOptions.ParsedUriProperties parsedUriProperties, + ImmutableMap.@Nullable Builder> builder) { + for (Map.Entry entry : parsedUriProperties.getPropertyValues().entrySet()) { + ConnectionProperty property = CONNECTION_PROPERTIES.get(entry.getKey()); + if (property != null) { + ConnectionPropertyValue converted = property.convert(entry.getValue()); + if (builder != null) { + builder.put(property.getKey(), converted); + } + } + } } /** This class should not be instantiated. */ diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperty.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperty.java index 7c06774cf2fb..cbadc4911cae 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperty.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionProperty.java @@ -16,10 +16,12 @@ package com.google.cloud.spanner.connection; +import com.google.api.core.InternalApi; import com.google.cloud.spanner.ErrorCode; import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.common.base.Strings; import java.util.Locale; +import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -36,6 +38,7 @@ * the default for PostgreSQL-dialect databases. For GoogleSQL-dialect databases, transactional * connection state is an opt-in. */ +@InternalApi public class ConnectionProperty { /** @@ -78,9 +81,10 @@ static ConnectionProperty create( @Nonnull String name, String description, T defaultValue, + boolean nullAllowed, ClientSideStatementValueConverter converter, Context context) { - return create(name, description, defaultValue, null, converter, context); + return create(name, description, defaultValue, null, nullAllowed, converter, context); } /** Utility method for creating a typed {@link ConnectionProperty}. */ @@ -90,10 +94,11 @@ static ConnectionProperty create( String description, T defaultValue, T[] validValues, + boolean nullAllowed, ClientSideStatementValueConverter converter, Context context) { return new ConnectionProperty<>( - null, name, description, defaultValue, validValues, converter, context); + null, name, description, defaultValue, validValues, nullAllowed, converter, context); } /** @@ -116,18 +121,24 @@ static ConnectionProperty create( private final Context context; + private final boolean nullAllowed; + ConnectionProperty( String extension, @Nonnull String name, @Nonnull String description, T defaultValue, T[] validValues, + boolean nullAllowed, ClientSideStatementValueConverter converter, Context context) { ConnectionPreconditions.checkArgument( !Strings.isNullOrEmpty(name), "property name must be a non-empty string"); ConnectionPreconditions.checkArgument( !Strings.isNullOrEmpty(description), "property description must be a non-empty string"); + ConnectionPreconditions.checkArgument( + defaultValue != null || nullAllowed, + "defaultValue cannot be null when null is not allowed"); this.extension = extension == null ? null : extension.toLowerCase(Locale.ENGLISH); this.name = name.toLowerCase(Locale.ENGLISH); this.description = description; @@ -136,6 +147,7 @@ static ConnectionProperty create( this.converter = converter; this.context = context; this.key = createKey(this.extension, this.name); + this.nullAllowed = nullAllowed; } @Override @@ -163,6 +175,24 @@ ConnectionPropertyValue createInitialValue(@Nullable ConnectionPropertyValue< : initialValue.copy(); } + boolean isValidValue(@Nullable T value) { + if (value == null) { + return this.nullAllowed; + } + if (!this.converter.isValid(value)) { + return false; + } + if (this.validValues != null) { + for (T validValue : this.validValues) { + if (Objects.equals(validValue, value)) { + return true; + } + } + return false; + } + return true; + } + @Nullable ConnectionPropertyValue convert(@Nullable String stringValue) { if (stringValue == null) { @@ -210,4 +240,9 @@ public T[] getValidValues() { public Context getContext() { return this.context; } + + /** Returns {@code true} if {@code null} is a valid value for this property. */ + public boolean isNullAllowed() { + return this.nullAllowed; + } } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertyValue.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertyValue.java index 088a28d9d8a3..7414471dac1d 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertyValue.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertyValue.java @@ -16,21 +16,43 @@ package com.google.cloud.spanner.connection; +import com.google.api.core.InternalApi; +import com.google.cloud.spanner.ErrorCode; +import com.google.cloud.spanner.SpannerExceptionFactory; import com.google.cloud.spanner.connection.ConnectionProperty.Context; +import com.google.common.base.Preconditions; import java.util.Objects; +import org.jspecify.annotations.Nullable; -class ConnectionPropertyValue { +/** + * Value holder for a {@link ConnectionProperty} in a {@link ConnectionOptions} or {@link + * ConnectionState}. + */ +@InternalApi +public class ConnectionPropertyValue { static ConnectionPropertyValue cast(ConnectionPropertyValue value) { //noinspection unchecked return (ConnectionPropertyValue) value; } + /** Creates a {@link ConnectionPropertyValue} with the given property and value. */ + public static ConnectionPropertyValue of( + ConnectionProperty property, @Nullable T value) { + Preconditions.checkNotNull(property, "property must not be null"); + if (!property.isValidValue(value)) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.INVALID_ARGUMENT, "Invalid value for property " + property + ": " + value); + } + return new ConnectionPropertyValue<>(property, value, value); + } + private final ConnectionProperty property; - private final T resetValue; + private final @Nullable T resetValue; - private T value; + private @Nullable T value; - ConnectionPropertyValue(ConnectionProperty property, T resetValue, T value) { + ConnectionPropertyValue( + ConnectionProperty property, @Nullable T resetValue, @Nullable T value) { this.property = property; this.resetValue = resetValue; this.value = value; @@ -52,15 +74,15 @@ public int hashCode() { return Objects.hash(this.property, this.resetValue, this.value); } - ConnectionProperty getProperty() { + public ConnectionProperty getProperty() { return property; } - T getResetValue() { + public @Nullable T getResetValue() { return resetValue; } - T getValue() { + public @Nullable T getValue() { return value; } diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/omni/OpaqueUtil.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/omni/OpaqueUtil.java index e7dd92824c25..366163bd9b41 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/omni/OpaqueUtil.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/omni/OpaqueUtil.java @@ -237,16 +237,80 @@ public static byte[] getHashToCurve(byte[] message, byte[] domain) } } - public static byte[] blind(byte[] password, byte[] blindScalar) throws GeneralSecurityException { - byte[] hashedPoint = getHashToCurve(password, LOGIN_DOMAIN_SEPARATION_TAG.getBytes(UTF_8)); + /** + * Decodes a canonical 33-byte compressed secp256r1 point, rejecting the point at infinity, + * non-canonical encodings, and off-curve coordinates per RFC 9497 Section 3.3.1 / RFC 9807. + */ + private static ECPoint decodeCompressedPoint(ECCurve curve, byte[] encoded, String label) + throws GeneralSecurityException { + if (encoded == null) { + throw new GeneralSecurityException("Invalid " + label + ": point bytes must not be null"); + } + if (encoded.length != PUBLIC_KEY_LENGTH || (encoded[0] != 0x02 && encoded[0] != 0x03)) { + throw new GeneralSecurityException( + "Invalid " + + label + + ": expected " + + PUBLIC_KEY_LENGTH + + "-byte compressed secp256r1 point"); + } + ECPoint point; + try { + point = curve.decodePoint(encoded); + } catch (IllegalArgumentException e) { + throw new GeneralSecurityException( + "Invalid " + label + ": failed to decode secp256r1 point", e); + } + // Defense-in-depth: unreachable via public API on prime-order secp256r1 after 33-byte + // compressed decoding, kept to fail closed if the curve or decoder ever changes. + if (point.isInfinity() || !point.isValid()) { + throw new GeneralSecurityException( + "Invalid " + label + ": point is at infinity or not on curve"); + } + return point; + } + /** + * Validates that a big-endian scalar byte array is non-null, non-empty, and non-zero modulo the + * curve order, returning the reduced value in {@code [1, order - 1]} so scalar inversion and + * BouncyCastle multiplication cannot fail or collapse to infinity. + */ + private static BigInteger validateNonZeroScalar( + byte[] scalarBytes, BigInteger order, String label) throws GeneralSecurityException { + if (scalarBytes == null || scalarBytes.length == 0) { + throw new GeneralSecurityException("Invalid " + label + ": scalar must not be null or empty"); + } + BigInteger reduced = new BigInteger(1, scalarBytes).mod(order); + if (reduced.equals(BigInteger.ZERO)) { + throw new GeneralSecurityException( + "Invalid " + label + ": scalar must be non-zero modulo curve order"); + } + return reduced; + } + + /** + * Normalizes and encodes a curve point in compressed form, failing closed if the multiplication + * result is the point at infinity. + */ + private static byte[] encodeNonInfinityPoint(ECPoint point, String label) + throws GeneralSecurityException { + ECPoint normalized = point.normalize(); + // Defense-in-depth: unreachable on prime-order secp256r1 with validated non-zero scalars, + // kept to fail closed if the curve or caller invariants ever change. + if (normalized.isInfinity()) { + throw new GeneralSecurityException("Invalid " + label + ": resulting point is at infinity"); + } + return normalized.getEncoded(true); + } + + public static byte[] blind(byte[] password, byte[] blindScalar) throws GeneralSecurityException { X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME); - ECCurve curve = params.getCurve(); + BigInteger scalar = validateNonZeroScalar(blindScalar, params.getN(), "blindScalar"); - ECPoint point = curve.decodePoint(hashedPoint); - BigInteger scalar = new BigInteger(1, blindScalar); + byte[] hashedPoint = getHashToCurve(password, LOGIN_DOMAIN_SEPARATION_TAG.getBytes(UTF_8)); + ECPoint point = decodeCompressedPoint(params.getCurve(), hashedPoint, "hashedPoint"); - return point.multiply(scalar).getEncoded(true); + return encodeNonInfinityPoint(point.multiply(scalar), "blindedPoint"); } public static byte[] expand(byte[] keyMaterial, byte[] info, int size) @@ -323,24 +387,24 @@ public static byte[] mac(byte[] key, byte[] data) throws GeneralSecurityExceptio public static byte[] finalize(byte[] blind, byte[] evaluatedMessage) throws GeneralSecurityException { - BigInteger blindBigInt = new BigInteger(1, blind); X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME); BigInteger order = params.getN(); + BigInteger blindBigInt = validateNonZeroScalar(blind, order, "blind"); BigInteger inverseBlind = blindBigInt.modInverse(order); - ECCurve curve = params.getCurve(); - ECPoint evaluatedPoint = curve.decodePoint(evaluatedMessage); + ECPoint evaluatedPoint = + decodeCompressedPoint(params.getCurve(), evaluatedMessage, "evaluatedMessage"); - return evaluatedPoint.multiply(inverseBlind).getEncoded(true); + return encodeNonInfinityPoint(evaluatedPoint.multiply(inverseBlind), "evaluatedMessage"); } public static byte[] diffieHellman(byte[] privateKey, byte[] peerPublicKey) throws GeneralSecurityException { X9ECParameters params = CustomNamedCurves.getByName(CURVE_NAME); - ECCurve curve = params.getCurve(); - ECPoint peerPublicPoint = curve.decodePoint(peerPublicKey); - BigInteger priv = new BigInteger(1, privateKey); - return peerPublicPoint.multiply(priv).getEncoded(true); + BigInteger priv = validateNonZeroScalar(privateKey, params.getN(), "privateKey"); + ECPoint peerPublicPoint = + decodeCompressedPoint(params.getCurve(), peerPublicKey, "peerPublicKey"); + return encodeNonInfinityPoint(peerPublicPoint.multiply(priv), "peerPublicKey"); } public static byte[] randomOracleSha256(byte[] x, BigInteger max) diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionState.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionState.java new file mode 100644 index 000000000000..f3b82c557590 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionState.java @@ -0,0 +1,151 @@ +/* + * 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.spi.v1; + +import com.google.api.gax.grpc.GrpcStatusCode; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.spanner.v1.BatchWriteRequest; +import com.google.spanner.v1.BatchWriteResponse; +import io.grpc.Status; +import org.jspecify.annotations.Nullable; + +/** + * Pure state tracker for {@code BatchWrite} mutation groups across stream resumption attempts. + * + *

    Tracks which mutation groups remain unacknowledged, builds compacted retry requests containing + * only remaining groups, and translates attempt-local response indices back to the caller's + * original index space while releasing acknowledged payloads for immediate garbage collection. + * + *

    Not thread-safe; callers must synchronize access externally. + */ +final class BatchWriteResumptionState { + + // Metadata-only template (session, request_options, exclude_txn_from_change_streams) with + // mutation_groups cleared so acknowledged payloads can be garbage-collected mid-stream. + private final BatchWriteRequest requestTemplate; + // Entries are nulled once acknowledged so large mutation payloads can be GC'd immediately. + private final BatchWriteRequest.MutationGroup[] pending; + private int remaining; + private int @Nullable [] streamIndexes; + + BatchWriteResumptionState(BatchWriteRequest initialRequest) { + Preconditions.checkNotNull(initialRequest, "initialRequest must not be null"); + this.requestTemplate = initialRequest.toBuilder().clearMutationGroups().build(); + int count = initialRequest.getMutationGroupsCount(); + this.pending = new BatchWriteRequest.MutationGroup[count]; + for (int i = 0; i < count; i++) { + this.pending[i] = initialRequest.getMutationGroups(i); + } + this.remaining = count; + } + + boolean isAllAcknowledged() { + return remaining == 0; + } + + int getRemainingCount() { + return remaining; + } + + int getTotalCount() { + return pending.length; + } + + BatchWriteRequest getRequestTemplate() { + return requestTemplate; + } + + @VisibleForTesting + BatchWriteRequest.@Nullable MutationGroup getPending(int originalIndex) { + return pending[originalIndex]; + } + + /** + * Builds the request for the next stream attempt containing only unacknowledged mutation groups + * and updates the relative-to-original index mapping for that attempt. + */ + BatchWriteRequest buildNextAttemptRequest() { + BatchWriteRequest.Builder builder = requestTemplate.toBuilder(); + int[] nextIndexes = new int[remaining]; + int pos = 0; + for (int i = 0; i < pending.length; i++) { + BatchWriteRequest.MutationGroup group = pending[i]; + if (group != null) { + builder.addMutationGroups(group); + nextIndexes[pos++] = i; + } + } + this.streamIndexes = nextIndexes; + return builder.build(); + } + + /** + * Validates all indices in {@code response}, translates them back to the caller's original index + * space, and marks those mutation groups as acknowledged. + * + * @throws ApiException with {@link Status.Code#INTERNAL} (non-retryable) if any index is out of + * bounds; tracking state is left unmodified when this exception is thrown. + */ + BatchWriteResponse translateAndAcknowledge(BatchWriteResponse response) { + Preconditions.checkNotNull(response, "response must not be null"); + Preconditions.checkState( + streamIndexes != null, + "buildNextAttemptRequest() must be called before translateAndAcknowledge()"); + int indexCount = response.getIndexesCount(); + // Validate all indices before mutating tracking state. + for (int i = 0; i < indexCount; i++) { + int relIdx = response.getIndexes(i); + if (relIdx < 0 || relIdx >= streamIndexes.length) { + throw ApiExceptionFactory.createException( + String.format( + "Spanner returned mutation group index %d out of bounds for BatchWrite" + + " stream with %d mutation groups", + relIdx, streamIndexes.length), + null, + GrpcStatusCode.of(Status.Code.INTERNAL), + /* retryable= */ false); + } + } + + // When all mutation groups are present in the attempt request, streamIndexes is the identity + // mapping, so we can update tracking state and return response directly without copying. + if (streamIndexes.length == pending.length) { + for (int i = 0; i < indexCount; i++) { + int origIdx = response.getIndexes(i); + if (pending[origIdx] != null) { + pending[origIdx] = null; + remaining--; + } + } + return response; + } + + BatchWriteResponse.Builder translated = response.toBuilder().clearIndexes(); + for (int i = 0; i < indexCount; i++) { + int origIdx = streamIndexes[response.getIndexes(i)]; + translated.addIndexes(origIdx); + if (pending[origIdx] != null) { + pending[origIdx] = null; + remaining--; + } + } + return translated.build(); + } +} diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicy.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicy.java new file mode 100644 index 000000000000..603681917b49 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicy.java @@ -0,0 +1,270 @@ +/* + * 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.spi.v1; + +import com.google.api.core.ApiClock; +import com.google.api.gax.grpc.GrpcStatusCode; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.StatusCode.Code; +import com.google.api.gax.rpc.WatchdogTimeoutException; +import com.google.cloud.spanner.IsRetryableInternalError; +import com.google.cloud.spanner.StreamingRetryHelper; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.Status; +import io.grpc.StatusException; +import io.grpc.StatusRuntimeException; +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.DoubleSupplier; +import org.jspecify.annotations.Nullable; + +/** + * Pure retryability, backoff, {@code RetryInfo} extraction, and timeout budgeting policy for {@code + * BatchWrite} stream resumption. + */ +final class BatchWriteRetryPolicy { + + private final RetrySettings retrySettings; + private final ImmutableSet retryableCodes; + private final ApiClock clock; + private final DoubleSupplier jitterRandom; + + BatchWriteRetryPolicy( + RetrySettings retrySettings, + Set retryableCodes, + ApiClock clock, + DoubleSupplier jitterRandom) { + this.retrySettings = + Preconditions.checkNotNull(retrySettings, "retrySettings must not be null"); + this.retryableCodes = + ImmutableSet.copyOf( + Preconditions.checkNotNull(retryableCodes, "retryableCodes must not be null")); + this.clock = Preconditions.checkNotNull(clock, "clock must not be null"); + this.jitterRandom = Preconditions.checkNotNull(jitterRandom, "jitterRandom must not be null"); + } + + enum Action { + RETRY, + PERMANENT_FAILURE, + RETRIES_EXHAUSTED, + CANCELLED + } + + static final class RetryDecision { + final Action action; + final Duration delay; + final @Nullable Throwable terminalError; + + private RetryDecision(Action action, Duration delay, @Nullable Throwable terminalError) { + this.action = action; + this.delay = delay; + this.terminalError = terminalError; + } + + static RetryDecision retry(Duration delay) { + return new RetryDecision( + Action.RETRY, Preconditions.checkNotNull(delay, "delay must not be null"), null); + } + + static RetryDecision permanentFailure(Throwable error) { + return new RetryDecision(Action.PERMANENT_FAILURE, Duration.ZERO, error); + } + + static RetryDecision retriesExhausted(Throwable error) { + return new RetryDecision(Action.RETRIES_EXHAUSTED, Duration.ZERO, error); + } + + static RetryDecision cancelled(Throwable error) { + return new RetryDecision(Action.CANCELLED, Duration.ZERO, error); + } + } + + RetryDecision evaluate( + Throwable error, + int completedAttempts, + long operationStartNanos, + Context grpcContext, + @Nullable Deadline callOptionsDeadline) { + if (grpcContext.isCancelled()) { + ApiException cancelError = createContextCancellationException(grpcContext); + if (cancelError.getStatusCode().getCode() == Code.DEADLINE_EXCEEDED) { + return RetryDecision.permanentFailure(cancelError); + } + return RetryDecision.cancelled(cancelError); + } + if (!isRetryable(error)) { + return RetryDecision.permanentFailure(error); + } + + // maxAttempts == 1 disables retries; maxAttempts == 0 means unlimited (GAX convention). + if (StreamingRetryHelper.isMaxAttemptsExhausted(retrySettings, completedAttempts)) { + return RetryDecision.retriesExhausted(error); + } + + Duration delay = computeNextRetryDelay(error, completedAttempts); + ApiException deadlineExceeded = + checkDeadlineExceeded(operationStartNanos, grpcContext, callOptionsDeadline, delay, error); + if (deadlineExceeded != null) { + return RetryDecision.retriesExhausted(deadlineExceeded); + } + + return RetryDecision.retry(delay); + } + + /** + * Returns a non-retryable {@link Status.Code#DEADLINE_EXCEEDED} {@link ApiException} if {@code + * totalTimeout}, {@code grpcContext} deadline, or {@code callOptionsDeadline} is already expired + * or would be exceeded after sleeping {@code additionalDelay}; otherwise returns {@code null}. + */ + @Nullable ApiException checkDeadlineExceeded( + long operationStartNanos, + Context grpcContext, + @Nullable Deadline callOptionsDeadline, + Duration additionalDelay, + @Nullable Throwable cause) { + Duration effectiveDelay = + additionalDelay != null && !additionalDelay.isNegative() ? additionalDelay : Duration.ZERO; + if (StreamingRetryHelper.isTotalTimeoutExceeded( + retrySettings, clock.nanoTime() - operationStartNanos, effectiveDelay)) { + return ApiExceptionFactory.createException( + "BatchWrite total timeout exceeded while retrying", + cause, + GrpcStatusCode.of(Status.Code.DEADLINE_EXCEEDED), + /* retryable= */ false); + } + + long additionalDelayNanos = StreamingRetryHelper.toSaturatedNanos(effectiveDelay); + Deadline contextDeadline = grpcContext.getDeadline(); + if (contextDeadline != null + && contextDeadline.timeRemaining(TimeUnit.NANOSECONDS) <= additionalDelayNanos) { + return ApiExceptionFactory.createException( + "BatchWrite context deadline exceeded while retrying", + cause, + GrpcStatusCode.of(Status.Code.DEADLINE_EXCEEDED), + /* retryable= */ false); + } + + if (callOptionsDeadline != null + && callOptionsDeadline.timeRemaining(TimeUnit.NANOSECONDS) <= additionalDelayNanos) { + return ApiExceptionFactory.createException( + "BatchWrite call deadline exceeded while retrying", + cause, + GrpcStatusCode.of(Status.Code.DEADLINE_EXCEEDED), + /* retryable= */ false); + } + + return null; + } + + @Nullable Duration computeAttemptRpcTimeout( + int zeroBasedAttemptNumber, @Nullable Duration explicitTimeout, long operationStartNanos) { + Duration configuredRpcTimeout = retrySettings.getInitialRpcTimeoutDuration(); + Duration effectiveRpcTimeout = explicitTimeout; + + if (effectiveRpcTimeout == null && isPositive(configuredRpcTimeout)) { + double multiplier = Math.max(1.0, retrySettings.getRpcTimeoutMultiplier()); + long initialRpcMillis = + StreamingRetryHelper.saturatedDurationMillis(configuredRpcTimeout, 0L, Long.MAX_VALUE); + double scaledMillis = initialRpcMillis * Math.pow(multiplier, zeroBasedAttemptNumber); + long maxMillis = + StreamingRetryHelper.saturatedDurationMillis( + retrySettings.getMaxRpcTimeoutDuration(), Long.MAX_VALUE, Long.MAX_VALUE); + effectiveRpcTimeout = Duration.ofMillis((long) Math.min(scaledMillis, maxMillis)); + } + + Duration totalTimeout = retrySettings.getTotalTimeoutDuration(); + if (isPositive(totalTimeout)) { + long elapsedMillis = + TimeUnit.NANOSECONDS.toMillis(Math.max(0L, clock.nanoTime() - operationStartNanos)); + long totalTimeoutMillis = + StreamingRetryHelper.saturatedDurationMillis(totalTimeout, 0L, Long.MAX_VALUE); + long remainingMillis = Math.max(1L, totalTimeoutMillis - elapsedMillis); + Duration remainingDuration = Duration.ofMillis(remainingMillis); + if (effectiveRpcTimeout == null || remainingDuration.compareTo(effectiveRpcTimeout) < 0) { + return remainingDuration; + } + } + return effectiveRpcTimeout; + } + + boolean isRetryable(Throwable error) { + if (retryableCodes.isEmpty()) { + return false; + } + if (error instanceof WatchdogTimeoutException) { + // Idle watchdog timeouts indicate an abandoned consumer and must never be retried; + // wait timeouts indicate a stalled server and are retryable. + return ((WatchdogTimeoutException) error).isRetryable(); + } + Code code = extractStatusCode(error); + if (code != null && retryableCodes.contains(code)) { + return true; + } + return error != null + && error.getMessage() != null + && retryableCodes.contains(Code.UNAVAILABLE) + && IsRetryableInternalError.INSTANCE.apply(error); + } + + Duration computeNextRetryDelay(Throwable error, int completedAttempts) { + return StreamingRetryHelper.computeRetryDelay( + retrySettings, error, completedAttempts, jitterRandom, Duration.ZERO); + } + + static @Nullable Code extractStatusCode(Throwable error) { + if (error instanceof ApiException) { + StatusCode statusCode = ((ApiException) error).getStatusCode(); + return statusCode != null ? statusCode.getCode() : null; + } + if (error instanceof StatusRuntimeException) { + return GrpcStatusCode.of(((StatusRuntimeException) error).getStatus().getCode()).getCode(); + } + if (error instanceof StatusException) { + return GrpcStatusCode.of(((StatusException) error).getStatus().getCode()).getCode(); + } + return null; + } + + private static boolean isPositive(@Nullable Duration duration) { + return duration != null && !duration.isZero() && !duration.isNegative(); + } + + static ApiException createContextCancellationException(Context ctx) { + Throwable cause = ctx.cancellationCause(); + Status.Code code = Status.Code.CANCELLED; + if (cause instanceof TimeoutException) { + code = Status.Code.DEADLINE_EXCEEDED; + } else if (cause != null + && Status.fromThrowable(cause).getCode() == Status.Code.DEADLINE_EXCEEDED) { + code = Status.Code.DEADLINE_EXCEEDED; + } + String message = + code == Status.Code.DEADLINE_EXCEEDED + ? "BatchWrite stream deadline exceeded" + : "BatchWrite stream cancelled by context"; + return ApiExceptionFactory.createException( + message, cause, GrpcStatusCode.of(code), /* retryable= */ false); + } +} diff --git a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpc.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpc.java index a6d5e3a1caf1..5e22cc22e7f2 100644 --- a/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpc.java +++ b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpc.java @@ -276,13 +276,14 @@ public class GapicSpannerRpc implements SpannerRpc { private static final CallOptions.Key BASE_CONTEXT_MARKER_KEY = CallOptions.Key.create("BASE_CONTEXT_MARKER_KEY"); - // Normalize the generated placeholder to the historical streaming resume policy. + // Normalize the generated placeholder to the historical streaming resume policy, while allowing + // server-supplied retry delays up to the standard 32s unary max retry delay. static final RetrySettings DEFAULT_STREAMING_RETRY_SETTINGS = RetrySettings.newBuilder() .setTotalTimeoutDuration(Duration.ZERO) .setMaxAttempts(0) .setInitialRetryDelayDuration(Duration.ofMillis(10)) - .setMaxRetryDelayDuration(Duration.ofMillis(1000)) + .setMaxRetryDelayDuration(Duration.ofSeconds(32)) .build(); /** Fallback states owned by this rpc, one per grpc-gcp pool. */ diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java new file mode 100644 index 000000000000..1139795d66fc --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java @@ -0,0 +1,1322 @@ +/* + * 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 com.google.cloud.spanner.AsyncResultSetImplTestUtil.executorProviderOf; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.sneakyThrow; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.api.core.ApiFuture; +import com.google.api.gax.core.ExecutorProvider; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.protobuf.Value; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for pause/resume races, cancellation concurrency, executor rejections, listener isolation, + * and supplier exception caching in {@link AsyncResultSetImpl}. + */ +@RunWith(JUnit4.class) +public class AsyncResultSetImplLifecycleAndConcurrencyTest { + private ExecutorProvider mockedProvider; + private SpannerOptions.CloseableExecutorProvider simpleProvider; + + @Before + public void setup() { + mockedProvider = executorProviderOf(mock(ScheduledExecutorService.class), false); + simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + } + + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testPollingResumeDuringConsumingDoesNotBypassCallbackPause() throws Exception { + // Callers that coordinate externally (such as ReadAsyncTest#pauseResume and + // AsyncResultSetImplTest#testCallbackIsNotCalledWhilePaused) poll resume() concurrently while + // cursorReady() is still executing in State.CONSUMING. Returning CallbackResponse.PAUSE must + // still transition the cursor to State.PAUSED rather than consuming a pre-pause resume() call. + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + List receivedIds = new ArrayList<>(); + AtomicInteger callbackInvocations = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(queuedProvider, stream.delegate, 10)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + int call = callbackInvocations.incrementAndGet(); + if (call == 1) { + // Simulate an external coordinator polling resume() while cursorReady() is in + // State.CONSUMING before returning PAUSE. + cursor.resume(); + assertEquals(CursorState.OK, cursor.tryNext()); + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.PAUSE; + } + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + stream.availableRows.set(2); + stream.emitEndOfStream(false); + queuedProvider.runNext(); // ProduceRowsRunnable -> buffers rows 1 & 2 + EOF + + assertEquals(Collections.singletonList(1L), receivedIds); + assertEquals(AsyncResultSetImpl.State.PAUSED, resultSet.getState()); + assertFalse(future.isDone()); + + resultSet.resume(); + assertTrue(future.isDone()); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + } + } + + @Test(timeout = 10_000) + public void testResumeImmediatelyUponEnteringPausedStateDoesNotLoseWakeup() throws Exception { + final int totalRows = 80; + final int maxBufferSize = 3; + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ExecutorService resumerExecutor = Executors.newFixedThreadPool(2); + ExecutorService streamFeederExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(totalRows); + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, maxBufferSize)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + resumerExecutor.execute( + () -> { + while (resultSet.getState() == AsyncResultSetImpl.State.CONSUMING) { + Thread.yield(); + } + resultSet.resume(); + }); + return CallbackResponse.PAUSE; + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + Future feederFuture = + streamFeederExecutor.submit( + () -> { + stream.awaitListener(); + for (int row = 1; row <= totalRows; row++) { + stream.availableRows.incrementAndGet(); + stream.emitFlushableChunk("r" + row, row % 4 == 0); + } + stream.emitEndOfStream(false); + return null; + }); + + feederFuture.get(5, TimeUnit.SECONDS); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(totalRows, receivedIds.size()); + for (int index = 0; index < totalRows; index++) { + assertEquals(Long.valueOf(index + 1L), receivedIds.get(index)); + } + } finally { + streamFeederExecutor.shutdownNow(); + resumerExecutor.shutdownNow(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testConcurrentStreamingPauseResumeWithSeededRandom() throws Exception { + final int totalRows = 150; + final int maxBufferSize = 4; + final Random random = new Random(42L); + ExecutorService callbackPool = Executors.newFixedThreadPool(2); + ExecutorService resumerExecutor = Executors.newSingleThreadExecutor(); + ExecutorService streamFeederExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(totalRows); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + AtomicBoolean currentlyPaused = new AtomicBoolean(false); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, maxBufferSize)) { + Executor notifyingCallbackExecutor = + command -> + callbackPool.execute( + () -> { + try { + command.run(); + } finally { + if (resultSet.getState() == AsyncResultSetImpl.State.PAUSED) { + resumerExecutor.execute( + () -> { + currentlyPaused.set(false); + resultSet.resume(); + }); + } + } + }); + + ApiFuture resultFuture = + resultSet.setCallback( + notifyingCallbackExecutor, + cursor -> { + assertFalse(currentlyPaused.get()); + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + if (random.nextInt(4) == 0) { + currentlyPaused.set(true); + return CallbackResponse.PAUSE; + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + Future feederFuture = + streamFeederExecutor.submit( + () -> { + AsyncResultSet.StreamMessageListener listener = stream.awaitListener(); + for (int row = 1; row <= totalRows; row++) { + listener.onStreamMessage( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue(String.valueOf(row))) + .build(), + false); + stream.availableRows.incrementAndGet(); + stream.emitFlushableChunk("r" + row, row % 3 == 0); + } + stream.emitEndOfStream(false); + return null; + }); + + feederFuture.get(5, TimeUnit.SECONDS); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(totalRows, receivedIds.size()); + for (int index = 0; index < totalRows; index++) { + assertEquals(Long.valueOf(index + 1L), receivedIds.get(index)); + } + } finally { + streamFeederExecutor.shutdownNow(); + resumerExecutor.shutdownNow(); + callbackPool.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringCallbackReturningDoneDoesNotReinvokeCallback() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch inDoneCallbackLatch = new CountDownLatch(1); + CountDownLatch allowDoneReturnLatch = new CountDownLatch(1); + AtomicInteger doneCallbackCount = new AtomicInteger(); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, false); + when(delegate.getCurrentRowAsStruct()).thenReturn(Struct.newBuilder().set("c").to(1L).build()); + + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + doneCallbackCount.incrementAndGet(); + assertEquals(CursorState.OK, cursor.tryNext()); + inDoneCallbackLatch.countDown(); + try { + assertTrue(allowDoneReturnLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + return CallbackResponse.DONE; + }); + assertTrue(inDoneCallbackLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); + assertThrows(IllegalStateException.class, resultSet::tryNext); + allowDoneReturnLatch.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, doneCallbackCount.get()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringCallbackReturningPauseOrContinueDeliversCancelledOnNextInvocation() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + try { + for (CallbackResponse firstResponse : + new CallbackResponse[] {CallbackResponse.PAUSE, CallbackResponse.CONTINUE}) { + CountDownLatch inFirstCallbackLatch = new CountDownLatch(1); + CountDownLatch allowFirstReturnLatch = new CountDownLatch(1); + AtomicInteger callbackCount = new AtomicInteger(); + AtomicBoolean observedCancelledInCallback = new AtomicBoolean(false); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, false); + when(delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("c").to(1L).build()); + + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + int call = callbackCount.incrementAndGet(); + if (call == 1) { + assertEquals(CursorState.OK, cursor.tryNext()); + inFirstCallbackLatch.countDown(); + try { + assertTrue(allowFirstReturnLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + return firstResponse; + } + try { + cursor.tryNext(); + } catch (SpannerException spannerException) { + if (spannerException.getErrorCode() == ErrorCode.CANCELLED) { + observedCancelledInCallback.set(true); + } + } + return CallbackResponse.CONTINUE; + }); + + assertTrue(inFirstCallbackLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); + allowFirstReturnLatch.countDown(); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, + ((SpannerException) executionException.getCause()).getErrorCode()); + assertTrue(observedCancelledInCallback.get()); + assertEquals(2, callbackCount.get()); + } + } + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelBeforeCallbackReturningContinueWithoutTryNextStopsAfterOneInvocation() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger noTryNextCallbackCount = new AtomicInteger(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + noTryNextCallbackCount.incrementAndGet(); + return CallbackResponse.CONTINUE; + }); + resultSet.cancel(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, noTryNextCallbackCount.get()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelBeforeInitiateStreamingRunsSkipsDelegateInitialization() throws Exception { + CountDownLatch blockerStartedLatch = new CountDownLatch(1); + CountDownLatch releaseBlockerLatch = new CountDownLatch(1); + Future blockerFuture = + simpleProvider + .getExecutor() + .submit( + () -> { + blockerStartedLatch.countDown(); + try { + releaseBlockerLatch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + }); + + assertTrue(blockerStartedLatch.await(5, TimeUnit.SECONDS)); + AtomicInteger supplierCalls = new AtomicInteger(); + AtomicInteger onStartOrCloseCalls = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + supplierCalls.incrementAndGet(); + return mock(ResultSet.class); + }, + 4, + onStartOrCloseCalls::incrementAndGet)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertThrows(IllegalStateException.class, cursor::getColumnCount); + SpannerException cancelled = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.CANCELLED, cancelled.getErrorCode()); + assertThrows(IllegalStateException.class, cursor::getColumnCount); + return CallbackResponse.DONE; + }); + resultSet.cancel(); + releaseBlockerLatch.countDown(); + blockerFuture.get(5, TimeUnit.SECONDS); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(0, supplierCalls.get()); + assertEquals(1, onStartOrCloseCalls.get()); + } + } + + @Test(timeout = 10_000) + public void testCancelDuringNonStreamingInitiateStreamingPreservesCancelledState() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + AtomicReference nonStreamingCancelHolder = new AtomicReference<>(); + ResultSet nonStreamingCancelDelegate = mock(ResultSet.class); + AsyncResultSetImpl nonStreamingCancelResultSet = + new AsyncResultSetImpl( + queuedProvider, + () -> { + nonStreamingCancelHolder.get().cancel(); + return nonStreamingCancelDelegate; + }, + 4); + nonStreamingCancelHolder.set(nonStreamingCancelResultSet); + try (AsyncResultSetImpl ignored = nonStreamingCancelResultSet) { + ApiFuture future = + nonStreamingCancelResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + ExecutionException cancelledExec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) cancelledExec.getCause()).getErrorCode()); + verify(nonStreamingCancelDelegate, never()).next(); + } + } + + @Test(timeout = 10_000) + public void testCancelRacingWithProducerWakeupExitsWithoutCallingNext() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate cancelRaceStream = new ControllableStreamingDelegate(1); + AtomicReference cancelRaceResultSetRef = new AtomicReference<>(); + AtomicInteger isDataAvailableCalls = new AtomicInteger(); + doAnswer( + invocation -> { + if (isDataAvailableCalls.incrementAndGet() == 2) { + cancelRaceStream.emitEndOfStream(true); + cancelRaceResultSetRef.get().cancel(); + } + return false; + }) + .when(cancelRaceStream.delegate) + .isDataAvailable(); + try (AsyncResultSetImpl cancelRaceResultSet = + new AsyncResultSetImpl(queuedProvider, cancelRaceStream.delegate, 4)) { + cancelRaceResultSetRef.set(cancelRaceResultSet); + ApiFuture future = + cancelRaceResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + cancelRaceStream.emitFlushableChunk("wake", false); + queuedProvider.runNext(); // ProduceRowsRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + ExecutionException cancelExec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.CANCELLED, ((SpannerException) cancelExec.getCause()).getErrorCode()); + verify(cancelRaceStream.delegate, never()).next(); + } + } + + @Test(timeout = 10_000) + public void testCallbackNullReturnAndUncaughtExceptionsOnCancel() { + ResultSet oneRowDelegate = mock(ResultSet.class); + when(oneRowDelegate.next()).thenReturn(true, false); + when(oneRowDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("c").to(1L).build()); + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, oneRowDelegate, 4)) { + ApiFuture future = + resultSet.setCallback(MoreExecutors.directExecutor(), cursor -> null); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNKNOWN, ((SpannerException) executionException.getCause()).getErrorCode()); + } + + StreamingResultSet cancelledStreamingDelegate = mock(StreamingResultSet.class); + when(cancelledStreamingDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + try (AsyncResultSetImpl uncaughtCancelledResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl customUserCancelledResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl customExceptionResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4); + AsyncResultSetImpl nonCancelledSpannerExceptionResultSet = + new AsyncResultSetImpl(simpleProvider, cancelledStreamingDelegate, 4)) { + ApiFuture uncaughtCancelledFuture = + uncaughtCancelledResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + uncaughtCancelledResultSet.cancel(); + ExecutionException cancelledException = + assertThrows( + ExecutionException.class, () -> uncaughtCancelledFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) cancelledException.getCause()).getErrorCode()); + + SpannerException userCustomCancelled = + SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "custom user cancel reason"); + ApiFuture userCancelledFuture = + customUserCancelledResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw userCustomCancelled; + }); + customUserCancelledResultSet.cancel(); + ExecutionException userCancelledExecutionException = + assertThrows( + ExecutionException.class, () -> userCancelledFuture.get(5, TimeUnit.SECONDS)); + assertSame(userCustomCancelled, userCancelledExecutionException.getCause()); + + ApiFuture customFuture = + customExceptionResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw new IllegalArgumentException("custom callback failure"); + }); + customExceptionResultSet.cancel(); + ExecutionException customException = + assertThrows(ExecutionException.class, () -> customFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNKNOWN, ((SpannerException) customException.getCause()).getErrorCode()); + assertTrue(customException.getCause().getMessage().contains("custom callback failure")); + + ApiFuture internalSpannerFuture = + nonCancelledSpannerExceptionResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.INTERNAL, "internal callback failure"); + }); + nonCancelledSpannerExceptionResultSet.cancel(); + ExecutionException internalException = + assertThrows( + ExecutionException.class, () -> internalSpannerFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INTERNAL, ((SpannerException) internalException.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testExecutorRejectionsAndListenerIsolation() { + AtomicInteger serviceExecuteCalls = new AtomicInteger(); + ScheduledExecutorService customService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + Runnable runnable = invocation.getArgument(0); + if (serviceExecuteCalls.incrementAndGet() == 1) { + runnable.run(); + return null; + } + throw new RejectedExecutionException("producer rejected on stream message"); + } + return null; + }); + ExecutorProvider rejectingProducerProvider = executorProviderOf(customService, true); + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + AtomicInteger listenerCalls = new AtomicInteger(); + try (AsyncResultSetImpl producerRejectedResultSet = + new AsyncResultSetImpl(rejectingProducerProvider, streamingDelegate, 4)) { + producerRejectedResultSet.addListener( + () -> { + listenerCalls.incrementAndGet(); + throw new RuntimeException("listener failure 1"); + }); + producerRejectedResultSet.addListener(listenerCalls::incrementAndGet); + ApiFuture future = + producerRejectedResultSet.setCallback( + MoreExecutors.directExecutor(), cursor -> CallbackResponse.DONE); + producerRejectedResultSet.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + ExecutionException rejectedException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertTrue(rejectedException.getCause() instanceof SpannerException); + assertEquals(2, listenerCalls.get()); + assertThrows( + IllegalStateException.class, () -> producerRejectedResultSet.addListener(() -> {})); + } + + Executor rejectingCallbackExecutor = + command -> { + throw new RejectedExecutionException("callback executor shut down"); + }; + ResultSet emptyDelegate = mock(ResultSet.class); + when(emptyDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl callbackRejectedResultSet = + new AsyncResultSetImpl(simpleProvider, emptyDelegate, 4)) { + ApiFuture future = + callbackRejectedResultSet.setCallback( + rejectingCallbackExecutor, cursor -> CallbackResponse.DONE); + ExecutionException callbackRejectedException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertTrue(callbackRejectedException.getCause() instanceof SpannerException); + verify(emptyDelegate).close(); + } + + ScheduledExecutorService nonAutoCloseRejectingService = mock(ScheduledExecutorService.class); + doThrow(new RejectedExecutionException("rejected")) + .when(nonAutoCloseRejectingService) + .execute(any(Runnable.class)); + ExecutorProvider nonAutoCloseProvider = executorProviderOf(nonAutoCloseRejectingService, false); + try (AsyncResultSetImpl rejectedNonAutoClose = + new AsyncResultSetImpl(nonAutoCloseProvider, mock(ResultSet.class), 4)) { + assertThrows( + RejectedExecutionException.class, + () -> + rejectedNonAutoClose.setCallback( + MoreExecutors.directExecutor(), cursor -> CallbackResponse.DONE)); + } + verify(nonAutoCloseRejectingService, never()).shutdown(); + } + + @Test(timeout = 10_000) + public void testListenerRemovalAndSwallowedDelegateCloseExceptions() throws Exception { + AtomicInteger removedListenerCalls = new AtomicInteger(); + AtomicInteger keptListenerCalls = new AtomicInteger(); + Runnable removedListener = removedListenerCalls::incrementAndGet; + Runnable keptListener = keptListenerCalls::incrementAndGet; + ResultSet emptySyncDelegate = mock(ResultSet.class); + when(emptySyncDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl listenerResultSet = + new AsyncResultSetImpl(simpleProvider, emptySyncDelegate, 4)) { + listenerResultSet.addListener(removedListener); + listenerResultSet.addListener(keptListener); + listenerResultSet.removeListener(removedListener); + assertEquals( + 0, + listenerResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS) + .size()); + assertEquals(0, removedListenerCalls.get()); + assertEquals(1, keptListenerCalls.get()); + } + + ResultSet throwingLazyDelegate = mock(ResultSet.class); + ResultSetMetadata expectedMetadata = ResultSetMetadata.getDefaultInstance(); + when(throwingLazyDelegate.getMetadata()).thenReturn(expectedMetadata); + doThrow(new RuntimeException("lazy close failure")).when(throwingLazyDelegate).close(); + AsyncResultSetImpl closedBeforeInitResultSet = + new AsyncResultSetImpl(mockedProvider, () -> throwingLazyDelegate, 4); + closedBeforeInitResultSet.close(); + assertSame(expectedMetadata, closedBeforeInitResultSet.getMetadata()); + + ResultSet throwingInitializedDelegate = mock(ResultSet.class); + doThrow(new RuntimeException("eager close failure")).when(throwingInitializedDelegate).close(); + AsyncResultSetImpl initializedThrowingCloseResultSet = + new AsyncResultSetImpl(mockedProvider, throwingInitializedDelegate, 4); + initializedThrowingCloseResultSet.close(); + verify(throwingInitializedDelegate).close(); + } + + @Test(timeout = 10_000) + public void testToListInterruptedAndCachedSupplierExceptions() { + StreamingResultSet stalledDelegate = mock(StreamingResultSet.class); + when(stalledDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + try (AsyncResultSetImpl stalledResultSet = + new AsyncResultSetImpl(simpleProvider, stalledDelegate, 4)) { + Thread.currentThread().interrupt(); + try { + SpannerException interruptedSpannerException = + assertThrows( + SpannerException.class, () -> stalledResultSet.toList(reader -> reader.getLong(0))); + assertEquals(ErrorCode.CANCELLED, interruptedSpannerException.getErrorCode()); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + } + + ScheduledExecutorService autoCloseService = mock(ScheduledExecutorService.class); + ExecutorProvider autoCloseProvider = executorProviderOf(autoCloseService, true); + AtomicInteger runtimeSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl runtimeSupplierResultSet = + new AsyncResultSetImpl( + autoCloseProvider, + () -> { + runtimeSupplierCalls.incrementAndGet(); + throw new IllegalStateException("runtime supplier failure"); + }, + 4)) { + assertThrows(IllegalStateException.class, runtimeSupplierResultSet::getMetadata); + assertThrows(IllegalStateException.class, runtimeSupplierResultSet::getStats); + assertEquals(1, runtimeSupplierCalls.get()); + } + verify(autoCloseService).shutdown(); + + AtomicInteger errorSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl errorSupplierResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + errorSupplierCalls.incrementAndGet(); + throw new AssertionError("fatal supplier error"); + }, + 4)) { + assertThrows(AssertionError.class, errorSupplierResultSet::getMetadata); + assertThrows(AssertionError.class, errorSupplierResultSet::getStats); + assertEquals(1, errorSupplierCalls.get()); + } + + AtomicInteger checkedSupplierCalls = new AtomicInteger(); + try (AsyncResultSetImpl checkedSupplierResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + checkedSupplierCalls.incrementAndGet(); + throw sneakyThrow(new IOException("checked supplier io failure")); + }, + 4)) { + assertThrows(SpannerException.class, checkedSupplierResultSet::getMetadata); + assertThrows(SpannerException.class, checkedSupplierResultSet::getStats); + assertEquals(1, checkedSupplierCalls.get()); + } + } + + @Test(timeout = 10_000) + public void testSetCallbackWithCallerRunsServiceDoesNotHoldMonitorDuringInitiateStreaming() + throws Exception { + ScheduledExecutorService callerRunsService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + Runnable runnable = invocation.getArgument(0); + runnable.run(); + } + return null; + }); + ExecutorProvider callerRunsProvider = executorProviderOf(callerRunsService, false); + + ExecutorService externalObserverExecutor = Executors.newSingleThreadExecutor(); + AtomicReference resultSetRef = new AtomicReference<>(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.isDataAvailable()).thenReturn(true); + when(streamingDelegate.next()).thenReturn(false); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + Future externalCall = + externalObserverExecutor.submit( + () -> { + assertEquals( + AsyncResultSetImpl.State.STREAMING_INITIALIZED, + resultSetRef.get().getState()); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return null; + }); + // If setCallback holds monitor across service.execute(...), externalCall deadlocks + // trying to acquire monitor in getState()/onStreamMessage() and times out here. + externalCall.get(1, TimeUnit.SECONDS); + return true; + }); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(callerRunsProvider, streamingDelegate, 4)) { + resultSetRef.set(resultSet); + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.DONE; + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + } finally { + externalObserverExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testSetCallbackConcurrentCancelBeforeRejectedExecutionRollsBackCleanly() { + for (boolean alsoCloseBeforeReject : new boolean[] {false, true}) { + AtomicReference resultSetRef = new AtomicReference<>(); + ScheduledExecutorService cancelThenRejectService = + mock( + ScheduledExecutorService.class, + invocation -> { + if ("execute".equals(invocation.getMethod().getName())) { + // Simulate another thread calling cancel() (and optionally close()) right after + // setCallback transitions to STREAMING_INITIALIZED and releases monitor, before + // service.execute() throws RejectedExecutionException. + resultSetRef.get().cancel(); + if (alsoCloseBeforeReject) { + resultSetRef.get().close(); + } + throw new RejectedExecutionException("rejected after concurrent cancel"); + } + return null; + }); + ExecutorProvider provider = executorProviderOf(cancelThenRejectService, true); + + AtomicInteger runningAsyncOperations = new AtomicInteger(); + AtomicInteger callbackCount = new AtomicInteger(); + ResultSet delegate = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(provider, delegate, 4)) { + resultSetRef.set(resultSet); + Runnable listener = runningAsyncOperations::decrementAndGet; + assertThrows( + RejectedExecutionException.class, + () -> { + // Mirror TransactionRunnerImpl.TransactionContextAsyncResultSetImpl.setCallback. + runningAsyncOperations.incrementAndGet(); + resultSet.addListener(listener); + try { + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + callbackCount.incrementAndGet(); + return CallbackResponse.DONE; + }); + } catch (Throwable throwable) { + resultSet.removeListener(listener); + runningAsyncOperations.decrementAndGet(); + throw throwable; + } + }); + assertEquals(0, runningAsyncOperations.get()); + assertEquals(0, callbackCount.get()); + assertEquals(AsyncResultSetImpl.State.INITIALIZED, resultSet.getState()); + verify(delegate).close(); + verify(cancelThenRejectService).shutdown(); + } + } + } + + @Test(timeout = 10_000) + public void testCancelDuringInitiateStreamingDefersCallbackUntilInitiateStreamingCompletes() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + CountDownLatch insideInitiateStreaming = new CountDownLatch(1); + CountDownLatch allowInitiateStreamingToFinish = new CountDownLatch(1); + Runnable enterDelegate = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + enterDelegate.run(); + try { + insideInitiateStreaming.countDown(); + assertTrue(allowInitiateStreamingToFinish.await(5, TimeUnit.SECONDS)); + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }); + when(streamingDelegate.getMetadata()) + .thenAnswer( + invocation -> { + enterDelegate.run(); + try { + return ResultSetMetadata.getDefaultInstance(); + } finally { + activeDelegateCalls.decrementAndGet(); + } + }); + + Runnable noopListener = () -> {}; + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + resultSet.addListener(noopListener); + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.getMetadata(); + assertThrows(SpannerException.class, cursor::tryNext); + return CallbackResponse.DONE; + }); + + assertTrue(insideInitiateStreaming.await(5, TimeUnit.SECONDS)); + // removeListener must reject removal while active and not closed. + assertThrows(IllegalStateException.class, () -> resultSet.removeListener(noopListener)); + + // Cancel while InitiateStreamingRunnable is still inside initiateStreaming(); flush + // callbackExecutor to prove ReadyCallback was NOT scheduled while initiatingStreaming=true. + resultSet.cancel(); + callbackExecutor.submit(() -> null).get(5, TimeUnit.SECONDS); + assertEquals(1, activeDelegateCalls.get()); + + allowInitiateStreamingToFinish.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + allowInitiateStreamingToFinish.countDown(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelledExceptionDoesNotLeakSuppressedExceptionsAcrossQueries() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet delegate1 = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet1 = new AsyncResultSetImpl(queuedProvider, delegate1, 4)) { + ApiFuture future1 = + resultSet1.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + try (AutoCloseable failingCloseable = + () -> { + throw new IOException("suppressed close failure"); + }) { + cursor.tryNext(); + } catch (Exception exception) { + // Also invoke cancel() a second time before rethrowing to ensure repeated + // cancel() calls keep the same per-instance cancelledException identity. + resultSet1.cancel(); + if (exception instanceof RuntimeException) { + throw (RuntimeException) exception; + } + throw new RuntimeException(exception); + } + return CallbackResponse.DONE; + }); + resultSet1.cancel(); + queuedProvider.runNext(); + ExecutionException exec1 = + assertThrows(ExecutionException.class, () -> future1.get(5, TimeUnit.SECONDS)); + SpannerException cancelled1 = (SpannerException) exec1.getCause(); + assertEquals(ErrorCode.CANCELLED, cancelled1.getErrorCode()); + assertEquals(1, cancelled1.getSuppressed().length); + } + + ResultSet delegate2 = mock(ResultSet.class); + try (AsyncResultSetImpl resultSet2 = new AsyncResultSetImpl(queuedProvider, delegate2, 4)) { + AtomicReference caughtInCallback = new AtomicReference<>(); + ApiFuture future2 = + resultSet2.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + caughtInCallback.set(thrown); + return CallbackResponse.DONE; + }); + resultSet2.cancel(); + queuedProvider.runNext(); + ExecutionException exec2 = + assertThrows(ExecutionException.class, () -> future2.get(5, TimeUnit.SECONDS)); + SpannerException cancelled2 = (SpannerException) exec2.getCause(); + assertEquals(ErrorCode.CANCELLED, cancelled2.getErrorCode()); + assertEquals(0, caughtInCallback.get().getSuppressed().length); + assertEquals(0, cancelled2.getSuppressed().length); + } + } + + @Test(timeout = 10_000) + public void testConcurrentLazySupplierFailureInvokesSupplierOnlyOnce() throws Exception { + SpannerException transientFailure = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "transient lazy supplier error"); + CountDownLatch firstThreadInSupplier = new CountDownLatch(1); + CountDownLatch allowSupplierToThrow = new CountDownLatch(1); + AtomicInteger supplierCalls = new AtomicInteger(); + ResultSet leakedSecondDelegate = mock(ResultSet.class); + + ExecutorService callerPool = Executors.newFixedThreadPool(2); + AtomicReference secondCallerThread = new AtomicReference<>(); + CountDownLatch secondCallerEntering = new CountDownLatch(1); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + int call = supplierCalls.incrementAndGet(); + if (call == 1) { + firstThreadInSupplier.countDown(); + try { + assertTrue(allowSupplierToThrow.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + throw transientFailure; + } + return leakedSecondDelegate; + }, + 4)) { + Future firstCall = + callerPool.submit(() -> assertThrows(SpannerException.class, resultSet::getMetadata)); + assertTrue(firstThreadInSupplier.await(5, TimeUnit.SECONDS)); + + Future secondCall = + callerPool.submit( + () -> { + secondCallerThread.set(Thread.currentThread()); + secondCallerEntering.countDown(); + return assertThrows(SpannerException.class, resultSet::getStats); + }); + assertTrue(secondCallerEntering.await(5, TimeUnit.SECONDS)); + while (secondCallerThread.get().getState() != Thread.State.BLOCKED && !secondCall.isDone()) { + Thread.yield(); + } + allowSupplierToThrow.countDown(); + + assertSame(transientFailure, firstCall.get(5, TimeUnit.SECONDS)); + assertSame(transientFailure, secondCall.get(5, TimeUnit.SECONDS)); + assertEquals(1, supplierCalls.get()); + } finally { + allowSupplierToThrow.countDown(); + callerPool.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testCancelWithUndeliveredProducerExceptionResolvesFutureAsCancelled() + throws Exception { + SpannerException unavailableException = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "stream broken on row 2"); + + // 1. Producer buffers row 1 and records UNAVAILABLE on row 2 while callback has not yet + // observed UNAVAILABLE. Calling cancel() must cause both tryNext() and the setCallback() future + // to report CANCELLED rather than mismatching (tryNext -> CANCELLED, future -> UNAVAILABLE). + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet failingRow2Delegate = mock(ResultSet.class); + when(failingRow2Delegate.next()).thenReturn(true).thenThrow(unavailableException); + when(failingRow2Delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + AtomicReference callbackObservedCode = new AtomicReference<>(); + + try (AsyncResultSetImpl preemptedResultSet = + new AsyncResultSetImpl(queuedProvider, failingRow2Delegate, 4)) { + Executor deferredCallbackExecutor = queuedProvider.tasks::addLast; + ApiFuture future = + preemptedResultSet.setCallback( + deferredCallbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackObservedCode.set(thrown.getErrorCode()); + return CallbackResponse.DONE; + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable: buffers row 1, sets executionException + preemptedResultSet.cancel(); + while (!queuedProvider.tasks.isEmpty()) { + queuedProvider.runNext(); + } + + assertEquals(ErrorCode.CANCELLED, callbackObservedCode.get()); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.CANCELLED, ((SpannerException) executionException.getCause()).getErrorCode()); + } + + // 2. Conversely, if tryNext() ALREADY delivered UNAVAILABLE before cancel() is invoked, the + // terminal UNAVAILABLE outcome was already observed and must be preserved on the future. + ResultSet alreadyDeliveredDelegate = mock(ResultSet.class); + when(alreadyDeliveredDelegate.next()).thenThrow(unavailableException); + try (AsyncResultSetImpl deliveredResultSet = + new AsyncResultSetImpl(simpleProvider, alreadyDeliveredDelegate, 4)) { + ApiFuture future = + deliveredResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + assertSame(unavailableException, thrown); + deliveredResultSet.cancel(); + return CallbackResponse.DONE; + }); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertSame(unavailableException, executionException.getCause()); + } + } + + @Test(timeout = 10_000) + public void testExternalThreadCannotReadActiveCallbackRow() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch positionedOnRowLatch = new CountDownLatch(1); + CountDownLatch releaseCallbackLatch = new CountDownLatch(1); + ResultSet singleRowDelegate = mock(ResultSet.class); + when(singleRowDelegate.next()).thenReturn(true, false); + when(singleRowDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(42L).build()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, singleRowDelegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + assertEquals(42L, cursor.getLong(0)); + positionedOnRowLatch.countDown(); + try { + assertTrue(releaseCallbackLatch.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + assertTrue(positionedOnRowLatch.await(5, TimeUnit.SECONDS)); + // Even while currentRow is non-null inside an active callback invocation, external threads + // must be rejected across column, schema, and Struct readers. + assertThrows(IllegalStateException.class, () -> resultSet.getLong(0)); + assertThrows(IllegalStateException.class, resultSet::getType); + assertThrows(IllegalStateException.class, resultSet::getCurrentRowAsStruct); + + releaseCallbackLatch.countDown(); + assertNull(future.get(5, TimeUnit.SECONDS)); + } finally { + releaseCallbackLatch.countDown(); + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testInitializedDelegateCachedOnlyAfterStartOrCloseCompletes() { + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, false); + when(delegate.getLong(0)).thenReturn(99L); + + AtomicReference resultSetRef = new AtomicReference<>(); + AtomicReference delegateDuringStartCallback = new AtomicReference<>(); + AtomicInteger onStartOrCloseCalls = new AtomicInteger(); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + mockedProvider, + () -> delegate, + 4, + () -> { + onStartOrCloseCalls.incrementAndGet(); + // initializedDelegate must still be null while onStartOrClose.run() is executing so + // concurrent callers cannot fast-path past getOrInitializeDelegate() before lifecycle + // notification completes. + delegateDuringStartCallback.set(resultSetRef.get().initializedDelegate); + })) { + resultSetRef.set(resultSet); + assertNull(resultSet.initializedDelegate); + + assertTrue(resultSet.next()); + assertEquals(1, onStartOrCloseCalls.get()); + assertNull(delegateDuringStartCallback.get()); + assertSame(delegate, resultSet.initializedDelegate); + + assertEquals(99L, resultSet.getLong(0)); + assertFalse(resultSet.next()); + assertEquals(1, onStartOrCloseCalls.get()); + assertSame(delegate, resultSet.initializedDelegate); + } + + // Failing supplier must leave initializedDelegate null while still running onStartOrClose once. + AtomicInteger failingStartCalls = new AtomicInteger(); + try (AsyncResultSetImpl failingResultSet = + new AsyncResultSetImpl( + mockedProvider, + () -> { + throw new IllegalStateException("supplier failed"); + }, + 4, + failingStartCalls::incrementAndGet)) { + assertThrows(IllegalStateException.class, failingResultSet::getMetadata); + assertNull(failingResultSet.initializedDelegate); + assertEquals(1, failingStartCalls.get()); + assertThrows(IllegalStateException.class, failingResultSet::getMetadata); + assertNull(failingResultSet.initializedDelegate); + assertEquals(1, failingStartCalls.get()); + } + } + + @Test(timeout = 60_000) + public void testCancelAfterCallbackDoneWhileProducerStillRunningPreservesDoneState() + throws Exception { + CountDownLatch producerInRow2Latch = new CountDownLatch(1); + CountDownLatch releaseProducerLatch = new CountDownLatch(1); + CountDownLatch callbackInvokedLatch = new CountDownLatch(1); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ResultSet slowRow2Delegate = mock(ResultSet.class); + AtomicInteger nextCalls = new AtomicInteger(); + when(slowRow2Delegate.next()) + .thenAnswer( + invocation -> { + if (nextCalls.incrementAndGet() == 1) { + return true; + } + producerInRow2Latch.countDown(); + assertTrue(releaseProducerLatch.await(30, TimeUnit.SECONDS)); + return false; + }); + when(slowRow2Delegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, slowRow2Delegate, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + callbackInvokedLatch.countDown(); + return CallbackResponse.DONE; + }); + + assertTrue(producerInRow2Latch.await(30, TimeUnit.SECONDS)); + assertTrue(callbackInvokedLatch.await(30, TimeUnit.SECONDS)); + callbackExecutor.submit(() -> null).get(30, TimeUnit.SECONDS); + + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + assertFalse(future.isDone()); + + resultSet.cancel(); + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + + releaseProducerLatch.countDown(); + assertNull(future.get(30, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.State.DONE, resultSet.getState()); + } finally { + releaseProducerLatch.countDown(); + callbackExecutor.shutdownNow(); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java new file mode 100644 index 000000000000..130da13d4ed2 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java @@ -0,0 +1,1363 @@ +/* + * 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 com.google.cloud.spanner.AsyncResultSetImplTestUtil.NO_OP_RESULT_SET_LISTENER; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.drainLongIdsCallback; +import static com.google.cloud.spanner.AsyncResultSetImplTestUtil.singleInt64MetadataChunk; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.api.core.ApiFuture; +import com.google.api.core.SettableApiFuture; +import com.google.cloud.spanner.AbstractResultSet.CloseableIterator; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.AbstractCloseableIterator; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.GrpcStreamingTestHarness; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.NoOpResultSetListener; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; +import com.google.common.base.Supplier; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.protobuf.ByteString; +import com.google.protobuf.Value; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Tests for event-driven streaming, non-blocking executor yielding, buffer hysteresis, and {@link + * GrpcResultSet} startup error translation in {@link AsyncResultSetImpl}. + */ +@RunWith(JUnit4.class) +public class AsyncResultSetImplStreamingTest { + private SpannerOptions.CloseableExecutorProvider simpleProvider; + + @Before + public void setup() { + simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + } + + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testProducerYieldsSingleThreadExecutorWhenWaitingForStreamData() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(1); + CountDownLatch waitingForStreamDataLatch = new CountDownLatch(1); + CountDownLatch row1ConsumedLatch = new CountDownLatch(1); + doAnswer( + invocation -> { + if (stream.consumedRows.get() == 0) { + return stream.availableRows.get() > 0; + } + boolean available = stream.streamFinished.get(); + if (!available) { + waitingForStreamDataLatch.countDown(); + } + return available; + }) + .when(stream.delegate) + .isDataAvailable(); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + receivedIds.add(cursor.getLong(0)); + row1ConsumedLatch.countDown(); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + + AsyncResultSet.StreamMessageListener listener = + stream.awaitStreamingInitialized(simpleProvider); + verify(stream.delegate, times(1)).isDataAvailable(); + + // Non-flushable partial chunk before resumeToken/bufferFull must not start the producer. + listener.onStreamMessage( + PartialResultSet.newBuilder().addValues(Value.newBuilder().setStringValue("1")).build(), + false); + verify(stream.delegate, times(1)).isDataAvailable(); + + // Flushable chunk starts the producer, delivers row 1, then yields when !isDataAvailable(). + stream.availableRows.set(1); + stream.emitFlushableChunk("tok1", false); + assertTrue(row1ConsumedLatch.await(5, TimeUnit.SECONDS)); + assertTrue(waitingForStreamDataLatch.await(5, TimeUnit.SECONDS)); + + // Single-thread executor must be free while waiting for the next gRPC chunk. + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + + stream.emitEndOfStream(false); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Collections.singletonList(1L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testImmediateEndOfStreamInitiatesRowProduction() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet emptyDelegate = mock(StreamingResultSet.class); + when(emptyDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener emptyListener = invocation.getArgument(0); + emptyListener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return true; + }); + when(emptyDelegate.isDataAvailable()).thenReturn(true); + when(emptyDelegate.next()).thenReturn(false); + + try (AsyncResultSetImpl immediateEofResultSet = + new AsyncResultSetImpl(simpleProvider, emptyDelegate, 4)) { + ApiFuture emptyFuture = + immediateEofResultSet.setCallback( + callbackExecutor, + cursor -> { + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.DONE; + }); + assertNull(emptyFuture.get(5, TimeUnit.SECONDS)); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testProducerYieldsSingleThreadExecutorWhenBufferIsFullAndResumesOnTryNext() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int totalRows = 5; + final int maxBufferSize = 2; + AtomicInteger producedRows = new AtomicInteger(); + CountDownLatch bufferFilledLatch = new CountDownLatch(maxBufferSize); + CountDownLatch pausedCallbackLatch = new CountDownLatch(1); + + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenAnswer(invocation -> producedRows.incrementAndGet() <= totalRows); + when(delegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> { + long id = producedRows.get(); + bufferFilledLatch.countDown(); + return Struct.newBuilder().set("id").to(id).build(); + }); + + AtomicBoolean pauseOnFirstCall = new AtomicBoolean(true); + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, delegate, maxBufferSize)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + if (pauseOnFirstCall.compareAndSet(true, false)) { + pausedCallbackLatch.countDown(); + return CallbackResponse.PAUSE; + } + return drainLongIdsCallback(receivedIds).cursorReady(cursor); + }); + + assertTrue(pausedCallbackLatch.await(5, TimeUnit.SECONDS)); + callbackExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + assertTrue(bufferFilledLatch.await(5, TimeUnit.SECONDS)); + + // With buffer at capacity (2 rows), ProduceRowsRunnable returns without pinning the thread. + Future probeFuture = simpleProvider.getExecutor().submit(producedRows::get); + assertEquals(Integer.valueOf(maxBufferSize), probeFuture.get(5, TimeUnit.SECONDS)); + + resultSet.resume(); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L, 4L, 5L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testFastStreamMessageDuringInitiateStreamingDefersProducerWithoutLosingWakeup() + throws Exception { + SpannerOptions.CloseableExecutorProvider twoThreadProvider = + SpannerOptions.createAsyncExecutorProvider(2, 1L, TimeUnit.SECONDS); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicBoolean streamPublished = new AtomicBoolean(false); + AtomicInteger availabilityChecksWhileInitiating = new AtomicInteger(); + AtomicInteger rowIndex = new AtomicInteger(); + + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + assertTrue( + twoThreadProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertEquals(0, availabilityChecksWhileInitiating.get()); + streamPublished.set(true); + return true; + }); + when(streamingDelegate.isDataAvailable()) + .thenAnswer( + invocation -> { + boolean published = streamPublished.get(); + if (!published) { + availabilityChecksWhileInitiating.incrementAndGet(); + } + return published; + }); + when(streamingDelegate.next()).thenAnswer(invocation -> rowIndex.incrementAndGet() == 1); + when(streamingDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(42L).build()); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(twoThreadProvider, streamingDelegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback(callbackExecutor, drainLongIdsCallback(receivedIds)); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(0, availabilityChecksWhileInitiating.get()); + assertEquals(Collections.singletonList(42L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + twoThreadProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testCustomStreamingResultSetStartupFailureDoesNotCallNext() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet customFailingDelegate = mock(StreamingResultSet.class); + when(customFailingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenThrow( + SpannerExceptionFactory.newSpannerException( + ErrorCode.INVALID_ARGUMENT, "custom startup error")); + + try (AsyncResultSetImpl customFailingResultSet = + new AsyncResultSetImpl(simpleProvider, customFailingDelegate, 4)) { + ApiFuture customFailingFuture = + customFailingResultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + ExecutionException customExecutionException = + assertThrows( + ExecutionException.class, () -> customFailingFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INVALID_ARGUMENT, + ((SpannerException) customExecutionException.getCause()).getErrorCode()); + verify(customFailingDelegate, never()).next(); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testFastEndOfStreamBeforeGrpcInitiateStreamingThrowsPreservesSingleConsumer() { + SpannerOptions.CloseableExecutorProvider twoThreadProvider = + SpannerOptions.createAsyncExecutorProvider(2, 1L, TimeUnit.SECONDS); + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + Runnable enterDelegate = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + AbstractResultSet.Listener translatingListener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "translated startup error", exception); + } + }; + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming( + AsyncResultSet.StreamMessageListener streamMessageListener) { + enterDelegate.run(); + try { + streamMessageListener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + assertTrue( + twoThreadProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "raw startup error"); + } catch (InterruptedException | ExecutionException | TimeoutException exception) { + throw new RuntimeException(exception); + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + + @Override + public boolean isDataAvailable() { + enterDelegate.run(); + try { + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + + @Override + public boolean hasNext() { + enterDelegate.run(); + try { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.CANCELLED, "raw startup error"); + } finally { + activeDelegateCalls.decrementAndGet(); + } + } + }; + + try (AsyncResultSetImpl failingResultSet = + new AsyncResultSetImpl( + twoThreadProvider, () -> new GrpcResultSet(failingIterator, translatingListener), 4)) { + ApiFuture failingFuture = + failingResultSet.setCallback( + callbackExecutor, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> failingFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.ABORTED, ((SpannerException) executionException.getCause()).getErrorCode()); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + callbackExecutor.shutdownNow(); + twoThreadProvider.close(); + } + } + + @Test(timeout = 10_000) + public void testProducerWakeupInLoopAndInFinallyPreservesSingleConsumer() throws Exception { + ExecutorService callbackBackingExecutor = Executors.newSingleThreadExecutor(); + ExecutorService grpcDeliveryExecutor = Executors.newSingleThreadExecutor(); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + AtomicInteger activeDelegateCalls = new AtomicInteger(); + AtomicInteger maxConcurrentDelegateCalls = new AtomicInteger(); + AtomicInteger isDataAvailableCalls = new AtomicInteger(); + AtomicBoolean triggerFinallyWakeupOnCallbackSchedule = new AtomicBoolean(false); + + Runnable enterDelegateCall = + () -> { + int concurrent = activeDelegateCalls.incrementAndGet(); + maxConcurrentDelegateCalls.accumulateAndGet(concurrent, Math::max); + }; + + doAnswer( + invocation -> { + enterDelegateCall.run(); + try { + stream.listenerRef.set(invocation.getArgument(0)); + stream.listenerRegistered.countDown(); + return true; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .initiateStreaming(any(AsyncResultSet.StreamMessageListener.class)); + doAnswer( + invocation -> { + enterDelegateCall.run(); + int call = isDataAvailableCalls.incrementAndGet(); + try { + if (call == 1) { + return false; + } + if (call == 2) { + grpcDeliveryExecutor + .submit(() -> stream.emitFlushableChunk("tok2", false)) + .get(5, TimeUnit.SECONDS); + return false; + } + if (call == 3 || call == 4) { + return true; + } + if (call == 5) { + triggerFinallyWakeupOnCallbackSchedule.set(true); + return false; + } + return stream.streamFinished.get(); + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .isDataAvailable(); + doAnswer( + invocation -> { + enterDelegateCall.run(); + try { + return stream.consumedRows.incrementAndGet() <= 2; + } finally { + activeDelegateCalls.decrementAndGet(); + } + }) + .when(stream.delegate) + .next(); + + Executor hookingCallbackExecutor = + command -> { + if (triggerFinallyWakeupOnCallbackSchedule.compareAndSet(true, false)) { + stream.emitEndOfStream(false); + } + callbackBackingExecutor.execute(command); + }; + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, stream.delegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback(hookingCallbackExecutor, drainLongIdsCallback(receivedIds)); + + stream.awaitStreamingInitialized(simpleProvider); + stream.emitFlushableChunk("tok1", false); + + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + assertEquals(1, maxConcurrentDelegateCalls.get()); + } finally { + grpcDeliveryExecutor.shutdownNow(); + callbackBackingExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testIsDataAvailableFailurePropagatesThroughNextToCallbackAndResultFuture() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage(GrpcStreamIterator.END_OF_STREAM, false); + return true; + }); + when(streamingDelegate.isDataAvailable()) + .thenThrow(new IllegalStateException("unexpected availability failure")); + when(streamingDelegate.next()) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "stream broken")); + + AtomicReference callbackObservedException = new AtomicReference<>(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackObservedException.set(thrown); + throw thrown; + }); + + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> resultFuture.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAVAILABLE, ((SpannerException) executionException.getCause()).getErrorCode()); + assertNotNull(callbackObservedException.get()); + assertEquals(ErrorCode.UNAVAILABLE, callbackObservedException.get().getErrorCode()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testGrpcInitiateStreamingFailureTranslatesErrorViaListenerWithoutSecondRpc() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + SettableApiFuture transactionIdFuture = SettableApiFuture.create(); + List listenerEvents = Collections.synchronizedList(new ArrayList<>()); + AtomicInteger initiateStreamingCalls = new AtomicInteger(); + AtomicInteger hasNextCalls = new AtomicInteger(); + + AbstractResultSet.Listener listener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + listenerEvents.add("onError:" + withBeginTransaction); + SpannerException translated = + withBeginTransaction && exception.getErrorCode() == ErrorCode.CANCELLED + ? SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "Transaction was aborted", exception) + : exception; + if (withBeginTransaction && !transactionIdFuture.isDone()) { + transactionIdFuture.setException(translated); + } + return translated; + } + + @Override + public void onDone(boolean withBeginTransaction) { + listenerEvents.add("onDone:" + withBeginTransaction); + } + }; + + SpannerException startupException = + SpannerExceptionFactory.asSpannerException( + Status.CANCELLED.withDescription("Transaction was aborted").asRuntimeException()); + + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming( + AsyncResultSet.StreamMessageListener streamMessageListener) { + initiateStreamingCalls.incrementAndGet(); + throw startupException; + } + + @Override + public boolean isDataAvailable() { + return initiateStreamingCalls.get() > 0; + } + + @Override + public boolean hasNext() { + hasNextCalls.incrementAndGet(); + throw startupException; + } + }; + + AtomicReference callbackException = new AtomicReference<>(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, () -> new GrpcResultSet(failingIterator, listener), 4)) { + ApiFuture resultFuture = + resultSet.setCallback( + callbackExecutor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + callbackException.set(thrown); + throw thrown; + }); + + ExecutionException futureExecutionException = + assertThrows(ExecutionException.class, () -> resultFuture.get(5, TimeUnit.SECONDS)); + SpannerException futureException = (SpannerException) futureExecutionException.getCause(); + assertEquals(ErrorCode.ABORTED, futureException.getErrorCode()); + assertNotNull(callbackException.get()); + assertEquals(ErrorCode.ABORTED, callbackException.get().getErrorCode()); + + ExecutionException txExecutionException = + assertThrows( + ExecutionException.class, () -> transactionIdFuture.get(5, TimeUnit.SECONDS)); + assertSame(futureException, txExecutionException.getCause()); + assertEquals(1, initiateStreamingCalls.get()); + assertEquals(1, hasNextCalls.get()); + assertEquals(Arrays.asList("onError:true", "onDone:true"), listenerEvents); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testForwardingResultSetWrappingNonStreamingResultSetDeliversRowsIncrementally() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + CountDownLatch allowRow2Latch = new CountDownLatch(1); + AtomicInteger nextCalls = new AtomicInteger(); + ResultSet blockingNonStreaming = mock(ResultSet.class); + when(blockingNonStreaming.next()) + .thenAnswer( + invocation -> { + int call = nextCalls.incrementAndGet(); + if (call == 1) { + return true; + } + if (call == 2) { + assertTrue(allowRow2Latch.await(5, TimeUnit.SECONDS)); + return true; + } + return false; + }); + when(blockingNonStreaming.getCurrentRowAsStruct()) + .thenAnswer(invocation -> Struct.newBuilder().set("id").to((long) nextCalls.get()).build()); + + List received = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl wrappedBlocking = + new AsyncResultSetImpl(simpleProvider, new ForwardingResultSet(blockingNonStreaming), 10)) { + ApiFuture future = + wrappedBlocking.setCallback( + callbackExecutor, + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + long id = cursor.getLong(0); + received.add(id); + if (id == 1L) { + allowRow2Latch.countDown(); + } + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), received); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testNonStreamingInlineCallbackPauseAndDoneStopsProducerImmediately() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + + // 1. Inline directExecutor() callback returning DONE after row 1 must stop ProduceRowsRunnable + // immediately without pulling row 2. + AtomicInteger doneNextCalls = new AtomicInteger(); + ResultSet doneDelegate = mock(ResultSet.class); + when(doneDelegate.next()).thenAnswer(invocation -> doneNextCalls.incrementAndGet() <= 3); + when(doneDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) doneNextCalls.get()).build()); + + try (AsyncResultSetImpl doneResultSet = + new AsyncResultSetImpl(queuedProvider, doneDelegate, 10)) { + ApiFuture doneFuture = + doneResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable + assertNull(doneFuture.get(5, TimeUnit.SECONDS)); + assertEquals(1, doneNextCalls.get()); + } + + // 2. Inline directExecutor() callback returning PAUSE after row 1 must stop ProduceRowsRunnable + // immediately until resume() is called. + AtomicInteger pauseNextCalls = new AtomicInteger(); + ResultSet pauseDelegate = mock(ResultSet.class); + when(pauseDelegate.next()).thenAnswer(invocation -> pauseNextCalls.incrementAndGet() <= 3); + when(pauseDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) pauseNextCalls.get()).build()); + + AtomicBoolean pauseOnFirstRow = new AtomicBoolean(true); + List receivedIds = new ArrayList<>(); + try (AsyncResultSetImpl pauseResultSet = + new AsyncResultSetImpl(queuedProvider, pauseDelegate, 10)) { + ApiFuture pauseFuture = + pauseResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + if (pauseOnFirstRow.compareAndSet(true, false)) { + assertEquals(CursorState.OK, cursor.tryNext()); + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.PAUSE; + } + return drainLongIdsCallback(receivedIds).cursorReady(cursor); + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable -> row 1 -> inline PAUSE -> breaks! + assertEquals(1, pauseNextCalls.get()); + assertEquals(AsyncResultSetImpl.State.PAUSED, pauseResultSet.getState()); + + pauseResultSet.resume(); + queuedProvider.runNext(); // ProduceRowsRunnable -> rows 2 and 3 + EOF + assertNull(pauseFuture.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L), receivedIds); + } + } + + @Test(timeout = 10_000) + public void testForwardingResultSetWrappingGrpcResultSetAndFailingLazySupplier() { + AbstractResultSet.Listener translatingListener = + new NoOpResultSetListener() { + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return SpannerExceptionFactory.newSpannerException( + ErrorCode.ABORTED, "wrapped grpc startup translated", exception); + } + }; + CloseableIterator failingIterator = + new AbstractCloseableIterator(true) { + @Override + public boolean initiateStreaming(AsyncResultSet.StreamMessageListener listener) { + throw new UnsupportedOperationException("grpc startup failed"); + } + + @Override + public boolean hasNext() { + throw SpannerExceptionFactory.newSpannerException(ErrorCode.CANCELLED, "raw cancelled"); + } + }; + ResultSet doubleWrappedGrpc = + new ForwardingResultSet( + new ForwardingResultSet(new GrpcResultSet(failingIterator, translatingListener))); + try (AsyncResultSetImpl wrappedGrpcResultSet = + new AsyncResultSetImpl(simpleProvider, doubleWrappedGrpc, 4)) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + wrappedGrpcResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.ABORTED, ((SpannerException) failure.getCause()).getErrorCode()); + } + + ForwardingResultSet brokenLazyWrapper = + new ForwardingResultSet( + (Supplier) + () -> { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAUTHENTICATED, "lazy delegate supplier failed"); + }); + try (AsyncResultSetImpl brokenWrapperResultSet = + new AsyncResultSetImpl(simpleProvider, brokenLazyWrapper, 4)) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + brokenWrapperResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAUTHENTICATED, ((SpannerException) failure.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testGrpcInitiateStreamingFailureEdgeCases() { + // mode 0: !isDataAvailable() preserves startup exception. + // mode 1: isDataAvailable() == true and next() genuinely returns false (valid metadata chunk + // followed by EOF) without throwing, preserving the original UNKNOWN startup exception. + // mode 2: cancel() during initiateStreaming() skips next() and completes with CANCELLED. + for (int mode = 0; mode < 3; mode++) { + final int currentMode = mode; + final AtomicBoolean metadataEmitted = new AtomicBoolean(false); + CloseableIterator iterator = + new AbstractCloseableIterator(false) { + @Override + public boolean isDataAvailable() { + return currentMode == 1; + } + + @Override + public boolean initiateStreaming(AsyncResultSet.StreamMessageListener listener) { + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNKNOWN, "startup failure " + currentMode); + } + + @Override + public boolean hasNext() { + return currentMode == 1 && !metadataEmitted.get(); + } + + @Override + public PartialResultSet next() { + if (currentMode == 1 && metadataEmitted.compareAndSet(false, true)) { + return singleInt64MetadataChunk(); + } + throw new NoSuchElementException(); + } + }; + GrpcResultSet grpcDelegate = new GrpcResultSet(iterator, NO_OP_RESULT_SET_LISTENER); + AtomicReference holder = new AtomicReference<>(); + AsyncResultSetImpl grpcAsyncResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + if (currentMode == 2) { + holder.get().cancel(); + } + return grpcDelegate; + }, + 4); + holder.set(grpcAsyncResultSet); + try (AsyncResultSetImpl ignored = grpcAsyncResultSet) { + ExecutionException failure = + assertThrows( + ExecutionException.class, + () -> + grpcAsyncResultSet + .toListAsync(reader -> reader.getLong(0), MoreExecutors.directExecutor()) + .get(5, TimeUnit.SECONDS)); + SpannerException cause = (SpannerException) failure.getCause(); + if (currentMode == 2) { + assertEquals(ErrorCode.CANCELLED, cause.getErrorCode()); + } else { + assertEquals(ErrorCode.UNKNOWN, cause.getErrorCode()); + assertTrue(cause.getMessage().contains("startup failure " + currentMode)); + } + } + } + } + + @Test(timeout = 10_000) + public void testBufferHysteresisPartialConsumptionDispatchesZeroExtraProducerTasks() + throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate partialStream = new ControllableStreamingDelegate(3); + List partialReceived = new ArrayList<>(); + try (AsyncResultSetImpl partialResultSet = + new AsyncResultSetImpl(queuedProvider, partialStream.delegate, 10)) { + ApiFuture future = + partialResultSet.setCallback( + MoreExecutors.directExecutor(), drainLongIdsCallback(partialReceived)); + + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + + partialStream.availableRows.set(3); + partialStream.emitFlushableChunk("chunk1", false); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // ProduceRowsRunnable + assertEquals(Arrays.asList(1L, 2L, 3L), partialReceived); + assertTrue(queuedProvider.tasks.isEmpty()); + + partialStream.emitEndOfStream(false); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); + assertNull(future.get(5, TimeUnit.SECONDS)); + } + } + + @Test(timeout = 10_000) + public void testBufferHysteresisBatchThresholdDispatchesSingleRefillTask() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ControllableStreamingDelegate batchStream = new ControllableStreamingDelegate(15); + List batchReceived = new ArrayList<>(); + AtomicBoolean pauseAfterEachRow = new AtomicBoolean(true); + try (AsyncResultSetImpl batchResultSet = + new AsyncResultSetImpl(queuedProvider, batchStream.delegate, 10)) { + ApiFuture future = + batchResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + batchReceived.add(cursor.getLong(0)); + if (pauseAfterEachRow.get()) { + return CallbackResponse.PAUSE; + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + assertTrue(queuedProvider.tasks.isEmpty()); + + batchStream.availableRows.set(15); + batchStream.emitEndOfStream(true); + assertEquals(1, queuedProvider.tasks.size()); + queuedProvider.runNext(); // ProduceRowsRunnable buffers 10 rows -> callback reads row 1 + assertEquals(10, batchStream.consumedRows.get()); + assertEquals(1, batchReceived.size()); + assertTrue(queuedProvider.tasks.isEmpty()); + + // Incoming stream message while waitingForBufferSpace is true schedules 0 tasks. + batchStream.emitEndOfStream(true); + assertTrue(queuedProvider.tasks.isEmpty()); + + for (int expectedConsumed = 2; expectedConsumed <= 5; expectedConsumed++) { + batchResultSet.resume(); + assertEquals(expectedConsumed, batchReceived.size()); + assertTrue(queuedProvider.tasks.isEmpty()); + } + + pauseAfterEachRow.set(false); + batchResultSet.resume(); + assertEquals(10, batchReceived.size()); + assertEquals(1, queuedProvider.tasks.size()); + + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(15, batchReceived.size()); + } + } + + @Test(timeout = 10_000) + public void testPreClosedStreamingDelegateCompletesWhenDataImmediatelyAvailable() { + StreamingResultSet preClosedStreamingDelegate = mock(StreamingResultSet.class); + when(preClosedStreamingDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenReturn(true); + when(preClosedStreamingDelegate.isDataAvailable()).thenReturn(true); + when(preClosedStreamingDelegate.next()).thenReturn(false); + try (AsyncResultSetImpl preClosedResultSet = + new AsyncResultSetImpl(simpleProvider, preClosedStreamingDelegate, 4)) { + assertTrue(preClosedResultSet.toList(reader -> reader.getLong(0)).isEmpty()); + } + } + + @Test(timeout = 10_000) + public void testMidStreamErrorReinvokesCallbackAfterPartialConsumption() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet oneRowThenErrorDelegate = mock(ResultSet.class); + when(oneRowThenErrorDelegate.next()) + .thenReturn(true) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "mid-stream fail")); + when(oneRowThenErrorDelegate.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(1L).build()); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl midStreamErrorResultSet = + new AsyncResultSetImpl(queuedProvider, oneRowThenErrorDelegate, 4)) { + AtomicInteger callbackInvocations = new AtomicInteger(); + ApiFuture future = + midStreamErrorResultSet.setCallback( + gatedCallbacks::addLast, + cursor -> { + if (callbackInvocations.incrementAndGet() == 1) { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + return CallbackResponse.CONTINUE; + } + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertEquals(1, gatedCallbacks.size()); + gatedCallbacks.removeFirst().run(); + ExecutionException midStreamFailure = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.UNAVAILABLE, ((SpannerException) midStreamFailure.getCause()).getErrorCode()); + assertEquals(2, callbackInvocations.get()); + } + } + + @Test(timeout = 10_000) + public void testLateStreamMessageAfterInitiateStreamingFailureDoesNotClobberConsumingState() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + AtomicReference lateErrorListenerRef = + new AtomicReference<>(); + StreamingResultSet failingAfterRegisterDelegate = mock(StreamingResultSet.class); + when(failingAfterRegisterDelegate.initiateStreaming( + any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + lateErrorListenerRef.set(invocation.getArgument(0)); + throw SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "init failed after register"); + }); + BlockingDeque lateErrorCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl lateErrorResultSet = + new AsyncResultSetImpl(queuedProvider, failingAfterRegisterDelegate, 4)) { + ApiFuture future = + lateErrorResultSet.setCallback( + lateErrorCallbacks::addLast, + cursor -> { + cursor.tryNext(); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable -> catches error -> CONSUMING + assertEquals(AsyncResultSetImpl.State.CONSUMING, lateErrorResultSet.getState()); + lateErrorListenerRef.get().onStreamMessage(GrpcStreamIterator.END_OF_STREAM, true); + assertEquals(AsyncResultSetImpl.State.CONSUMING, lateErrorResultSet.getState()); + assertTrue(queuedProvider.tasks.isEmpty()); + lateErrorCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.UNAVAILABLE, ((SpannerException) exec.getCause()).getErrorCode()); + } + } + + @Test(timeout = 10_000) + public void testSingleRowPerCallbackContinueReachesDoneAfterLastBufferedRow() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + ResultSet twoRowDelegate = mock(ResultSet.class); + when(twoRowDelegate.next()).thenReturn(true, true, false); + when(twoRowDelegate.getCurrentRowAsStruct()) + .thenReturn( + Struct.newBuilder().set("id").to(1L).build(), + Struct.newBuilder().set("id").to(2L).build()); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + List receivedIds = new ArrayList<>(); + AtomicInteger callbackInvocations = new AtomicInteger(); + try (AsyncResultSetImpl singleRowConsumerResultSet = + new AsyncResultSetImpl(queuedProvider, twoRowDelegate, 4)) { + ApiFuture future = + singleRowConsumerResultSet.setCallback( + gatedCallbacks::addLast, + cursor -> { + callbackInvocations.incrementAndGet(); + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + return CallbackResponse.CONTINUE; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + default: + throw new AssertionError("Unexpected CursorState"); + } + }); + // Run InitiateStreamingRunnable + ProduceRowsRunnable so both rows and finished=true are + // buffered before CallbackRunnable executes. + queuedProvider.runNext(); + queuedProvider.runNext(); + assertTrue(queuedProvider.tasks.isEmpty()); + assertEquals(1, gatedCallbacks.size()); + gatedCallbacks.removeFirst().run(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L), receivedIds); + assertEquals(3, callbackInvocations.get()); + } + } + + @Test(timeout = 10_000) + public void testStreamingFlushesWhenChunksWithoutResumeTokenExceedMaxBufferedChunks() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int maxBufferedChunks = 512; + final int prefetchChunks = 1000; + final int unflushedChunkCount = maxBufferedChunks + 1; + GrpcStreamingTestHarness harness = + new GrpcStreamingTestHarness(maxBufferedChunks, prefetchChunks); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch flushedBeforeEofLatch = new CountDownLatch(1); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 64)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + if (receivedIds.size() == unflushedChunkCount) { + flushedBeforeEofLatch.countDown(); + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + for (int chunkIndex = 1; chunkIndex <= unflushedChunkCount; chunkIndex++) { + PartialResultSet.Builder chunkBuilder = + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue(String.valueOf(chunkIndex))); + if (chunkIndex == 1) { + chunkBuilder.setMetadata(singleInt64MetadataChunk().getMetadata()); + } + grpcStream.consumer().onPartialResultSet(chunkBuilder.build()); + } + + // Even though no resumeToken arrived, bufferIsFull is false (513 < 1000), and the stream has + // not completed yet, ResumableStreamIterator has exceeded maxBufferedChunks (512) and all + // 513 rows must be flushed to the callback without stalling. + assertTrue(flushedBeforeEofLatch.await(2, TimeUnit.SECONDS)); + assertEquals(unflushedChunkCount, receivedIds.size()); + + grpcStream.consumer().onCompleted(); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(unflushedChunkCount, receivedIds.size()); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testLargeBufferSizeSchedulesCallbackAtDefaultBatchThresholdBeforeBlockingNext() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + AtomicInteger producedCount = new AtomicInteger(); + CountDownLatch firstBatchConsumedLatch = new CountDownLatch(1); + StreamingResultSet streamingDelegate = mock(StreamingResultSet.class); + when(streamingDelegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + AsyncResultSet.StreamMessageListener listener = invocation.getArgument(0); + listener.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + return true; + }); + when(streamingDelegate.isDataAvailable()).thenReturn(true); + when(streamingDelegate.next()) + .thenAnswer( + invocation -> { + int current = producedCount.incrementAndGet(); + if (current <= AsyncResultSetImpl.DEFAULT_BUFFER_SIZE) { + return true; + } + // Simulate row 11 blocking in mid-stream retry backoff; rows 1..10 must already have + // been dispatched to callbackExecutor even though maxBufferSize (100) is not full. + assertTrue(firstBatchConsumedLatch.await(2, TimeUnit.SECONDS)); + return false; + }); + when(streamingDelegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) producedCount.get()).build()); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(simpleProvider, streamingDelegate, 100)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedIds.add(cursor.getLong(0)); + if (receivedIds.size() == AsyncResultSetImpl.DEFAULT_BUFFER_SIZE) { + firstBatchConsumedLatch.countDown(); + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.DEFAULT_BUFFER_SIZE, receivedIds.size()); + assertEquals(Long.valueOf(1L), receivedIds.get(0)); + assertEquals(Long.valueOf(10L), receivedIds.get(9)); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testChunkedStringValueSplitAcrossChunksYieldsAndMergesCleanly() throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + GrpcStreamingTestHarness harness = new GrpcStreamingTestHarness(16, 8); + ResultSetMetadata stringColumnMetadata = + ResultSetMetadata.newBuilder() + .setRowType( + Type.struct(Type.StructField.of("payload", Type.string())) + .toProto() + .getStructType()) + .build(); + + List receivedValues = Collections.synchronizedList(new ArrayList<>()); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 4)) { + ApiFuture future = + resultSet.setCallback( + callbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + receivedValues.add(cursor.getString(0)); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + + // Deliver chunk 1 with chunked_value=true and a resume token: ProduceRowsRunnable wakes up, + // sees GrpcValueIterator#isDataAvailable() == false because the trailing string is still + // incomplete, and yields the single-thread executor cleanly without blocking. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .setMetadata(stringColumnMetadata) + .addValues(Value.newBuilder().setStringValue("hello-")) + .setChunkedValue(true) + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build()); + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertEquals(0, receivedValues.size()); + + // Deliver chunk 2 completing the split string, followed by end-of-stream. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("world")) + .setChunkedValue(false) + .setResumeToken(ByteString.copyFromUtf8("r2")) + .build()); + grpcStream.consumer().onCompleted(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Collections.singletonList("hello-world"), receivedValues); + } finally { + callbackExecutor.shutdownNow(); + } + } + + @Test(timeout = 10_000) + public void testPrefetchChunksReplenishmentDoesNotStallWhenEarlyChunksArriveDuringInitiation() + throws Exception { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); + final int prefetchChunks = 2; + // Deliver chunk 1 (without resumeToken) during startStream() before InitiateStreamingRunnable + // runs its initial isDataAvailable() check, so InitiateStreamingRunnable drains 1 chunk into + // ResumableStreamIterator.buffer and replenishes gRPC flow control via request(1). + GrpcStreamingTestHarness harness = + new GrpcStreamingTestHarness( + 512, + prefetchChunks, + grpcStream -> + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .setMetadata(singleInt64MetadataChunk().getMetadata()) + .addValues(Value.newBuilder().setStringValue("1")) + .build())); + + List receivedIds = Collections.synchronizedList(new ArrayList<>()); + try (GrpcResultSet grpcResultSet = harness.newGrpcResultSet(); + AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, grpcResultSet, 4)) { + ApiFuture future = + resultSet.setCallback(callbackExecutor, drainLongIdsCallback(receivedIds)); + + GrpcStreamIterator grpcStream = harness.awaitStreamingInitialized(simpleProvider); + verify(harness.streamingCall, times(1)).request(prefetchChunks); + verify(harness.streamingCall, times(1)).request(1); + + // Deliver prefetchChunks (2) more non-resume-token chunks: chunk 3 fills GrpcStreamIterator + // (bufferIsFull == true), flipping produceRowsInitiated = true and waking ProduceRowsRunnable + // to drain both chunks into ResumableStreamIterator.buffer and replenish request(1) twice. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("2")) + .build()); + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("3")) + .build()); + assertTrue(simpleProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + verify(harness.streamingCall, times(3)).request(1); + + // Deliver chunk 4 with a resume token + EOF and verify all 4 rows arrive in order. + grpcStream + .consumer() + .onPartialResultSet( + PartialResultSet.newBuilder() + .addValues(Value.newBuilder().setStringValue("4")) + .setResumeToken(ByteString.copyFromUtf8("r4")) + .build()); + grpcStream.consumer().onCompleted(); + + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(Arrays.asList(1L, 2L, 3L, 4L), receivedIds); + } finally { + callbackExecutor.shutdownNow(); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java index 13e4d784a589..372d0dfa6305 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -37,6 +38,8 @@ import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; import com.google.cloud.spanner.AsyncResultSet.CursorState; import com.google.cloud.spanner.AsyncResultSet.ReadyCallback; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.ControllableStreamingDelegate; +import com.google.cloud.spanner.AsyncResultSetImplTestUtil.QueuedExecutorProvider; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.collect.Range; @@ -46,6 +49,9 @@ import com.google.spanner.v1.PartialResultSet; import com.google.spanner.v1.ResultSetMetadata; import com.google.spanner.v1.ResultSetStats; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.CountDownLatch; @@ -59,18 +65,19 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.Mockito; +import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @RunWith(JUnit4.class) public class AsyncResultSetImplTest { private ExecutorProvider mockedProvider; - private ExecutorProvider simpleProvider; + private SpannerOptions.CloseableExecutorProvider simpleProvider; @Before public void setup() { @@ -79,6 +86,13 @@ public void setup() { simpleProvider = SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); } + @After + public void teardown() { + if (simpleProvider != null) { + simpleProvider.close(); + } + } + @SuppressWarnings("unchecked") @Test public void close() { @@ -399,44 +413,54 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { } } - @Test - public void testCallbackIsNotCalledWhilePausedAndCanceled() { + @Test(timeout = 10_000) + public void testCallbackIsNotCalledWhilePausedAndCanceled() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); final AtomicInteger callbackCounter = new AtomicInteger(); + final CountDownLatch pausedLatch = new CountDownLatch(1); ApiFuture callbackResult; - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenAnswer( answer -> { - rs.onStreamMessage(PartialResultSet.newBuilder().build(), false); - return null; + resultSet.onStreamMessage( + PartialResultSet.newBuilder() + .setResumeToken(ByteString.copyFromUtf8("r1")) + .build(), + false); + return Boolean.TRUE; }); + when(delegate.isDataAvailable()).thenReturn(true); callbackResult = - rs.setCallback( + resultSet.setCallback( executor, - resultSet -> { + cursor -> { callbackCounter.getAndIncrement(); + pausedLatch.countDown(); return CallbackResponse.PAUSE; }); - rs.cancel(); + assertTrue(pausedLatch.await(5, TimeUnit.SECONDS)); + resultSet.cancel(); SpannerException exception = assertThrows(SpannerException.class, () -> get(callbackResult)); assertEquals(ErrorCode.CANCELLED, exception.getErrorCode()); - assertEquals(1, callbackCounter.get()); + // 1 callback before cancel() returning PAUSE + 1 post-cancel callback given a chance to + // catch CANCELLED and stopping cleanly when it returns PAUSE without calling tryNext(). + assertEquals(2, callbackCounter.get()); } finally { - executor.shutdown(); + executor.shutdownNow(); } } - @Test + @Test(timeout = 10_000) public void cancel() throws InterruptedException { - Executor executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newSingleThreadExecutor(); ResultSet delegate = mock(ResultSet.class); when(delegate.next()).thenReturn(true, true, true, false); when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); @@ -485,12 +509,14 @@ public void cancel() throws InterruptedException { } assertThat(callbackCounter.get()).isIn(Range.closed(2, 4)); assertThat(rowCounter).isIn(Range.closed(2, 3)); + } finally { + executor.shutdownNow(); } } - @Test + @Test(timeout = 10_000) public void callbackReturnsError() throws InterruptedException { - Executor executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newSingleThreadExecutor(); ResultSet delegate = mock(ResultSet.class); when(delegate.next()).thenReturn(true, true, true, false); when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); @@ -509,6 +535,8 @@ public void callbackReturnsError() throws InterruptedException { assertThat(se.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN); assertThat(se.getMessage()).contains("async test"); assertThat(callbackCounter.get()).isEqualTo(1); + } finally { + executor.shutdownNow(); } } @@ -539,7 +567,7 @@ public void callbackReturnsErrorWhileBufferIsFull_shouldStopProducer() throws Ex assertThat(se.getErrorCode()).isEqualTo(ErrorCode.UNKNOWN); assertThat(se.getMessage()).contains("async test"); // The producer should stop and release the underlying result set. - Mockito.verify(delegate).close(); + verify(delegate).close(); assertThat(producedRows.get()).isLessThan(simulatedRows); } finally { executor.shutdown(); @@ -548,74 +576,97 @@ public void callbackReturnsErrorWhileBufferIsFull_shouldStopProducer() throws Ex @Test public void callbackReturnsDoneBeforeEnd_shouldStopIteration() throws Exception { - Executor executor = Executors.newSingleThreadExecutor(); - ResultSet delegate = mock(ResultSet.class); - when(delegate.next()).thenReturn(true, true, true, false); - when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); - try (AsyncResultSetImpl rs = - new AsyncResultSetImpl(simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { - rs.setCallback( - executor, - // Not calling resultSet.tryNext() means that it will also never return DONE. - // Instead the callback indicates that it does not want any more rows. - ignored -> CallbackResponse.DONE); - rs.getResult().get(10L, TimeUnit.SECONDS); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, true, false); + when(delegate.getCurrentRowAsStruct()).thenReturn(mock(Struct.class)); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl( + simpleProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { + resultSet.setCallback( + executor, + // Not calling resultSet.tryNext() means that it will also never return DONE. + // Instead the callback indicates that it does not want any more rows. + ignored -> CallbackResponse.DONE); + resultSet.getResult().get(10L, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); } } @Test public void testOnStreamMessageWhenResumeTokenIsPresent() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(mockedProvider.getExecutor(), times(1)).execute(runnableCaptor.capture()); + runnableCaptor.getValue().run(); + verify(mockedProvider.getExecutor(), times(1)).execute(any()); + + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), false); + verify(mockedProvider.getExecutor(), times(1)).execute(any()); - rs.onStreamMessage( + resultSet.onStreamMessage( PartialResultSet.newBuilder().setResumeToken(ByteString.copyFromUtf8("test")).build(), false); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + verify(mockedProvider.getExecutor(), times(2)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @Test public void testOnStreamMessageWhenCurrentBufferSizeReachedPrefetchChunkSize() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); + verify(mockedProvider.getExecutor(), times(1)).execute(runnableCaptor.capture()); + runnableCaptor.getValue().run(); + + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), true); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + verify(mockedProvider.getExecutor(), times(2)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @Test public void testOnStreamMessageWhenAsyncResultIsCancelled() { + ExecutorService callbackExecutor = Executors.newSingleThreadExecutor(); StreamingResultSet delegate = mock(StreamingResultSet.class); - try (AsyncResultSetImpl rs = + try (AsyncResultSetImpl resultSet = new AsyncResultSetImpl(mockedProvider, delegate, AsyncResultSetImpl.DEFAULT_BUFFER_SIZE)) { // Marking Streaming as supported - Mockito.when( - delegate.initiateStreaming(Mockito.any(AsyncResultSet.StreamMessageListener.class))) + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) .thenReturn(true); - rs.setCallback(Executors.newSingleThreadExecutor(), ignored -> CallbackResponse.DONE); - rs.cancel(); - rs.onStreamMessage( + resultSet.setCallback(callbackExecutor, ignored -> CallbackResponse.DONE); + resultSet.cancel(); + resultSet.onStreamMessage( PartialResultSet.newBuilder().addValues(Value.newBuilder().build()).build(), false); - Mockito.verify(mockedProvider.getExecutor(), times(2)).execute(Mockito.any()); + // Once cancelled, cancel() schedules the callback directly and incoming stream messages must + // not dispatch a wasted ProduceRowsRunnable onto the producer executor. + verify(mockedProvider.getExecutor(), times(1)).execute(any()); + } finally { + callbackExecutor.shutdownNow(); } } @@ -876,20 +927,19 @@ public void testOnStartOrCloseExceptionDoesNotMaskPrimaryException() { public void testSetCallbackRejectsNullArguments() { ResultSet delegate = mock(ResultSet.class); AtomicInteger count = new AtomicInteger(); - AsyncResultSetImpl asyncResultSet = - new AsyncResultSetImpl(simpleProvider, () -> delegate, 10, count::incrementAndGet); - - assertThrows( - NullPointerException.class, - () -> asyncResultSet.setCallback(null, ignored -> CallbackResponse.DONE)); - assertThrows( - NullPointerException.class, - () -> asyncResultSet.setCallback(MoreExecutors.directExecutor(), null)); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, () -> delegate, 10, count::incrementAndGet)) { + assertThrows( + NullPointerException.class, + () -> asyncResultSet.setCallback(null, ignored -> CallbackResponse.DONE)); + assertThrows( + NullPointerException.class, + () -> asyncResultSet.setCallback(MoreExecutors.directExecutor(), null)); - // Because arguments were null, setCallback failed before mutating state. - // The result set should still be closeable cleanly, notifying start or close once. - assertEquals(0, count.get()); - asyncResultSet.close(); + // Because arguments were null, setCallback failed before mutating state. + // The result set should still be closeable cleanly, notifying start or close once. + assertEquals(0, count.get()); + } assertEquals(1, count.get()); } @@ -902,22 +952,25 @@ public void testSetCallbackRejectedExecutionNotifiesStartOrClose() { when(provider.shouldAutoClose()).thenReturn(true); AtomicInteger count = new AtomicInteger(); - AsyncResultSetImpl asyncResultSet = - new AsyncResultSetImpl(provider, () -> mock(ResultSet.class), 10, count::incrementAndGet); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(provider, () -> mock(ResultSet.class), 10, count::incrementAndGet)) { + assertThrows( + RejectedExecutionException.class, + () -> + asyncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); - assertThrows( - RejectedExecutionException.class, - () -> - asyncResultSet.setCallback( - MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + // State is rolled back to INITIALIZED so cancel() and resume() reject calls cleanly. + assertThrows(IllegalStateException.class, asyncResultSet::cancel); + assertThrows(IllegalStateException.class, asyncResultSet::resume); - // Rejection should immediately trigger start or close notification so that callers - // waiting on query initialization are unblocked. - assertEquals(1, count.get()); - verify(mockService).shutdown(); + // Rejection should immediately trigger start or close notification so that callers + // waiting on query initialization are unblocked. + assertEquals(1, count.get()); + verify(mockService).shutdown(); + } // Closing afterwards is a no-op and does not notify a second time. - asyncResultSet.close(); assertEquals(1, count.get()); } @@ -949,13 +1002,15 @@ public void testSetCallbackRejectedExecutionClosesInitializedDelegate() { @Test public void testRemoveListenerAfterCloseDoesNotThrow() { ResultSet delegate = mock(ResultSet.class); - AsyncResultSetImpl asyncResultSet = new AsyncResultSetImpl(simpleProvider, () -> delegate, 10); Runnable listener = () -> {}; - asyncResultSet.addListener(listener); - asyncResultSet.close(); + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, () -> delegate, 10)) { + asyncResultSet.addListener(listener); + asyncResultSet.close(); - // Calling removeListener after close should not throw IllegalStateException - asyncResultSet.removeListener(listener); + // Calling removeListener after close should not throw IllegalStateException + asyncResultSet.removeListener(listener); + } } @Test @@ -970,4 +1025,498 @@ public void testToListAsyncRejectsNullArguments() { NullPointerException.class, () -> asyncResultSet.toListAsync(reader -> null, null)); } } + + private static void assertAllSchemaMethodsThrowIllegalState(StructReader reader) { + assertThrows(IllegalStateException.class, reader::getType); + assertThrows(IllegalStateException.class, reader::getColumnCount); + assertThrows(IllegalStateException.class, () -> reader.getColumnIndex("id")); + assertThrows(IllegalStateException.class, () -> reader.getColumnType(0)); + assertThrows(IllegalStateException.class, () -> reader.getColumnType("id")); + } + + @Test(timeout = 10_000) + public void testStaleCurrentRowClearedAcrossNotReadyPauseAndDone() throws Exception { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + Type rowSchema = Type.struct(Type.StructField.of("id", Type.int64())); + ControllableStreamingDelegate stream = new ControllableStreamingDelegate(2); + when(stream.delegate.getType()).thenReturn(rowSchema); + when(stream.delegate.getColumnCount()).thenReturn(1); + when(stream.delegate.getColumnIndex("id")).thenReturn(0); + when(stream.delegate.getColumnType(0)).thenReturn(Type.int64()); + when(stream.delegate.getColumnType("id")).thenReturn(Type.int64()); + + AtomicInteger callbackStep = new AtomicInteger(); + try (AsyncResultSetImpl resultSet = + new AsyncResultSetImpl(queuedProvider, stream.delegate, 10)) { + ApiFuture future = + resultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + int step = callbackStep.incrementAndGet(); + if (step == 1) { + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + assertEquals(1L, cursor.getCurrentRowAsStruct().getLong(0)); + assertEquals(rowSchema, cursor.getType()); + + // Next tryNext() returns NOT_READY: stale Row 1 must be cleared! + assertEquals(CursorState.NOT_READY, cursor.tryNext()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.CONTINUE; + } + if (step == 2) { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(2L, cursor.getLong(0)); + // Return PAUSE while still positioned on Row 2 (without calling tryNext() again). + return CallbackResponse.PAUSE; + } + // Step 3: resumed after PAUSE. Before calling tryNext(), stale Row 2 must be + // cleared even if stream already reached finished = true! + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + + assertEquals(CursorState.DONE, cursor.tryNext()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertEquals(rowSchema, cursor.getType()); + return CallbackResponse.DONE; + }); + + queuedProvider.runNext(); // InitiateStreamingRunnable + stream.availableRows.set(1); + stream.emitFlushableChunk("c1", false); + queuedProvider.runNext(); // ProduceRowsRunnable -> Row 1 + NOT_READY + + stream.availableRows.set(2); + stream.emitEndOfStream(false); + queuedProvider.runNext(); // ProduceRowsRunnable -> Row 2 + finished=true -> PAUSE + resultSet.resume(); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertEquals(3, callbackStep.get()); + } + } + + @Test(timeout = 10_000) + public void testSchemaMethodsOnDoneForMultiRowAndEmptyResultSets() throws Exception { + Type rowSchema = + Type.struct( + Type.StructField.of("id", Type.int64()), Type.StructField.of("name", Type.string())); + + // 1. Empty PrePopulatedResultSet (0 rows): on DONE, all schema methods (including returning + // null for getColumnType("nonexistent")) succeed while row value getters throw. + ResultSet zeroRowDelegate = ResultSets.forRows(rowSchema, Collections.emptyList()); + try (AsyncResultSetImpl zeroRowResultSet = + new AsyncResultSetImpl(simpleProvider, zeroRowDelegate, 4)) { + ApiFuture future = + zeroRowResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + assertAllSchemaMethodsThrowIllegalState(cursor); + assertEquals(CursorState.DONE, cursor.tryNext()); + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("id")); + assertEquals(1, cursor.getColumnIndex("name")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + assertNull(cursor.getColumnType("nonexistent")); + assertThrows( + IllegalArgumentException.class, () -> cursor.getColumnIndex("nonexistent")); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + return CallbackResponse.DONE; + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + assertAllSchemaMethodsThrowIllegalState(zeroRowResultSet); + } + + // 2. Multi-rowResultSet: on OK, schema methods read from currentRow without touching delegate + // schema methods; on DONE, schema methods delegate to underlying ResultSet. + ResultSet twoRowDelegate = + ResultSets.forRows( + rowSchema, + Arrays.asList( + Struct.newBuilder().set("id").to(10L).set("name").to("a").build(), + Struct.newBuilder().set("id").to(20L).set("name").to("b").build())); + try (AsyncResultSetImpl multiRowResultSet = + new AsyncResultSetImpl(simpleProvider, twoRowDelegate, 4)) { + ApiFuture future = + multiRowResultSet.setCallback( + MoreExecutors.directExecutor(), + cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("id")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + assertEquals(rowSchema, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(1, cursor.getColumnIndex("name")); + assertEquals(Type.int64(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType("name")); + assertNull(cursor.getColumnType("nonexistent")); + return CallbackResponse.DONE; + } + } + }); + assertNull(future.get(5, TimeUnit.SECONDS)); + } + } + + @Test(timeout = 10_000) + public void testStaleCurrentRowClearedOnCancelAndMidStreamError() { + QueuedExecutorProvider queuedProvider = new QueuedExecutorProvider(false); + Type rowSchema = Type.struct(Type.StructField.of("id", Type.int64())); + ResultSet twoRowSync = + ResultSets.forRows( + rowSchema, + Arrays.asList( + Struct.newBuilder().set("id").to(1L).build(), + Struct.newBuilder().set("id").to(2L).build())); + BlockingDeque gatedCallbacks = new LinkedBlockingDeque<>(); + try (AsyncResultSetImpl cancelAfterRow1 = + new AsyncResultSetImpl(queuedProvider, twoRowSync, 10)) { + ApiFuture future = + cancelAfterRow1.setCallback( + gatedCallbacks::addLast, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(1L, cursor.getLong(0)); + cancelAfterRow1.cancel(); + SpannerException cancelled = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.CANCELLED, cancelled.getErrorCode()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable (reads both rows + finished = true) + gatedCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.CANCELLED, ((SpannerException) exec.getCause()).getErrorCode()); + } + + ResultSet row1ThenError = mock(ResultSet.class); + when(row1ThenError.next()) + .thenReturn(true) + .thenThrow( + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "mid-stream boom")); + when(row1ThenError.getCurrentRowAsStruct()) + .thenReturn(Struct.newBuilder().set("id").to(9L).build()); + try (AsyncResultSetImpl errorAfterRow1 = + new AsyncResultSetImpl(queuedProvider, row1ThenError, 10)) { + ApiFuture future = + errorAfterRow1.setCallback( + gatedCallbacks::addLast, + cursor -> { + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(9L, cursor.getLong(0)); + SpannerException err = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.UNAVAILABLE, err.getErrorCode()); + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(cursor); + return CallbackResponse.DONE; + }); + queuedProvider.runNext(); // InitiateStreamingRunnable + queuedProvider.runNext(); // ProduceRowsRunnable (buffers row 1 + records UNAVAILABLE) + gatedCallbacks.removeFirst().run(); + ExecutionException exec = + assertThrows(ExecutionException.class, () -> future.get(5, TimeUnit.SECONDS)); + assertEquals(ErrorCode.UNAVAILABLE, ((SpannerException) exec.getCause()).getErrorCode()); + } + } + + @Test + public void testBigDecimalStateValidationAndDelegation() { + AtomicInteger unstartedSupplierCalls = new AtomicInteger(); + AsyncResultSetImpl closedBeforeStart = + new AsyncResultSetImpl( + simpleProvider, + () -> { + unstartedSupplierCalls.incrementAndGet(); + return mock(ResultSet.class); + }, + 4); + closedBeforeStart.close(); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimal(0)); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimal("n")); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimalList(0)); + assertThrows(IllegalStateException.class, () -> closedBeforeStart.getBigDecimalList("na")); + assertEquals(0, unstartedSupplierCalls.get()); + + BigDecimal expectedDecimal = new BigDecimal("12.34"); + List expectedDecimalList = Arrays.asList(expectedDecimal, new BigDecimal("56.78")); + Struct numericRow = + Struct.newBuilder() + .set("n") + .to(expectedDecimal) + .set("na") + .toNumericArray(expectedDecimalList) + .build(); + ResultSet numericDelegate = + ResultSets.forRows(numericRow.getType(), Collections.singletonList(numericRow)); + try (AsyncResultSetImpl numericResultSet = + new AsyncResultSetImpl(simpleProvider, numericDelegate, 4)) { + List results = + numericResultSet.toList( + reader -> { + assertEquals(expectedDecimal, reader.getBigDecimal(0)); + assertEquals(expectedDecimal, reader.getBigDecimal("n")); + assertEquals(expectedDecimalList, reader.getBigDecimalList(1)); + assertEquals(expectedDecimalList, reader.getBigDecimalList("na")); + return reader.getBigDecimal(0); + }); + assertEquals(Collections.singletonList(expectedDecimal), results); + } + } + + @Test + public void testSyncModeStateValidation() { + assertThrows( + IllegalArgumentException.class, + () -> new AsyncResultSetImpl(simpleProvider, mock(ResultSet.class), 0)); + + Type syncSchema = Type.struct(Type.StructField.of("id", Type.int64())); + Struct singleRow = Struct.newBuilder().set("id").to(7L).build(); + ResultSet syncDelegate = ResultSets.forRows(syncSchema, Collections.singletonList(singleRow)); + try (AsyncResultSetImpl syncResultSet = + new AsyncResultSetImpl(simpleProvider, syncDelegate, 4)) { + assertThrows(IllegalStateException.class, syncResultSet::tryNext); + assertThrows(IllegalStateException.class, syncResultSet::cancel); + assertThrows(IllegalStateException.class, syncResultSet::resume); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + assertAllSchemaMethodsThrowIllegalState(syncResultSet); + + assertTrue(syncResultSet.next()); + assertThrows(IllegalStateException.class, syncResultSet::cancel); + assertThrows(IllegalStateException.class, syncResultSet::resume); + assertThrows( + IllegalStateException.class, + () -> + syncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + assertEquals(7L, syncResultSet.getLong(0)); + assertEquals(singleRow, syncResultSet.getCurrentRowAsStruct()); + assertEquals(syncSchema, syncResultSet.getType()); + assertEquals(1, syncResultSet.getColumnCount()); + assertEquals(0, syncResultSet.getColumnIndex("id")); + assertEquals(Type.int64(), syncResultSet.getColumnType(0)); + assertEquals(Type.int64(), syncResultSet.getColumnType("id")); + + assertFalse(syncResultSet.next()); + assertEquals(syncSchema, syncResultSet.getType()); + assertEquals(1, syncResultSet.getColumnCount()); + assertEquals(0, syncResultSet.getColumnIndex("id")); + assertEquals(Type.int64(), syncResultSet.getColumnType(0)); + assertEquals(Type.int64(), syncResultSet.getColumnType("id")); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + + syncResultSet.close(); + assertThrows(IllegalStateException.class, () -> syncResultSet.getLong(0)); + assertAllSchemaMethodsThrowIllegalState(syncResultSet); + } + } + + @Test + public void testSyncModeTransientSupplierFailureCachesExceptionWithoutLeakingDelegate() { + SpannerException transientFailure = + SpannerExceptionFactory.newSpannerException( + ErrorCode.UNAVAILABLE, "transient supplier failure"); + AtomicInteger supplierCalls = new AtomicInteger(); + ResultSet leakedDelegate = mock(ResultSet.class); + + try (AsyncResultSetImpl syncResultSet = + new AsyncResultSetImpl( + simpleProvider, + () -> { + if (supplierCalls.incrementAndGet() == 1) { + throw transientFailure; + } + return leakedDelegate; + }, + 4)) { + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::next)); + assertEquals(1, supplierCalls.get()); + + // Every StructReader and schema/metadata method in SYNC mode must route through + // getOrInitializeDelegate(), rethrowing the cached supplierException without invoking the + // underlying Supplier a second time or leaking a newly created ResultSet. + assertSame( + transientFailure, assertThrows(SpannerException.class, () -> syncResultSet.getLong(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getString("id"))); + assertSame( + transientFailure, assertThrows(SpannerException.class, () -> syncResultSet.isNull(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getBigDecimal(0))); + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::getType)); + assertSame( + transientFailure, assertThrows(SpannerException.class, syncResultSet::getColumnCount)); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnIndex("id"))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnType(0))); + assertSame( + transientFailure, + assertThrows(SpannerException.class, () -> syncResultSet.getColumnType("id"))); + assertSame(transientFailure, assertThrows(SpannerException.class, syncResultSet::getStats)); + assertSame( + transientFailure, assertThrows(SpannerException.class, syncResultSet::getMetadata)); + assertEquals(1, supplierCalls.get()); + } + assertEquals(1, supplierCalls.get()); + } + + @Test + public void testSyncModeNextExceptionClearsStaleCurrentRow() { + Struct row1 = Struct.newBuilder().set("id").to(1L).build(); + SpannerException row2Failure = + SpannerExceptionFactory.newSpannerException(ErrorCode.UNAVAILABLE, "row 2 stream failure"); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true).thenThrow(row2Failure); + when(delegate.getCurrentRowAsStruct()).thenReturn(row1); + when(delegate.getLong(0)).thenReturn(1L).thenThrow(new IllegalStateException("invalid row")); + + try (AsyncResultSetImpl syncResultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + assertTrue(syncResultSet.next()); + assertEquals(1L, syncResultSet.getLong(0)); + assertEquals(row1, syncResultSet.getCurrentRowAsStruct()); + + assertSame(row2Failure, assertThrows(SpannerException.class, syncResultSet::next)); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> syncResultSet.getLong(0)); + } + } + + @Test(timeout = 10_000) + public void testExternalTryNextAndStructReaderRejectedAcrossAsyncStates() throws Exception { + Struct singleRow = Struct.newBuilder().set("id").to(7L).build(); + CountDownLatch callbackQueuedLatch = new CountDownLatch(1); + CountDownLatch releaseQueuedCallbackLatch = new CountDownLatch(1); + CountDownLatch pausedLatch = new CountDownLatch(1); + ExecutorService callbackBackingExecutor = Executors.newSingleThreadExecutor(); + Executor gatedCallbackExecutor = + command -> { + if (callbackQueuedLatch.getCount() > 0) { + callbackBackingExecutor.execute( + () -> { + callbackQueuedLatch.countDown(); + try { + releaseQueuedCallbackLatch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + return; + } + command.run(); + }); + } else { + callbackBackingExecutor.execute(command); + } + }; + + ResultSet asyncDelegate = mock(ResultSet.class); + when(asyncDelegate.next()).thenReturn(true, false); + when(asyncDelegate.getCurrentRowAsStruct()).thenReturn(singleRow); + AtomicInteger callbackInvocations = new AtomicInteger(); + + try (AsyncResultSetImpl asyncResultSet = + new AsyncResultSetImpl(simpleProvider, asyncDelegate, 4)) { + ApiFuture resultFuture = + asyncResultSet.setCallback( + gatedCallbackExecutor, + cursor -> { + int call = callbackInvocations.incrementAndGet(); + if (call == 1) { + assertThrows(IllegalStateException.class, () -> cursor.getLong(0)); + assertThrows(IllegalStateException.class, cursor::getCurrentRowAsStruct); + assertEquals(CursorState.OK, cursor.tryNext()); + assertEquals(7L, cursor.getLong(0)); + assertEquals(singleRow, cursor.getCurrentRowAsStruct()); + pausedLatch.countDown(); + return CallbackResponse.PAUSE; + } + assertEquals(CursorState.DONE, cursor.tryNext()); + return CallbackResponse.PAUSE; + }); + + assertThrows( + IllegalStateException.class, + () -> + asyncResultSet.setCallback( + MoreExecutors.directExecutor(), ignored -> CallbackResponse.DONE)); + assertThrows(IllegalStateException.class, asyncResultSet::next); + assertThrows(IllegalStateException.class, () -> asyncResultSet.removeListener(() -> {})); + + assertTrue(callbackQueuedLatch.await(5, TimeUnit.SECONDS)); + assertEquals(AsyncResultSetImpl.State.CONSUMING, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + assertThrows(IllegalStateException.class, () -> asyncResultSet.getLong(0)); + + releaseQueuedCallbackLatch.countDown(); + assertTrue(pausedLatch.await(5, TimeUnit.SECONDS)); + callbackBackingExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + + assertEquals(AsyncResultSetImpl.State.PAUSED, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + + asyncResultSet.resume(); + assertNull(resultFuture.get(5, TimeUnit.SECONDS)); + + assertEquals(AsyncResultSetImpl.State.DONE, asyncResultSet.getState()); + asyncResultSet.cancel(); + asyncResultSet.resume(); + assertEquals(AsyncResultSetImpl.State.DONE, asyncResultSet.getState()); + assertThrows(IllegalStateException.class, asyncResultSet::tryNext); + assertThrows(IllegalStateException.class, asyncResultSet::getCurrentRowAsStruct); + } finally { + callbackBackingExecutor.shutdownNow(); + } + } + + @Test + public void testSyncModeNextDoesNotCopyCurrentRowAsStructUnlessRequested() { + Struct row2Struct = Struct.newBuilder().set("id").to(20L).build(); + ResultSet delegate = mock(ResultSet.class); + when(delegate.next()).thenReturn(true, true, false); + when(delegate.getLong(0)).thenReturn(10L, 20L); + when(delegate.getCurrentRowAsStruct()).thenReturn(row2Struct); + + try (AsyncResultSetImpl syncResultSet = new AsyncResultSetImpl(simpleProvider, delegate, 4)) { + assertTrue(syncResultSet.next()); + assertEquals(10L, syncResultSet.getLong(0)); + verify(delegate, never()).getCurrentRowAsStruct(); + + assertTrue(syncResultSet.next()); + assertEquals(20L, syncResultSet.getLong(0)); + verify(delegate, never()).getCurrentRowAsStruct(); + assertSame(row2Struct, syncResultSet.getCurrentRowAsStruct()); + verify(delegate, times(1)).getCurrentRowAsStruct(); + + assertFalse(syncResultSet.next()); + assertThrows(IllegalStateException.class, syncResultSet::getCurrentRowAsStruct); + verify(delegate, times(1)).getCurrentRowAsStruct(); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java new file mode 100644 index 000000000000..c20d35cb1715 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java @@ -0,0 +1,298 @@ +/* + * 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.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.api.gax.core.ExecutorProvider; +import com.google.api.gax.retrying.RetrySettings; +import com.google.cloud.spanner.AbstractResultSet.CloseableIterator; +import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; +import com.google.cloud.spanner.AsyncResultSet.ReadyCallback; +import com.google.cloud.spanner.ErrorHandler.DefaultErrorHandler; +import com.google.cloud.spanner.XGoogSpannerRequestId.NoopRequestIdCreator; +import com.google.cloud.spanner.spi.v1.SpannerRpc; +import com.google.cloud.spanner.v1.stub.SpannerStubSettings; +import com.google.protobuf.ByteString; +import com.google.spanner.v1.MultiplexedSessionPrecommitToken; +import com.google.spanner.v1.PartialResultSet; +import com.google.spanner.v1.ResultSetMetadata; +import com.google.spanner.v1.Transaction; +import io.opencensus.trace.Tracing; +import io.opentelemetry.api.OpenTelemetry; +import java.time.Duration; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import org.jspecify.annotations.Nullable; + +/** Shared test fixtures for {@link AsyncResultSetImpl} unit tests. */ +final class AsyncResultSetImplTestUtil { + + static class NoOpResultSetListener implements AbstractResultSet.Listener { + @Override + public void onTransactionMetadata(Transaction transaction, boolean shouldIncludeId) {} + + @Override + public SpannerException onError( + SpannerException exception, boolean withBeginTransaction, boolean lastStatement) { + return exception; + } + + @Override + public void onDone(boolean withBeginTransaction) {} + + @Override + public void onPrecommitToken(MultiplexedSessionPrecommitToken token) {} + } + + static final AbstractResultSet.Listener NO_OP_RESULT_SET_LISTENER = new NoOpResultSetListener(); + + abstract static class AbstractCloseableIterator implements CloseableIterator { + private final boolean withBeginTransaction; + + AbstractCloseableIterator(boolean withBeginTransaction) { + this.withBeginTransaction = withBeginTransaction; + } + + @Override + public void close(@Nullable String message) {} + + @Override + public boolean isWithBeginTransaction() { + return withBeginTransaction; + } + + @Override + public boolean isLastStatement() { + return false; + } + + @Override + public PartialResultSet next() { + throw new NoSuchElementException(); + } + } + + static final class QueuedExecutorProvider implements ExecutorProvider { + final BlockingDeque tasks = new LinkedBlockingDeque<>(); + final ScheduledExecutorService service = mock(ScheduledExecutorService.class); + private final boolean autoClose; + + QueuedExecutorProvider(boolean autoClose) { + this.autoClose = autoClose; + doAnswer( + invocation -> { + tasks.addLast(invocation.getArgument(0)); + return null; + }) + .when(service) + .execute(any(Runnable.class)); + } + + @Override + public boolean shouldAutoClose() { + return autoClose; + } + + @Override + public ScheduledExecutorService getExecutor() { + return service; + } + + void runNext() { + tasks.removeFirst().run(); + } + } + + static final class ControllableStreamingDelegate { + final StreamingResultSet delegate = mock(StreamingResultSet.class); + final AtomicReference listenerRef = + new AtomicReference<>(); + final CountDownLatch listenerRegistered = new CountDownLatch(1); + final AtomicInteger availableRows = new AtomicInteger(); + final AtomicInteger consumedRows = new AtomicInteger(); + final AtomicBoolean streamFinished = new AtomicBoolean(); + + ControllableStreamingDelegate(int totalRows) { + when(delegate.initiateStreaming(any(AsyncResultSet.StreamMessageListener.class))) + .thenAnswer( + invocation -> { + listenerRef.set(invocation.getArgument(0)); + listenerRegistered.countDown(); + return true; + }); + when(delegate.isDataAvailable()) + .thenAnswer( + invocation -> streamFinished.get() || consumedRows.get() < availableRows.get()); + when(delegate.next()).thenAnswer(invocation -> consumedRows.incrementAndGet() <= totalRows); + when(delegate.getCurrentRowAsStruct()) + .thenAnswer( + invocation -> Struct.newBuilder().set("id").to((long) consumedRows.get()).build()); + } + + AsyncResultSet.StreamMessageListener awaitListener() throws InterruptedException { + assertTrue(listenerRegistered.await(5, TimeUnit.SECONDS)); + return listenerRef.get(); + } + + /** + * Waits until {@code initiateStreaming} has registered the listener AND {@code + * InitiateStreamingRunnable} has finished its initial availability check and yielded on {@code + * provider}'s single-thread executor. + */ + AsyncResultSet.StreamMessageListener awaitStreamingInitialized(ExecutorProvider provider) + throws Exception { + AsyncResultSet.StreamMessageListener listener = awaitListener(); + assertTrue(provider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + return listener; + } + + void emitFlushableChunk(String token, boolean bufferIsFull) { + listenerRef + .get() + .onStreamMessage( + PartialResultSet.newBuilder().setResumeToken(ByteString.copyFromUtf8(token)).build(), + bufferIsFull); + } + + void emitEndOfStream(boolean bufferIsFull) { + streamFinished.set(true); + listenerRef.get().onStreamMessage(GrpcStreamIterator.END_OF_STREAM, bufferIsFull); + } + } + + static final class GrpcStreamingTestHarness { + final SpannerRpc.StreamingCall streamingCall = mock(SpannerRpc.StreamingCall.class); + final ResumableStreamIterator resumableIterator; + private final AtomicReference grpcStreamRef = new AtomicReference<>(); + private final CountDownLatch streamStartedLatch = new CountDownLatch(1); + + GrpcStreamingTestHarness(int maxBufferSize, int prefetchChunks) { + this(maxBufferSize, prefetchChunks, ignored -> {}); + } + + GrpcStreamingTestHarness( + int maxBufferSize, int prefetchChunks, Consumer onStartStream) { + TraceWrapper tracer = + new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false); + ISpan parentSpan = tracer.spanBuilder("test"); + RetrySettings retrySettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(10)) + .setMaxRetryDelayDuration(Duration.ofMillis(100)) + .build(); + this.resumableIterator = + new ResumableStreamIterator( + maxBufferSize, + "query", + parentSpan, + tracer, + DefaultErrorHandler.INSTANCE, + retrySettings, + SpannerStubSettings.newBuilder().executeStreamingSqlSettings().getRetryableCodes(), + NoopRequestIdCreator.INSTANCE) { + @Override + CloseableIterator startStream( + ByteString resumeToken, + AsyncResultSet.StreamMessageListener streamMessageListener, + XGoogSpannerRequestId requestId) { + GrpcStreamIterator grpcStream = new GrpcStreamIterator(false, prefetchChunks, false); + if (streamMessageListener != null) { + grpcStream.registerListener(streamMessageListener); + } + grpcStream.setCall(streamingCall); + onStartStream.accept(grpcStream); + grpcStreamRef.set(grpcStream); + streamStartedLatch.countDown(); + return grpcStream; + } + }; + } + + GrpcResultSet newGrpcResultSet() { + return new GrpcResultSet(resumableIterator, NO_OP_RESULT_SET_LISTENER); + } + + GrpcStreamIterator awaitStreamingInitialized(ExecutorProvider provider) throws Exception { + assertTrue(streamStartedLatch.await(5, TimeUnit.SECONDS)); + assertTrue(provider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + GrpcStreamIterator grpcStream = grpcStreamRef.get(); + assertNotNull(grpcStream); + return grpcStream; + } + } + + static ExecutorProvider executorProviderOf(ScheduledExecutorService service, boolean autoClose) { + return new ExecutorProvider() { + @Override + public boolean shouldAutoClose() { + return autoClose; + } + + @Override + public ScheduledExecutorService getExecutor() { + return service; + } + }; + } + + static PartialResultSet singleInt64MetadataChunk() { + return PartialResultSet.newBuilder() + .setMetadata( + ResultSetMetadata.newBuilder() + .setRowType( + Type.struct(Type.StructField.of("id", Type.int64())).toProto().getStructType())) + .build(); + } + + static ReadyCallback drainLongIdsCallback(List sink) { + return cursor -> { + while (true) { + CursorState cursorState = cursor.tryNext(); + if (cursorState == CursorState.OK) { + sink.add(cursor.getLong(0)); + } else if (cursorState == CursorState.NOT_READY) { + return CallbackResponse.CONTINUE; + } else { + return CallbackResponse.DONE; + } + } + }; + } + + @SuppressWarnings("unchecked") + static RuntimeException sneakyThrow(Throwable throwable) throws E { + throw (E) throwable; + } + + private AsyncResultSetImplTestUtil() {} +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsBothSinksTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsBothSinksTest.java index e053dd22e7e5..e9ff9d3c999e 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsBothSinksTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsBothSinksTest.java @@ -18,6 +18,7 @@ import static com.google.common.truth.Truth.assertThat; +import com.google.auth.Credentials; import com.google.cloud.NoCredentials; import com.google.cloud.spanner.connection.AbstractMockServerTest; import io.grpc.ManagedChannelBuilder; @@ -55,12 +56,10 @@ public void enableCloudMonitoringGuard() { // created even though the client uses NoCredentials against the mock server. previousJmhEnabled = System.getProperty("jmh.enabled"); System.setProperty("jmh.enabled", "true"); - BuiltInMetricsProvider.INSTANCE.reset(); } @After public void restore() { - BuiltInMetricsProvider.INSTANCE.reset(); if (previousJmhEnabled == null) { System.clearProperty("jmh.enabled"); } else { @@ -84,16 +83,19 @@ private static OpenTelemetrySdk customOpenTelemetry(InMemoryMetricReader reader) return OpenTelemetrySdk.builder().setMeterProvider(meterProviderBuilder.build()).build(); } - private Spanner createSpanner(OpenTelemetry customSink) { - return SpannerOptions.newBuilder() - .setProjectId("my-project") - .setHost(String.format("http://localhost:%d", getPort())) - .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) - .setCredentials(NoCredentials.getInstance()) - .setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build()) - .setClientMetricsProvider(CustomOpenTelemetryMetricsProvider.create(customSink)) - .build() - .getService(); + private Spanner createSpanner(OpenTelemetry gcmSink, OpenTelemetry customSink) { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("my-project") + .setHost(String.format("http://localhost:%d", getPort())) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .setCredentials(NoCredentials.getInstance()) + .setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build()) + .setClientMetricsProvider(CustomOpenTelemetryMetricsProvider.create(customSink)) + .build(); + options.builtInMetricsProvider.setOpenTelemetry(gcmSink); + return options.getService(); } private static void executeSelect1(Spanner spanner) { @@ -122,25 +124,30 @@ private static long operationCount(InMemoryMetricReader reader, String meterName public void bothSinksRecordAppLayerMetricsInTheirOwnNamespaces() { InMemoryMetricReader gcmReader = InMemoryMetricReader.create(); InMemoryMetricReader customReader = InMemoryMetricReader.create(); - BuiltInMetricsProvider.INSTANCE.setOpenTelemetry(gcmOpenTelemetry(gcmReader)); - - try (Spanner spanner = createSpanner(customOpenTelemetry(customReader))) { - executeSelect1(spanner); - } - - // Both sinks recorded the operation, each in its own namespace. - assertThat(operationCount(gcmReader, BuiltInMetricsConstant.METER_NAME)).isGreaterThan(0L); - assertThat(operationCount(customReader, BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME)) - .isGreaterThan(0L); - - // No cross-contamination: the reserved names never land on the custom sink, and the custom - // names never land on the GCM sink. - for (MetricData metric : customReader.collectAllMetrics()) { - assertThat(metric.getName()).doesNotContain("spanner.googleapis.com"); - } - for (MetricData metric : gcmReader.collectAllMetrics()) { - assertThat(metric.getName()) - .doesNotContain(BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + "/"); + OpenTelemetrySdk gcmOtel = gcmOpenTelemetry(gcmReader); + OpenTelemetrySdk customOtel = customOpenTelemetry(customReader); + try { + try (Spanner spanner = createSpanner(gcmOtel, customOtel)) { + executeSelect1(spanner); + } + + // Both sinks recorded the operation, each in its own namespace. + assertThat(operationCount(gcmReader, BuiltInMetricsConstant.METER_NAME)).isGreaterThan(0L); + assertThat(operationCount(customReader, BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME)) + .isGreaterThan(0L); + + // No cross-contamination: the reserved names never land on the custom sink, and the custom + // names never land on the GCM sink. + for (MetricData metric : customReader.collectAllMetrics()) { + assertThat(metric.getName()).doesNotContain("spanner.googleapis.com"); + } + for (MetricData metric : gcmReader.collectAllMetrics()) { + assertThat(metric.getName()) + .doesNotContain(BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + "/"); + } + } finally { + gcmOtel.close(); + customOtel.close(); } } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsCustomOpenTelemetryTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsCustomOpenTelemetryTest.java index 0c9df7757cbf..a2a57a1ea825 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsCustomOpenTelemetryTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsCustomOpenTelemetryTest.java @@ -46,11 +46,8 @@ public class BuiltInMetricsCustomOpenTelemetryTest extends AbstractMockServerTes private static final Statement SELECT1 = Statement.of("SELECT 1"); @After - public void resetGcmSingleton() { - // A cloud custom+enabled client now also activates the Cloud Monitoring sink (additive - // semantics), which initializes the process-wide singleton via the gRPC layer. Reset it so the - // state does not leak into other tests sharing the JVM fork. - BuiltInMetricsProvider.INSTANCE.reset(); + public void resetEnvironment() { + SpannerOptions.useDefaultEnvironment(); } private Spanner createSpanner(MetricsProvider metricsProvider) { @@ -153,16 +150,120 @@ public void noMetricsAreRecordedForNoopProvider() { @Test public void gcmSingletonIsNotInitializedByCustomOnlyClient() { // With the Cloud Monitoring sink disabled, a custom-sink client must not create or modify the - // process-wide Cloud Monitoring OpenTelemetry singleton (custom sink only, no GCM). - BuiltInMetricsProvider.INSTANCE.reset(); + // Cloud Monitoring OpenTelemetry provider (custom sink only, no GCM). InMemoryMetricReader metricReader = InMemoryMetricReader.create(); - try (Spanner spanner = + SpannerOptions options = spannerBuilder(CustomOpenTelemetryMetricsProvider.create(createOpenTelemetry(metricReader))) .setBuiltInMetricsEnabled(false) - .build() - .getService()) { + .build(); + try (Spanner spanner = options.getService()) { executeSelect1(spanner); + assertNull(options.builtInMetricsProvider.getOpenTelemetry()); + } + } + + @Test + public void noCredentialsClientDoesNotInitializeGcmSingletonWithGrpcMetricsEnabled() { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + + try { + // Default provider with NoCredentials and built-in metrics enabled must not initialize GCM. + SpannerOptions defaultOptions = + spannerBuilder(DefaultMetricsProvider.INSTANCE) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + try (Spanner defaultSpanner = defaultOptions.getService()) { + executeSelect1(defaultSpanner); + assertNull(defaultOptions.builtInMetricsProvider.getOpenTelemetry()); + } + + // Custom provider with NoCredentials and built-in metrics enabled still records custom + // metrics while leaving the GCM provider uninitialized. + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); + try { + SpannerOptions customOptions = + spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + try (Spanner customSpanner = customOptions.getService()) { + executeSelect1(customSpanner); + assertNull(customOptions.builtInMetricsProvider.getOpenTelemetry()); + } + assertNotNull( + getMetric( + metricReader, + BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + + "/" + + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); + } finally { + customOpenTelemetry.close(); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void customHostDisablesGcmEndToEndWhileKeepingCustomSink() { + String previousJmhEnabled = System.getProperty("jmh.enabled"); + // Lift the NoCredentials guard (same pattern as BuiltInMetricsBothSinksTest) because gRPC + // rejects OAuth2 CallCredentials on a plaintext mock-server channel. + System.setProperty("jmh.enabled", "true"); + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("my-project") + .setEmulatorHost(null) + .setHost(String.format("http://localhost:%d", getPort())) + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .setCredentials(NoCredentials.getInstance()) + .setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build()) + .setClientMetricsProvider( + CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + .build(); + assertFalse(options.isEnableBuiltInMetrics()); + + try (Spanner spanner = options.getService()) { + executeSelect1(spanner); + // Even with the NoCredentials guard lifted and gRPC built-in metrics enabled, the custom + // host must NOT initialize the GCM provider. + assertNull(options.builtInMetricsProvider.getOpenTelemetry()); + assertNull(options.builtInMetricsProvider.getProjectId()); + } + + // Caller-owned CustomOpenTelemetryMetricsProvider still records metrics end-to-end. + assertNotNull( + getMetric( + metricReader, + BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + + "/" + + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); + } finally { + customOpenTelemetry.close(); + SpannerOptions.useDefaultEnvironment(); + if (previousJmhEnabled == null) { + System.clearProperty("jmh.enabled"); + } else { + System.setProperty("jmh.enabled", previousJmhEnabled); + } } - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsMultiClientMockServerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsMultiClientMockServerTest.java new file mode 100644 index 000000000000..6f2d0cd429fe --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsMultiClientMockServerTest.java @@ -0,0 +1,407 @@ +/* + * 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 static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.auth.Credentials; +import com.google.cloud.monitoring.v3.MetricServiceClient; +import com.google.cloud.monitoring.v3.MetricServiceSettings; +import com.google.cloud.spanner.connection.AbstractMockServerTest; +import com.google.common.base.Strings; +import com.google.monitoring.v3.CreateTimeSeriesRequest; +import com.google.monitoring.v3.MetricServiceGrpc.MetricServiceImplBase; +import com.google.monitoring.v3.TimeSeries; +import com.google.protobuf.Empty; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.StreamObserver; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * End-to-end mock-server tests verifying that multiple {@link Spanner} clients in the same JVM + * export built-in Cloud Monitoring metrics (including gRPC metrics and final close flushes) using + * isolated credentials, monitoring endpoints, universe domains, fallback projects, and {@code + * client_uid}s. + */ +@RunWith(JUnit4.class) +public class BuiltInMetricsMultiClientMockServerTest extends AbstractMockServerTest { + + @Test + public void testTwoClientsExportIsolatedMetricsAndFinalFlushPreservesFallbackProject() + throws Exception { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + try (MockMonitoringServer monitoringServerA = MockMonitoringServer.start(); + MockMonitoringServer monitoringServerB = MockMonitoringServer.start()) { + String hostA = "localhost:" + monitoringServerA.getPort(); + String hostB = "localhost:" + monitoringServerB.getPort(); + Credentials credentialsA = credentials("token-a", "universe-a.example"); + Credentials credentialsB = credentials("token-b", "universe-b.example"); + + PlaintextExporterMetricsProvider providerA = new PlaintextExporterMetricsProvider(); + PlaintextExporterMetricsProvider providerB = new PlaintextExporterMetricsProvider(); + + SpannerOptions optionsA = + newClientOptions("host-project-a", credentialsA, hostA, "universe-a.example", providerA); + SpannerOptions optionsB = + newClientOptions("host-project-b", credentialsB, hostB, "universe-b.example", providerB); + + Spanner spannerA = optionsA.getService(); + Spanner spannerB = optionsB.getService(); + try { + executeSelect1(spannerA, DatabaseId.of("db-project-a", "instance-a", "database-a")); + executeSelect1(spannerB, DatabaseId.of("db-project-b", "instance-b", "database-b")); + + // Closing Client A must flush Client A's metrics (including gRPC metrics using + // fallbackProjectId) to monitoringServerA without touching Client B. + spannerA.close(); + + assertEquals(hostA, providerA.recordedMonitoringHost); + assertEquals("universe-a.example", providerA.recordedUniverseDomain); + // closeInternal() already replaced the provider's AtomicReference with an empty one, + // while the closing exporter's final flush still read "db-project-a". + assertNull(providerA.getProjectId()); + + assertFalse(monitoringServerA.requests.isEmpty()); + assertEquals( + Collections.singleton("Bearer token-a"), + new HashSet<>(monitoringServerA.authorizationHeaders)); + assertAllRequestsBelongToProject(monitoringServerA.requests, "db-project-a"); + assertTrue( + hasMetricPrefix(monitoringServerA.requests, BuiltInMetricsConstant.METER_NAME + "/")); + assertTrue( + hasMetricPrefix( + monitoringServerA.requests, BuiltInMetricsConstant.METER_NAME + "/grpc/")); + String clientUidA = extractSingleClientUid(monitoringServerA.requests); + + assertTrue(monitoringServerB.requests.isEmpty()); + + spannerB.close(); + + assertEquals(hostB, providerB.recordedMonitoringHost); + assertEquals("universe-b.example", providerB.recordedUniverseDomain); + assertFalse(monitoringServerB.requests.isEmpty()); + assertEquals( + Collections.singleton("Bearer token-b"), + new HashSet<>(monitoringServerB.authorizationHeaders)); + assertAllRequestsBelongToProject(monitoringServerB.requests, "db-project-b"); + assertTrue( + hasMetricPrefix(monitoringServerB.requests, BuiltInMetricsConstant.METER_NAME + "/")); + assertTrue( + hasMetricPrefix( + monitoringServerB.requests, BuiltInMetricsConstant.METER_NAME + "/grpc/")); + String clientUidB = extractSingleClientUid(monitoringServerB.requests); + + assertNotEquals(clientUidA, clientUidB); + } finally { + if (!spannerA.isClosed()) { + spannerA.close(); + } + if (!spannerB.isClosed()) { + spannerB.close(); + } + providerA.reset(); + providerB.reset(); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testReusingSpannerOptionsFlushesSeparateUidsAndProjectsPerLifecycle() + throws Exception { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + try (MockMonitoringServer monitoringServer = MockMonitoringServer.start()) { + String monitoringHost = "localhost:" + monitoringServer.getPort(); + Credentials credentials = credentials("reuse-token", Credentials.GOOGLE_DEFAULT_UNIVERSE); + PlaintextExporterMetricsProvider provider = new PlaintextExporterMetricsProvider(); + SpannerOptions options = + newClientOptions( + "host-project", + credentials, + monitoringHost, + Credentials.GOOGLE_DEFAULT_UNIVERSE, + provider); + + try { + try (Spanner firstSpanner = options.getService()) { + executeSelect1(firstSpanner, DatabaseId.of("first-db-project", "i", "d")); + } + assertFalse(monitoringServer.requests.isEmpty()); + assertAllRequestsBelongToProject(monitoringServer.requests, "first-db-project"); + String firstUid = extractSingleClientUid(monitoringServer.requests); + + monitoringServer.requests.clear(); + monitoringServer.authorizationHeaders.clear(); + + try (Spanner secondSpanner = options.getService()) { + executeSelect1(secondSpanner, DatabaseId.of("second-db-project", "i", "d")); + } + assertFalse(monitoringServer.requests.isEmpty()); + assertAllRequestsBelongToProject(monitoringServer.requests, "second-db-project"); + String secondUid = extractSingleClientUid(monitoringServer.requests); + + assertNotEquals(firstUid, secondUid); + } finally { + provider.reset(); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + private static SpannerOptions newClientOptions( + String hostProjectId, + Credentials credentials, + String monitoringHost, + String universeDomain, + PlaintextExporterMetricsProvider provider) { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId(hostProjectId) + .setHost("http://localhost:" + getPort()) + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .setEmulatorHost(null) + .setCredentials(credentials) + .setUniverseDomain(universeDomain) + .setMonitoringHost(monitoringHost) + .setBuiltInMetricsEnabled(true) + .build(); + options.builtInMetricsProvider = provider; + return options; + } + + private static Credentials credentials(String tokenValue, String universeDomain) { + // Subclass Credentials directly rather than GoogleCredentials so gRPC allows sending the + // Authorization header over plaintext localhost mock-server channels. + return new Credentials() { + @Override + public String getAuthenticationType() { + return "Bearer"; + } + + @Override + public Map> getRequestMetadata(URI uri) { + return Collections.singletonMap( + "Authorization", Collections.singletonList("Bearer " + tokenValue)); + } + + @Override + public boolean hasRequestMetadata() { + return true; + } + + @Override + public boolean hasRequestMetadataOnly() { + return true; + } + + @Override + public void refresh() {} + + @Override + public String getUniverseDomain() { + return universeDomain; + } + }; + } + + private static void executeSelect1(Spanner spanner, DatabaseId databaseId) { + DatabaseClient databaseClient = spanner.getDatabaseClient(databaseId); + try (ResultSet resultSet = databaseClient.singleUse().executeQuery(SELECT1_STATEMENT)) { + assertTrue(resultSet.next()); + assertEquals(1L, resultSet.getLong(0)); + assertFalse(resultSet.next()); + } + } + + private static void assertAllRequestsBelongToProject( + List requests, String expectedProjectId) { + for (CreateTimeSeriesRequest request : requests) { + assertEquals("projects/" + expectedProjectId, request.getName()); + for (TimeSeries timeSeries : request.getTimeSeriesList()) { + assertEquals( + expectedProjectId, + timeSeries + .getResource() + .getLabelsMap() + .get(BuiltInMetricsConstant.PROJECT_ID_KEY.getKey())); + } + } + } + + private static boolean hasMetricPrefix( + List requests, String metricTypePrefix) { + for (CreateTimeSeriesRequest request : requests) { + for (TimeSeries timeSeries : request.getTimeSeriesList()) { + if (timeSeries.getMetric().getType().startsWith(metricTypePrefix)) { + return true; + } + } + } + return false; + } + + private static String extractSingleClientUid(List requests) { + Set clientUids = new HashSet<>(); + for (CreateTimeSeriesRequest request : requests) { + for (TimeSeries timeSeries : request.getTimeSeriesList()) { + String uid = + timeSeries + .getMetric() + .getLabelsMap() + .get(BuiltInMetricsConstant.CLIENT_UID_KEY.getKey()); + if (uid != null) { + clientUids.add(uid); + } + } + } + assertEquals(1, clientUids.size()); + return clientUids.iterator().next(); + } + + private static final class PlaintextExporterMetricsProvider extends BuiltInMetricsProvider { + private volatile String recordedMonitoringHost; + private volatile String recordedUniverseDomain; + + @Override + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) + throws IOException { + this.recordedMonitoringHost = monitoringHost; + this.recordedUniverseDomain = universeDomain; + MetricServiceSettings.Builder settingsBuilder = + MetricServiceSettings.newBuilder() + .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) + .setEndpoint(monitoringHost) + .setTransportChannelProvider( + InstantiatingGrpcChannelProvider.newBuilder() + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .build()); + if (!Strings.isNullOrEmpty(universeDomain)) { + settingsBuilder.setUniverseDomain(universeDomain); + } + return new SpannerCloudMonitoringExporter( + fallbackProjectIdSupplier, + clientAttributes, + MetricServiceClient.create(settingsBuilder.build())); + } + } + + private static final class MockMonitoringServer implements AutoCloseable { + private static final Metadata.Key AUTHORIZATION_HEADER = + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); + + private final Server server; + private final List requests; + private final List authorizationHeaders; + + private MockMonitoringServer( + Server server, List requests, List authorizationHeaders) { + this.server = server; + this.requests = requests; + this.authorizationHeaders = authorizationHeaders; + } + + static MockMonitoringServer start() throws IOException { + List requests = new CopyOnWriteArrayList<>(); + List authHeaders = new CopyOnWriteArrayList<>(); + Server grpcServer = + NettyServerBuilder.forAddress(new InetSocketAddress("localhost", 0)) + .addService( + new MetricServiceImplBase() { + @Override + public void createServiceTimeSeries( + CreateTimeSeriesRequest request, StreamObserver responseObserver) { + requests.add(request); + responseObserver.onNext(Empty.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + .intercept( + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + String authorization = headers.get(AUTHORIZATION_HEADER); + if (authorization != null) { + authHeaders.add(authorization); + } + return next.startCall(call, headers); + } + }) + .build() + .start(); + return new MockMonitoringServer(grpcServer, requests, authHeaders); + } + + int getPort() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + server.awaitTermination(5L, TimeUnit.SECONDS); + } + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInOpenTelemetryMetricsProviderTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInOpenTelemetryMetricsProviderTest.java index 9cbffdda1c0e..9ac102ef74f0 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInOpenTelemetryMetricsProviderTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInOpenTelemetryMetricsProviderTest.java @@ -17,14 +17,41 @@ package com.google.cloud.spanner; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; +import com.google.auth.Credentials; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.OAuth2Credentials; +import com.google.cloud.spanner.spi.v1.SpannerRpc; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; import java.util.Date; -import org.junit.After; -import org.junit.Before; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import javax.annotation.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -32,16 +59,6 @@ @RunWith(JUnit4.class) public class BuiltInOpenTelemetryMetricsProviderTest { - @Before - public void setUp() { - BuiltInMetricsProvider.INSTANCE.reset(); - } - - @After - public void tearDown() { - BuiltInMetricsProvider.INSTANCE.reset(); - } - @Test public void testGenerateClientHashWithSimpleUid() { String clientUid = "testClient"; @@ -75,29 +92,559 @@ public void testGenerateClientHashWithSpecialCharacters() { @Test public void testApiTracerFactoryDoesNotSetBuiltInMetricsProject() { SpannerOptions options = newTestOptions(); + try { + options.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); - options.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); - - assertNull(BuiltInMetricsProvider.INSTANCE.getProjectId()); + assertNull(options.builtInMetricsProvider.getProjectId()); + } finally { + options.builtInMetricsProvider.reset(); + } } @Test public void testBuiltInOpenTelemetryDoesNotSetMetricsProject() { SpannerOptions options = newTestOptions(); + try { + options.getBuiltInOpenTelemetry(); - options.getBuiltInOpenTelemetry(); - - assertNull(BuiltInMetricsProvider.INSTANCE.getProjectId()); + assertNull(options.builtInMetricsProvider.getProjectId()); + } finally { + options.builtInMetricsProvider.reset(); + } } @Test public void testInitializeBuiltInMetricsUsesDatabaseProject() { SpannerOptions options = newTestOptions(); + try { + options.initializeBuiltInMetrics(DatabaseId.of("database-project", "i", "d")); + options.initializeBuiltInMetrics(DatabaseId.of("other-project", "i", "d")); + + assertEquals("database-project", options.builtInMetricsProvider.getProjectId()); + } finally { + options.builtInMetricsProvider.reset(); + } + } + + @Test + public void testDifferentCredentialsUseIsolatedExporters() throws Exception { + Credentials credsA = + OAuth2Credentials.create(new AccessToken("token-a", new Date(Long.MAX_VALUE))); + Credentials credsB = + OAuth2Credentials.create(new AccessToken("token-b", new Date(Long.MAX_VALUE))); + SpannerOptions optionsA = newTestOptionsBuilder().setCredentials(credsA).build(); + SpannerOptions optionsB = newTestOptionsBuilder().setCredentials(credsB).build(); + assertNotSame(optionsA.builtInMetricsProvider, optionsB.builtInMetricsProvider); + + CapturingBuiltInMetricsProvider providerA = new CapturingBuiltInMetricsProvider(); + CapturingBuiltInMetricsProvider providerB = new CapturingBuiltInMetricsProvider(); + optionsA.builtInMetricsProvider = providerA; + optionsB.builtInMetricsProvider = providerB; + try { + OpenTelemetry otelA = optionsA.getBuiltInOpenTelemetry(); + OpenTelemetry otelB = optionsB.getBuiltInOpenTelemetry(); + assertNotNull(otelA); + assertNotNull(otelB); + assertNotSame(otelA, otelB); + + assertEquals(1, providerA.createdExporters.size()); + assertEquals(1, providerB.createdExporters.size()); + assertSame( + credsA, + providerA + .createdExporters + .get(0) + .getMetricServiceClient() + .getSettings() + .getCredentialsProvider() + .getCredentials()); + assertSame( + credsB, + providerB + .createdExporters + .get(0) + .getMetricServiceClient() + .getSettings() + .getCredentialsProvider() + .getCredentials()); + } finally { + providerA.reset(); + providerB.reset(); + } + } + + @Test + public void testDifferentMonitoringHostsUseIsolatedExporters() { + SpannerOptions optionsA = + newTestOptionsBuilder().setMonitoringHost("monitoring-a.example:443").build(); + SpannerOptions optionsB = + newTestOptionsBuilder().setMonitoringHost("monitoring-b.example:443").build(); + assertNotSame(optionsA.builtInMetricsProvider, optionsB.builtInMetricsProvider); + + CapturingBuiltInMetricsProvider providerA = new CapturingBuiltInMetricsProvider(); + CapturingBuiltInMetricsProvider providerB = new CapturingBuiltInMetricsProvider(); + optionsA.builtInMetricsProvider = providerA; + optionsB.builtInMetricsProvider = providerB; + try { + assertNotNull(optionsA.getBuiltInOpenTelemetry()); + assertNotNull(optionsB.getBuiltInOpenTelemetry()); + + assertEquals( + "monitoring-a.example:443", + providerA.createdExporters.get(0).getMetricServiceClient().getSettings().getEndpoint()); + assertEquals( + "monitoring-b.example:443", + providerB.createdExporters.get(0).getMetricServiceClient().getSettings().getEndpoint()); + } finally { + providerA.reset(); + providerB.reset(); + } + } + + @Test + public void testDifferentUniverseDomainsUseIsolatedExporters() { + SpannerOptions optionsA = + newTestOptionsBuilder().setUniverseDomain("universe-a.example").build(); + SpannerOptions optionsB = + newTestOptionsBuilder().setUniverseDomain("universe-b.example").build(); + assertNotSame(optionsA.builtInMetricsProvider, optionsB.builtInMetricsProvider); + + CapturingBuiltInMetricsProvider providerA = new CapturingBuiltInMetricsProvider(); + CapturingBuiltInMetricsProvider providerB = new CapturingBuiltInMetricsProvider(); + optionsA.builtInMetricsProvider = providerA; + optionsB.builtInMetricsProvider = providerB; + try { + assertNotNull(optionsA.getBuiltInOpenTelemetry()); + assertNotNull(optionsB.getBuiltInOpenTelemetry()); + + assertEquals( + "universe-a.example", + providerA + .createdExporters + .get(0) + .getMetricServiceClient() + .getSettings() + .getUniverseDomain()); + assertEquals( + "monitoring.universe-a.example:443", + providerA.createdExporters.get(0).getMetricServiceClient().getSettings().getEndpoint()); + assertEquals( + "universe-b.example", + providerB + .createdExporters + .get(0) + .getMetricServiceClient() + .getSettings() + .getUniverseDomain()); + assertEquals( + "monitoring.universe-b.example:443", + providerB.createdExporters.get(0).getMetricServiceClient().getSettings().getEndpoint()); + } finally { + providerA.reset(); + providerB.reset(); + } + } + + @Test + public void testDifferentClientsHaveIsolatedFallbackProjectAndClientUid() { + SpannerOptions optionsA = newTestOptions(); + SpannerOptions optionsB = newTestOptions(); + try { + optionsA.initializeBuiltInMetrics(DatabaseId.of("project-a", "i", "d")); + optionsB.initializeBuiltInMetrics(DatabaseId.of("project-b", "i", "d")); + + assertEquals("project-a", optionsA.builtInMetricsProvider.getProjectId()); + assertEquals("project-b", optionsB.builtInMetricsProvider.getProjectId()); + + String uidA = + optionsA + .builtInMetricsProvider + .createClientAttributes() + .get(BuiltInMetricsConstant.CLIENT_UID_KEY.getKey()); + String uidB = + optionsB + .builtInMetricsProvider + .createClientAttributes() + .get(BuiltInMetricsConstant.CLIENT_UID_KEY.getKey()); + assertNotNull(uidA); + assertNotNull(uidB); + assertNotEquals(uidA, uidB); + assertEquals( + BuiltInMetricsProvider.generateClientHash(uidA), + optionsA + .builtInMetricsProvider + .createResourceAttributes("project-a") + .get(BuiltInMetricsConstant.CLIENT_HASH_KEY)); + assertEquals( + BuiltInMetricsProvider.generateClientHash(uidB), + optionsB + .builtInMetricsProvider + .createResourceAttributes("project-b") + .get(BuiltInMetricsConstant.CLIENT_HASH_KEY)); + } finally { + optionsA.builtInMetricsProvider.reset(); + optionsB.builtInMetricsProvider.reset(); + } + } + + @Test + public void testSpannerCloseShutsDownOnlyClosedClientsExporterAndIsIdempotent() { + SpannerOptions optionsA = newTestOptions(); + SpannerOptions optionsB = newTestOptions(); + CapturingBuiltInMetricsProvider providerA = new CapturingBuiltInMetricsProvider(); + CapturingBuiltInMetricsProvider providerB = new CapturingBuiltInMetricsProvider(); + optionsA.builtInMetricsProvider = providerA; + optionsB.builtInMetricsProvider = providerB; + SpannerImpl spannerA = new SpannerImpl(mock(SpannerRpc.class), optionsA); + SpannerImpl spannerB = new SpannerImpl(mock(SpannerRpc.class), optionsB); + try { + assertNotNull(optionsA.getBuiltInOpenTelemetry()); + assertNotNull(optionsB.getBuiltInOpenTelemetry()); + SpannerCloudMonitoringExporter exporterA = providerA.createdExporters.get(0); + SpannerCloudMonitoringExporter exporterB = providerB.createdExporters.get(0); + assertTrue(providerA.hasShutdownHook()); + assertTrue(providerB.hasShutdownHook()); + assertFalse(exporterA.getMetricServiceClient().isShutdown()); + assertFalse(exporterB.getMetricServiceClient().isShutdown()); + + spannerA.close(); + + assertTrue(exporterA.getMetricServiceClient().isShutdown()); + assertFalse(providerA.hasShutdownHook()); + assertNull(providerA.getOpenTelemetry()); + assertFalse(exporterB.getMetricServiceClient().isShutdown()); + assertTrue(providerB.hasShutdownHook()); + assertNotNull(providerB.getOpenTelemetry()); + + // Closing the provider again is idempotent. + providerA.close(); + assertFalse(providerA.hasShutdownHook()); + } finally { + if (!spannerB.isClosed()) { + spannerB.close(); + } + providerA.reset(); + providerB.reset(); + } + assertTrue(providerB.createdExporters.get(0).getMetricServiceClient().isShutdown()); + assertFalse(providerB.hasShutdownHook()); + } + + @Test + public void testReuseSpannerOptionsAfterCloseCreatesFreshOpenTelemetry() { + SpannerOptions options = newTestOptions(); + CapturingBuiltInMetricsProvider provider = new CapturingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + try { + options.initializeBuiltInMetrics(DatabaseId.of("project-first", "i", "d")); + String firstUid = + provider.createClientAttributes().get(BuiltInMetricsConstant.CLIENT_UID_KEY.getKey()); + OpenTelemetry firstOtel = options.getBuiltInOpenTelemetry(); + assertNotNull(firstOtel); + SpannerCloudMonitoringExporter firstExporter = provider.createdExporters.get(0); + + new SpannerImpl(mock(SpannerRpc.class), options).close(); + + assertTrue(firstExporter.getMetricServiceClient().isShutdown()); + assertNull(provider.getProjectId()); + assertFalse(provider.hasShutdownHook()); + + options.initializeBuiltInMetrics(DatabaseId.of("project-second", "i", "d")); + String secondUid = + provider.createClientAttributes().get(BuiltInMetricsConstant.CLIENT_UID_KEY.getKey()); + OpenTelemetry secondOtel = options.getBuiltInOpenTelemetry(); + assertNotNull(secondOtel); + assertNotSame(firstOtel, secondOtel); + assertNotEquals(firstUid, secondUid); + assertEquals("project-second", provider.getProjectId()); + assertTrue(provider.hasShutdownHook()); + assertFalse(provider.createdExporters.get(1).getMetricServiceClient().isShutdown()); + } finally { + provider.reset(); + } + } + + @Test + public void testToBuilderCreatesIsolatedBuiltInMetricsProvider() { + SpannerOptions optionsA = newTestOptions(); + SpannerOptions optionsB = optionsA.toBuilder().build(); + try { + assertNotSame(optionsA.builtInMetricsProvider, optionsB.builtInMetricsProvider); + optionsA.initializeBuiltInMetrics(DatabaseId.of("project-a", "i", "d")); + assertEquals("project-a", optionsA.builtInMetricsProvider.getProjectId()); + assertNull(optionsB.builtInMetricsProvider.getProjectId()); + } finally { + optionsA.builtInMetricsProvider.reset(); + optionsB.builtInMetricsProvider.reset(); + } + } + + @Test + public void testConcurrentCloseWaitsForInLockCreationAndShutsDownCreatedProvider() + throws Exception { + CountDownLatch exporterEntered = new CountDownLatch(1); + CountDownLatch allowExporterFinish = new CountDownLatch(1); + List createdExporters = new ArrayList<>(); + BuiltInMetricsProvider provider = + new BuiltInMetricsProvider() { + @Override + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) + throws IOException { + if (createdExporters.isEmpty()) { + exporterEntered.countDown(); + try { + assertTrue(allowExporterFinish.await(5L, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException(e); + } + } + SpannerCloudMonitoringExporter exporter = + (SpannerCloudMonitoringExporter) + super.createExporter( + fallbackProjectIdSupplier, + clientAttributes, + credentials, + monitoringHost, + universeDomain); + createdExporters.add(exporter); + return exporter; + } + }; + + Credentials creds = + OAuth2Credentials.create(new AccessToken("token", new Date(Long.MAX_VALUE))); + AtomicReference createdOtel = new AtomicReference<>(); + Thread creator = + new Thread( + () -> + createdOtel.set( + provider.getOrCreateOpenTelemetry("p", creds, null, "googleapis.com"))); + Thread closer = new Thread(provider::close); + try { + creator.start(); + assertTrue(exporterEntered.await(5L, TimeUnit.SECONDS)); + closer.start(); + long waitStart = System.nanoTime(); + while (closer.getState() != Thread.State.BLOCKED + && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - waitStart) < 5L) { + Thread.yield(); + } + assertEquals(Thread.State.BLOCKED, closer.getState()); + allowExporterFinish.countDown(); + creator.join(5000L); + closer.join(5000L); + assertFalse(creator.isAlive()); + assertFalse(closer.isAlive()); + assertNotNull(createdOtel.get()); + assertEquals(1, createdExporters.size()); + assertTrue(createdExporters.get(0).getMetricServiceClient().isShutdown()); + assertFalse(provider.hasShutdownHook()); + assertNull(provider.getOpenTelemetry()); + + OpenTelemetry reopened = + provider.getOrCreateOpenTelemetry("p", creds, null, "googleapis.com"); + assertNotNull(reopened); + assertNotSame(createdOtel.get(), reopened); + assertTrue(provider.hasShutdownHook()); + assertFalse(createdExporters.get(1).getMetricServiceClient().isShutdown()); + } finally { + allowExporterFinish.countDown(); + provider.reset(); + } + } + + @Test + public void testEnableGrpcMetricsNoOpsWhenExporterCreationThrowsIOException() { + BuiltInMetricsProvider provider = + new BuiltInMetricsProvider() { + @Override + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) + throws IOException { + throw new IOException("simulated exporter failure"); + } + }; + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder = + InstantiatingGrpcChannelProvider.newBuilder(); + Credentials creds = + OAuth2Credentials.create(new AccessToken("token", new Date(Long.MAX_VALUE))); + + provider.enableGrpcMetrics(channelProviderBuilder, "p", creds, null, "googleapis.com"); + assertNull(channelProviderBuilder.getChannelConfigurator()); + assertNull(provider.getOpenTelemetry()); + assertFalse(provider.hasShutdownHook()); + + provider.enableGrpcMetrics(channelProviderBuilder, null); + assertNull(channelProviderBuilder.getChannelConfigurator()); + } + + @Test + public void testInjectedOpenTelemetrySurvivesCloseAndClosesOnReset() { + BuiltInMetricsProvider provider = new BuiltInMetricsProvider(); + InMemoryMetricReader reader = InMemoryMetricReader.create(); + OpenTelemetrySdk injected = + OpenTelemetrySdk.builder() + .setMeterProvider(SdkMeterProvider.builder().registerMetricReader(reader).build()) + .build(); + try { + provider.setOpenTelemetry(injected); + injected.getMeter("test-meter").counterBuilder("test_counter").build().add(1L); + + provider.close(); + + assertNull(provider.getOpenTelemetry()); + assertFalse(reader.collectAllMetrics().isEmpty()); + + provider.setOpenTelemetry(injected); + provider.reset(); + + assertNull(provider.getOpenTelemetry()); + assertTrue(reader.collectAllMetrics().isEmpty()); + } finally { + injected.close(); + } + } + + @Test + public void testBoundedSpannerCloseReturnsWithinTimeoutWhenExporterBlocks() throws Exception { + CountDownLatch exportInvoked = new CountDownLatch(1); + CompletableResultCode blockingExportResult = new CompletableResultCode(); + CompletableResultCode blockingShutdownResult = new CompletableResultCode(); + MetricExporter blockingExporter = + new MetricExporter() { + @Override + public CompletableResultCode export(Collection metrics) { + exportInvoked.countDown(); + return blockingExportResult; + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return blockingShutdownResult; + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + }; + + SpannerOptions options = newTestOptions(); + BuiltInMetricsProvider provider = + new BuiltInMetricsProvider() { + @Override + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) { + return blockingExporter; + } + }; + options.builtInMetricsProvider = provider; + SpannerImpl spanner = new SpannerImpl(mock(SpannerRpc.class), options); + try { + OpenTelemetry otel = options.getBuiltInOpenTelemetry(); + assertNotNull(otel); + assertTrue(provider.hasShutdownHook()); + // Record a point so PeriodicMetricReader.shutdown() must invoke export(...) on final flush. + otel.getMeter(BuiltInMetricsConstant.METER_NAME) + .counterBuilder("test_counter") + .build() + .add(1L); + + long startNanos = System.nanoTime(); + spanner.close(200L, TimeUnit.MILLISECONDS); + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + + assertTrue( + "Expected final flush export to be invoked", exportInvoked.await(2L, TimeUnit.SECONDS)); + assertTrue( + "Expected bounded close to return within 2s, took " + elapsedMillis + "ms", + elapsedMillis < 2000L); + assertFalse(provider.hasShutdownHook()); + assertNull(provider.getOpenTelemetry()); + } finally { + blockingExportResult.succeed(); + blockingShutdownResult.succeed(); + provider.reset(); + } + } + + @Test + public void testConcurrentDetectClientLocationWaitsForFirstResolution() throws Exception { + BuiltInMetricsProvider.resetLocationForTesting(); + CountDownLatch resolverEntered = new CountDownLatch(1); + CountDownLatch allowResolve = new CountDownLatch(1); + CountDownLatch secondThreadStarted = new CountDownLatch(1); + AtomicInteger resolutionCalls = new AtomicInteger(); + AtomicReference firstResult = new AtomicReference<>(); + AtomicReference secondResult = new AtomicReference<>(); + + Thread firstThread = + new Thread( + () -> + firstResult.set( + BuiltInMetricsProvider.detectClientLocation( + () -> { + resolutionCalls.incrementAndGet(); + resolverEntered.countDown(); + try { + assertTrue(allowResolve.await(5L, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "us-central1"; + }))); + Thread secondThread = + new Thread( + () -> { + secondThreadStarted.countDown(); + secondResult.set( + BuiltInMetricsProvider.detectClientLocation(() -> "unexpected-fallback")); + }); + try { + firstThread.start(); + assertTrue(resolverEntered.await(5L, TimeUnit.SECONDS)); + + secondThread.start(); + assertTrue(secondThreadStarted.await(5L, TimeUnit.SECONDS)); + long waitStartNanos = System.nanoTime(); + while (secondThread.getState() != Thread.State.BLOCKED + && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - waitStartNanos) < 5L) { + Thread.yield(); + } + assertEquals(Thread.State.BLOCKED, secondThread.getState()); - options.initializeBuiltInMetrics(DatabaseId.of("database-project", "i", "d")); - options.initializeBuiltInMetrics(DatabaseId.of("other-project", "i", "d")); + allowResolve.countDown(); + firstThread.join(5000L); + secondThread.join(5000L); + assertFalse(firstThread.isAlive()); + assertFalse(secondThread.isAlive()); - assertEquals("database-project", BuiltInMetricsProvider.INSTANCE.getProjectId()); + assertEquals(1, resolutionCalls.get()); + assertEquals("us-central1", firstResult.get()); + assertEquals("us-central1", secondResult.get()); + } finally { + allowResolve.countDown(); + BuiltInMetricsProvider.resetLocationForTesting(); + } } private void verifyHash(String hash) { @@ -109,6 +656,10 @@ private void verifyHash(String hash) { } private SpannerOptions newTestOptions() { + return newTestOptionsBuilder().build(); + } + + private SpannerOptions.Builder newTestOptionsBuilder() { return SpannerOptions.newBuilder() .setProjectId("host-project") // The builder picks up SPANNER_EMULATOR_HOST from the environment, and building with an @@ -116,7 +667,30 @@ private SpannerOptions newTestOptions() { // disabled for a client without credentials, so leave the emulator out of these tests. .setEmulatorHost(null) .setCredentials( - OAuth2Credentials.create(new AccessToken("test-token", new Date(Long.MAX_VALUE)))) - .build(); + OAuth2Credentials.create(new AccessToken("test-token", new Date(Long.MAX_VALUE)))); + } + + private static final class CapturingBuiltInMetricsProvider extends BuiltInMetricsProvider { + private final List createdExporters = new ArrayList<>(); + + @Override + MetricExporter createExporter( + Supplier fallbackProjectIdSupplier, + Map clientAttributes, + @Nullable Credentials credentials, + @Nullable String monitoringHost, + String universeDomain) + throws IOException { + SpannerCloudMonitoringExporter exporter = + (SpannerCloudMonitoringExporter) + super.createExporter( + fallbackProjectIdSupplier, + clientAttributes, + credentials, + monitoringHost, + universeDomain); + createdExporters.add(exporter); + return exporter; + } } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ChannelPoolBuiltInMetricsTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ChannelPoolBuiltInMetricsTest.java index 9a43546c6d34..87245efda900 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ChannelPoolBuiltInMetricsTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ChannelPoolBuiltInMetricsTest.java @@ -22,6 +22,7 @@ import com.google.api.gax.grpc.GrpcCallContext; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiCallContext; +import com.google.auth.Credentials; import com.google.cloud.NoCredentials; import com.google.cloud.grpc.GcpManagedChannel; import com.google.cloud.spanner.SpannerOptions.CallContextConfigurator; @@ -57,25 +58,27 @@ public class ChannelPoolBuiltInMetricsTest extends AbstractMockServerTest { private String previousJmhEnabled; private InMemoryMetricReader builtInReader; + private OpenTelemetrySdk builtInOpenTelemetry; @Before public void setUp() { SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); previousJmhEnabled = System.getProperty("jmh.enabled"); System.setProperty("jmh.enabled", "true"); - BuiltInMetricsProvider.INSTANCE.reset(); builtInReader = InMemoryMetricReader.create(); SdkMeterProviderBuilder meterProviderBuilder = SdkMeterProvider.builder().registerMetricReader(builtInReader); BuiltInMetricsConstant.getAllViews().forEach(meterProviderBuilder::registerView); - BuiltInMetricsProvider.INSTANCE.setOpenTelemetry( - OpenTelemetrySdk.builder().setMeterProvider(meterProviderBuilder.build()).build()); + builtInOpenTelemetry = + OpenTelemetrySdk.builder().setMeterProvider(meterProviderBuilder.build()).build(); } @After public void tearDown() { SpannerOptions.useDefaultEnvironment(); - BuiltInMetricsProvider.INSTANCE.reset(); + if (builtInOpenTelemetry != null) { + builtInOpenTelemetry.close(); + } if (previousJmhEnabled == null) { System.clearProperty("jmh.enabled"); } else { @@ -85,7 +88,7 @@ public void tearDown() { @Test public void channelCountIsReportedForTheDataPoolOnly() { - try (Spanner spanner = createOptions().build().getService()) { + try (Spanner spanner = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(spanner); List active = activeChannelCountPoints(); @@ -103,7 +106,7 @@ public void channelCountIsReportedForTheDataPoolOnly() { @Test public void channelPoolMetricsAreNotReportedWithoutCredentials() { System.clearProperty("jmh.enabled"); - try (Spanner spanner = createOptions().build().getService()) { + try (Spanner spanner = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -113,7 +116,7 @@ public void channelPoolMetricsAreNotReportedWithoutCredentials() { @Test public void channelLoadIsReportedWithTheDatabaseOfTheCall() { - try (Spanner spanner = createOptions().build().getService()) { + try (Spanner spanner = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(spanner); List points = channelLoadPoints(); @@ -155,7 +158,8 @@ public ApiCallContext configure( } }; try (Spanner spanner = - createOptions().setCallContextConfigurator(configurator).build().getService()) { + buildWithBuiltInMetrics(createOptions().setCallContextConfigurator(configurator)) + .getService()) { executeSelect1(spanner); assertThat( @@ -220,7 +224,7 @@ public boolean isEnableChannelPoolBuiltInMetrics() { return false; } }); - try (Spanner spanner = createOptions().build().getService()) { + try (Spanner spanner = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -230,7 +234,8 @@ public boolean isEnableChannelPoolBuiltInMetrics() { @Test public void channelPoolMetricsAreNotReportedWhenBuiltInMetricsAreDisabled() { - try (Spanner spanner = createOptions().setBuiltInMetricsEnabled(false).build().getService()) { + try (Spanner spanner = + buildWithBuiltInMetrics(createOptions().setBuiltInMetricsEnabled(false)).getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -242,7 +247,8 @@ public void channelPoolMetricsAreNotReportedWhenBuiltInMetricsAreDisabled() { public void channelPoolMetricsAreNotReportedWithTheEmulator() { mockInstanceAdmin.addResponse(ListInstanceConfigsResponse.getDefaultInstance()); try (Spanner spanner = - createOptions().setEmulatorHost("localhost:" + getPort()).build().getService()) { + buildWithBuiltInMetrics(createOptions().setEmulatorHost("localhost:" + getPort())) + .getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -252,9 +258,9 @@ public void channelPoolMetricsAreNotReportedWithTheEmulator() { @Test public void eachClientReportsItsOwnPoolUntilItIsClosed() { - try (Spanner first = createOptions().build().getService()) { + try (Spanner first = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(first); - try (Spanner second = createOptions().build().getService()) { + try (Spanner second = buildWithBuiltInMetrics(createOptions()).getService()) { executeSelect1(second); List active = activeChannelCountPoints(); @@ -274,12 +280,15 @@ public void eachClientReportsItsOwnPoolUntilItIsClosed() { @Test public void channelPoolMetricsConvertToCloudMonitoringTimeSeries() { - try (Spanner spanner = createOptions().build().getService()) { + SpannerOptions options = buildWithBuiltInMetrics(createOptions()); + try (Spanner spanner = options.getService()) { executeSelect1(spanner); List allTimeSeries = SpannerCloudMonitoringExporterUtils.convertToSpannerTimeSeries( - builtInReader.collectAllMetrics(), "my-project"); + builtInReader.collectAllMetrics(), + "my-project", + options.builtInMetricsProvider.createClientAttributes()); TimeSeries channelCount = allTimeSeries.stream() @@ -335,7 +344,7 @@ public void channelPoolMetricsConvertToCloudMonitoringTimeSeries() { @Test public void adminCallsDoNotReportChannelLoad() { mockInstanceAdmin.addResponse(ListInstanceConfigsResponse.getDefaultInstance()); - try (Spanner spanner = createOptions().build().getService()) { + try (Spanner spanner = buildWithBuiltInMetrics(createOptions()).getService()) { spanner.getInstanceAdminClient().listInstanceConfigs().iterateAll().forEach(ignored -> {}); assertThat(channelLoadPoints()).isEmpty(); @@ -346,14 +355,15 @@ public void adminCallsDoNotReportChannelLoad() { @Test public void dynamicPoolReportsDynamicPoolModeAndChannelLoad() { SpannerOptions options = - SpannerOptions.newBuilder() - .setProjectId("my-project") - .setHost(String.format("http://localhost:%d", getPort())) - .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) - .setCredentials(NoCredentials.getInstance()) - .enableGrpcGcpExtension() - .enableDynamicChannelPool() - .build(); + buildWithBuiltInMetrics( + SpannerOptions.newBuilder() + .setProjectId("my-project") + .setHost(String.format("http://localhost:%d", getPort())) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .setCredentials(NoCredentials.getInstance()) + .enableGrpcGcpExtension() + .enableDynamicChannelPool()); try (Spanner spanner = options.getService()) { executeSelect1(spanner); @@ -398,7 +408,7 @@ public void channelPoolMetricsAreNotReportedWithCustomChannelProvider() { .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) .build(); try (Spanner spanner = - createOptions().setChannelProvider(customProvider).build().getService()) { + buildWithBuiltInMetrics(createOptions().setChannelProvider(customProvider)).getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -408,7 +418,8 @@ public void channelPoolMetricsAreNotReportedWithCustomChannelProvider() { @Test public void channelPoolMetricsAreNotReportedWhenGrpcGcpExtensionIsDisabled() { - try (Spanner spanner = createOptions().disableGrpcGcpExtension().build().getService()) { + try (Spanner spanner = + buildWithBuiltInMetrics(createOptions().disableGrpcGcpExtension()).getService()) { executeSelect1(spanner); assertThat(channelCountPoints()).isEmpty(); @@ -416,10 +427,17 @@ public void channelPoolMetricsAreNotReportedWhenGrpcGcpExtensionIsDisabled() { } } + private SpannerOptions buildWithBuiltInMetrics(SpannerOptions.Builder builder) { + SpannerOptions options = builder.build(); + options.builtInMetricsProvider.setOpenTelemetry(builtInOpenTelemetry); + return options; + } + private SpannerOptions.Builder createOptions() { return SpannerOptions.newBuilder() .setProjectId("my-project") .setHost(String.format("http://localhost:%d", getPort())) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) .setCredentials(NoCredentials.getInstance()) .enableGrpcGcpExtension() @@ -428,15 +446,16 @@ private SpannerOptions.Builder createOptions() { } private SpannerOptions createDirectPathFallbackOptions() { - return SpannerOptions.newBuilder() - .setProjectId("my-project") - .setEnableDirectAccess(true) - .setHost("http://localhost:1") - .setCredentials(NoCredentials.getInstance()) - .enableGrpcGcpExtension() - .disableDynamicChannelPool() - .setNumChannels(NUM_CHANNELS) - .build(); + return buildWithBuiltInMetrics( + SpannerOptions.newBuilder() + .setProjectId("my-project") + .setEnableDirectAccess(true) + .setHost("http://localhost:1") + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .setCredentials(NoCredentials.getInstance()) + .enableGrpcGcpExtension() + .disableDynamicChannelPool() + .setNumChannels(NUM_CHANNELS)); } private static void executeSelect1(Spanner spanner) { diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ConnectionOptionsPublicApiTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ConnectionOptionsPublicApiTest.java new file mode 100644 index 000000000000..998a3f9f83fd --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ConnectionOptionsPublicApiTest.java @@ -0,0 +1,79 @@ +/* + * 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 static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.cloud.spanner.connection.ConnectionOptions; +import com.google.cloud.spanner.connection.ConnectionOptions.StartupPropertyPolicy; +import com.google.cloud.spanner.connection.ConnectionProperties; +import com.google.cloud.spanner.connection.ConnectionPropertyValue; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** + * Verifies programmatic {@link ConnectionPropertyValue} access from outside the connection package. + */ +@RunWith(JUnit4.class) +public class ConnectionOptionsPublicApiTest { + + @Test + public void testExternalPackageCanBuildConnectionPropertyValues() { + ConnectionPropertyValue endpoint = + ConnectionPropertyValue.of(ConnectionProperties.ENDPOINT, "external.example.com:443"); + assertSame(ConnectionProperties.ENDPOINT, endpoint.getProperty()); + assertEquals("external.example.com:443", endpoint.getValue()); + assertEquals("external.example.com:443", endpoint.getResetValue()); + + ConnectionOptions options = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri( + "cloudspanner:/projects/test-project/instances/test-instance/databases/test-db?autocommit=true") + .setConnectionPropertyValue(endpoint) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USE_PLAIN_TEXT, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.AUTOCOMMIT, false)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.ENABLE_END_TO_END_TRACING, true)) + .build(); + + assertEquals("http://external.example.com:443", options.getHost()); + assertFalse(options.isAutocommit()); + assertEquals(Dialect.POSTGRESQL, options.getDialect()); + assertTrue(options.isEndToEndTracingEnabled()); + + SpannerException rejected = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri( + "cloudspanner:/projects/test-project/instances/test-instance/databases/test-db?endpoint=evil.example.com:443") + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, rejected.getErrorCode()); + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/GrpcMetricsDualWireTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/GrpcMetricsDualWireTest.java index 08191cfc566a..f7300e0debcb 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/GrpcMetricsDualWireTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/GrpcMetricsDualWireTest.java @@ -57,8 +57,9 @@ private static OpenTelemetrySdk newOpenTelemetry(InMemoryMetricReader reader) { private static ManagedChannel buildWiredChannel(OpenTelemetry... openTelemetries) { InstantiatingGrpcChannelProvider.Builder providerBuilder = InstantiatingGrpcChannelProvider.newBuilder(); + BuiltInMetricsProvider metricsProvider = new BuiltInMetricsProvider(); for (OpenTelemetry openTelemetry : openTelemetries) { - BuiltInMetricsProvider.INSTANCE.enableGrpcMetrics(providerBuilder, openTelemetry); + metricsProvider.enableGrpcMetrics(providerBuilder, openTelemetry); } ManagedChannelBuilder channelBuilder = NettyChannelBuilder.forAddress("localhost", getPort()).usePlaintext(); diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MetricsProviderTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MetricsProviderTest.java index 36e7ee96412d..b96844d9c377 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MetricsProviderTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MetricsProviderTest.java @@ -61,12 +61,12 @@ public void setUp() { @After public void reset() { SpannerOptions.useDefaultEnvironment(); - BuiltInMetricsProvider.INSTANCE.reset(); } private static SpannerOptions.Builder cloudBuilder() { return SpannerOptions.newBuilder() .setProjectId("test-project") + .setEmulatorHost(null) .setCredentials(NoCredentials.getInstance()); } @@ -291,17 +291,16 @@ public boolean isEnableBuiltInMetrics() { } @Test - public void customProviderDoesNotTouchProcessWideCloudMonitoringSingleton() { - BuiltInMetricsProvider.INSTANCE.reset(); + public void customProviderDoesNotTouchCloudMonitoringProvider() { CustomOpenTelemetryMetricsProvider provider = CustomOpenTelemetryMetricsProvider.create(OpenTelemetry.noop()); SpannerOptions cloudOptions = cloudBuilder().setClientMetricsProvider(provider).build(); cloudOptions.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + assertNull(cloudOptions.builtInMetricsProvider.getOpenTelemetry()); SpannerOptions omniOptions = omniBuilder().setClientMetricsProvider(provider).build(); omniOptions.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + assertNull(omniOptions.builtInMetricsProvider.getOpenTelemetry()); } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClientMockServerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClientMockServerTest.java index ff257414a0be..11a95980558b 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClientMockServerTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MultiplexedSessionDatabaseClientMockServerTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; @@ -47,10 +48,12 @@ import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; import com.google.protobuf.ByteString; +import com.google.protobuf.Value; import com.google.spanner.v1.*; import com.google.spanner.v1.RequestOptions.Priority; import com.google.spanner.v1.Session; import io.grpc.Status; +import java.lang.reflect.Field; import java.time.Duration; import java.util.*; import java.util.concurrent.CountDownLatch; @@ -1871,6 +1874,15 @@ public void testBatchWriteAtLeastOnce() { MutationGroup.of( Mutation.newInsertBuilder("FOO3").set("ID").to(3L).set("NAME").to("Bar3").build(), Mutation.newInsertBuilder("FOO4").set("ID").to(4L).set("NAME").to("Bar4").build())); + mockSpanner.setBatchWriteResult( + ImmutableList.of( + BatchWriteResponse.newBuilder() + .setStatus( + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.OK_VALUE) + .build()) + .addAllIndexes(ImmutableList.of(0, 1)) + .build())); ServerStream responseStream = client.batchWriteAtLeastOnce(MUTATION_GROUPS); int idx = 0; @@ -1896,6 +1908,183 @@ public void testBatchWriteAtLeastOnce() { assertEquals(1L, client.multiplexedSessionDatabaseClient.getNumSessionsReleased().get()); } + @Test + public void testBatchWriteAtLeastOnceDoesNotLeakSingleUseChannelUsage() { + DatabaseClientImpl client = + (DatabaseClientImpl) spanner.getDatabaseClient(DatabaseId.of("p", "i", "d")); + + ImmutableList groups = + ImmutableList.of( + MutationGroup.of( + Mutation.newInsertBuilder("FOO1").set("ID").to(1L).set("NAME").to("Bar1").build())); + mockSpanner.setBatchWriteResult( + ImmutableList.of( + BatchWriteResponse.newBuilder() + .setStatus( + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.OK_VALUE) + .build()) + .addIndexes(0) + .build())); + + for (int i = 0; i < 3; i++) { + ServerStream stream = client.batchWriteAtLeastOnce(groups); + assertThat(ImmutableList.copyOf(stream)).hasSize(1); + } + + assertEquals(0, client.multiplexedSessionDatabaseClient.getChannelUsageCardinality()); + assertEquals(0, client.multiplexedSessionDatabaseClient.getNumCurrentSingleUseTransactions()); + } + + @Test + public void testBatchWriteAtLeastOnceMergesClientContextAndDefaultExcludeTxnFromChangeStreams() + throws Exception { + RequestOptions.ClientContext defaultClientContext = + RequestOptions.ClientContext.newBuilder() + .putSecureContext( + "default_key", Value.newBuilder().setStringValue("default_val").build()) + .putSecureContext( + "shared_key", Value.newBuilder().setStringValue("from_default").build()) + .build(); + RequestOptions.ClientContext rpcClientContext = + RequestOptions.ClientContext.newBuilder() + .putSecureContext("shared_key", Value.newBuilder().setStringValue("from_rpc").build()) + .putSecureContext("rpc_key", Value.newBuilder().setStringValue("rpc_val").build()) + .build(); + + SpannerOptions.Builder builder = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setChannelProvider(channelProvider) + .setCredentials(NoCredentials.getInstance()) + .setDefaultClientContext(defaultClientContext); + Field defaultTxOptionsField = + SpannerOptions.Builder.class.getDeclaredField("defaultTransactionOptions"); + defaultTxOptionsField.setAccessible(true); + defaultTxOptionsField.set( + builder, TransactionOptions.newBuilder().setExcludeTxnFromChangeStreams(true).build()); + + mockSpanner.setBatchWriteResult( + ImmutableList.of( + BatchWriteResponse.newBuilder() + .setStatus( + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.OK_VALUE) + .build()) + .addIndexes(0) + .build())); + + ImmutableList groups = + ImmutableList.of( + MutationGroup.of( + Mutation.newInsertBuilder("FOO1").set("ID").to(1L).set("NAME").to("Bar1").build())); + + try (Spanner ctxSpanner = builder.build().getService()) { + DatabaseClient ctxClient = ctxSpanner.getDatabaseClient(DatabaseId.of("p", "i", "d")); + List responses = + ImmutableList.copyOf( + ctxClient.batchWriteAtLeastOnce(groups, Options.clientContext(rpcClientContext))); + assertThat(responses).hasSize(1); + } + + List requests = mockSpanner.getRequestsOfType(BatchWriteRequest.class); + assertThat(requests).hasSize(1); + BatchWriteRequest request = requests.get(0); + assertTrue(request.getExcludeTxnFromChangeStreams()); + RequestOptions.ClientContext actualContext = request.getRequestOptions().getClientContext(); + assertEquals( + "default_val", actualContext.getSecureContextOrThrow("default_key").getStringValue()); + assertEquals("from_rpc", actualContext.getSecureContextOrThrow("shared_key").getStringValue()); + assertEquals("rpc_val", actualContext.getSecureContextOrThrow("rpc_key").getStringValue()); + } + + @Test + public void testWriteAtLeastOnceWithOptionsMergesClientContext() { + RequestOptions.ClientContext defaultClientContext = + RequestOptions.ClientContext.newBuilder() + .putSecureContext( + "default_key", Value.newBuilder().setStringValue("default_val").build()) + .putSecureContext( + "shared_key", Value.newBuilder().setStringValue("from_default").build()) + .build(); + RequestOptions.ClientContext rpcClientContext = + RequestOptions.ClientContext.newBuilder() + .putSecureContext("shared_key", Value.newBuilder().setStringValue("from_rpc").build()) + .putSecureContext("rpc_key", Value.newBuilder().setStringValue("rpc_val").build()) + .build(); + + SpannerOptions.Builder builder = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setChannelProvider(channelProvider) + .setCredentials(NoCredentials.getInstance()) + .setDefaultClientContext(defaultClientContext); + + ImmutableList mutations = + ImmutableList.of( + Mutation.newInsertBuilder("FOO1").set("ID").to(1L).set("NAME").to("Bar1").build()); + + try (Spanner ctxSpanner = builder.build().getService()) { + DatabaseClient ctxClient = ctxSpanner.getDatabaseClient(DatabaseId.of("p", "i", "d")); + ctxClient.writeAtLeastOnceWithOptions(mutations, Options.clientContext(rpcClientContext)); + } + + List requests = mockSpanner.getRequestsOfType(CommitRequest.class); + assertThat(requests).hasSize(1); + RequestOptions.ClientContext actualContext = + requests.get(0).getRequestOptions().getClientContext(); + assertEquals( + "default_val", actualContext.getSecureContextOrThrow("default_key").getStringValue()); + assertEquals("from_rpc", actualContext.getSecureContextOrThrow("shared_key").getStringValue()); + assertEquals("rpc_val", actualContext.getSecureContextOrThrow("rpc_key").getStringValue()); + } + + @Test + public void testBatchWriteAtLeastOnceMaterializesAndRejectsNull() { + DatabaseClientImpl client = + (DatabaseClientImpl) spanner.getDatabaseClient(DatabaseId.of("p", "i", "d")); + + // Null mutationGroups must throw NullPointerException synchronously without sending an RPC. + assertThrows(NullPointerException.class, () -> client.batchWriteAtLeastOnce(null)); + assertThat(mockSpanner.getRequestsOfType(BatchWriteRequest.class)).isEmpty(); + + ImmutableList groups = + ImmutableList.of( + MutationGroup.of( + Mutation.newInsertBuilder("FOO1").set("ID").to(1L).set("NAME").to("Bar1").build())); + + // Verify defensive copying for mutable lists and zero-copy pass-through for ImmutableList. + assertSame(groups, SessionImpl.materializeMutationGroups(groups)); + List mutableCopy = new ArrayList<>(groups); + List materialized = SessionImpl.materializeMutationGroups(mutableCopy); + mutableCopy.clear(); + assertEquals(1, materialized.size()); + + // Single-use Iterable must be traversed only once. + mockSpanner.setBatchWriteResult( + ImmutableList.of( + BatchWriteResponse.newBuilder() + .setStatus( + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.OK_VALUE) + .build()) + .addIndexes(0) + .build())); + AtomicInteger iteratorCalls = new AtomicInteger(); + Iterable singlePass = + () -> { + if (iteratorCalls.incrementAndGet() > 1) { + throw new IllegalStateException("Single-use Iterable traversed more than once"); + } + return groups.iterator(); + }; + + List responses = + ImmutableList.copyOf(client.batchWriteAtLeastOnce(singlePass)); + assertThat(responses).hasSize(1); + assertEquals(1, iteratorCalls.get()); + } + @Test public void testRWTransactionWithTransactionManager_CommitAborted_SetsTransactionId_AndUsedInNewInstance() { diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/OpenTelemetryBuiltInMetricsTracerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/OpenTelemetryBuiltInMetricsTracerTest.java index ed24e02d3e9d..39b6f51c2a1a 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/OpenTelemetryBuiltInMetricsTracerTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/OpenTelemetryBuiltInMetricsTracerTest.java @@ -27,9 +27,13 @@ import static org.junit.Assume.assumeFalse; import com.google.api.gax.core.GaxProperties; +import com.google.api.gax.grpc.GrpcStatusCode; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; import com.google.api.gax.tracing.ApiTracerFactory; +import com.google.api.gax.tracing.MethodName; import com.google.cloud.NoCredentials; import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; @@ -70,7 +74,7 @@ public class OpenTelemetryBuiltInMetricsTracerTest extends AbstractNettyMockServ private static final Statement UPDATE_RANDOM = Statement.of("UPDATE random SET foo=1 WHERE id=1"); private static InMemoryMetricReader metricReader; private static final Map attributes = - BuiltInMetricsProvider.INSTANCE.createClientAttributes(); + new BuiltInMetricsProvider().createClientAttributes(); private static final Attributes expectedCommonBaseAttributes = Attributes.builder() .put(BuiltInMetricsConstant.PROJECT_ID_KEY, "test-project") @@ -402,6 +406,92 @@ public void testNoServerTimingHeader() throws IOException, InterruptedException serverNoHeader.awaitTermination(); } + @Test + @SuppressWarnings("deprecation") + public void testAttemptStartedResetsServerTimingHeaderMetricsBetweenAttempts() throws Exception { + try (InMemoryMetricReader localReader = InMemoryMetricReader.create()) { + SdkMeterProviderBuilder meterProvider = + SdkMeterProvider.builder().registerMetricReader(localReader); + BuiltInMetricsConstant.getAllViews().forEach(meterProvider::registerView); + OpenTelemetry openTelemetry = + OpenTelemetrySdk.builder().setMeterProvider(meterProvider.build()).build(); + + BuiltInMetricsRecorder recorder = + new BuiltInMetricsRecorder(openTelemetry, BuiltInMetricsConstant.METER_NAME); + TraceWrapper traceWrapper = + new TraceWrapper( + Tracing.getTracer(), + openTelemetry.getTracer( + MetricRegistryConstants.INSTRUMENTATION_SCOPE, + GaxProperties.getLibraryVersion(getClass())), + true); + BuiltInMetricsTracer tracer = + new BuiltInMetricsTracer( + MethodName.of("Spanner", "BatchWrite"), + recorder, + traceWrapper, + traceWrapper.getCurrentSpan()); + + ApiException unavailable = + ApiExceptionFactory.createException( + "transient", null, GrpcStatusCode.of(Status.Code.UNAVAILABLE), /* retryable= */ true); + + // Attempt 0 receives DirectPath + AFE headers and fails transiently. + tracer.attemptStarted(new Object(), 0); + tracer.recordServerTimingHeaderMetrics( + 12.0f, 5.0f, /* isDirectPathUsed= */ true, /* isAfeEnabled= */ true); + tracer.attemptFailedDuration(unavailable, Duration.ofMillis(10L)); + + // Attempt 1 fails before any response headers arrive; reset must clear all 4 fields so + // gfe_header_missing_count increments and stale AFE latency / AFE flag are not reused. + tracer.attemptStarted(new Object(), 1); + tracer.attemptFailedRetriesExhausted(unavailable); + + // Deprecated overload must start super.attemptTimer even when called first on a fresh tracer, + // and must reset all 4 fields identically. + BuiltInMetricsTracer deprecatedTracer = + new BuiltInMetricsTracer( + MethodName.of("Spanner", "BatchWrite"), + recorder, + traceWrapper, + traceWrapper.getCurrentSpan()); + deprecatedTracer.attemptStarted(0); + deprecatedTracer.recordServerTimingHeaderMetrics( + 9.0f, 4.0f, /* isDirectPathUsed= */ true, /* isAfeEnabled= */ true); + deprecatedTracer.attemptStarted(1); + deprecatedTracer.attemptCancelled(); + deprecatedTracer.operationCancelled(); + + Attributes unavailableAttrs = + Attributes.builder() + .put(BuiltInMetricsConstant.METHOD_KEY, "Spanner.BatchWrite") + .put(BuiltInMetricsConstant.STATUS_KEY, "UNAVAILABLE") + .build(); + Attributes cancelledAttrs = + Attributes.builder() + .put(BuiltInMetricsConstant.METHOD_KEY, "Spanner.BatchWrite") + .put(BuiltInMetricsConstant.STATUS_KEY, "CANCELLED") + .build(); + + MetricData gfeMissing = + getMetricData(localReader, BuiltInMetricsConstant.GFE_CONNECTIVITY_ERROR_NAME); + assertEquals(1.0f, getAggregatedValue(gfeMissing, unavailableAttrs), 0.0f); + assertEquals(1.0f, getAggregatedValue(gfeMissing, cancelledAttrs), 0.0f); + + MetricData afeLatency = getMetricData(localReader, BuiltInMetricsConstant.AFE_LATENCIES_NAME); + long afeCount = + afeLatency.getHistogramData().getPoints().stream() + .filter(pd -> pd.getAttributes().equals(unavailableAttrs)) + .mapToLong(pd -> pd.getCount()) + .sum(); + assertEquals(1L, afeCount); + + assertFalse( + checkIfMetricExists(localReader, BuiltInMetricsConstant.AFE_CONNECTIVITY_ERROR_NAME)); + assertFalse(checkIfMetricExists(localReader, BuiltInMetricsConstant.GFE_LATENCIES_NAME)); + } + } + private MetricData getMetricData(InMemoryMetricReader reader, String metricName) { String fullMetricName = BuiltInMetricsConstant.METER_NAME + "/" + metricName; Collection allMetricData; diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java index 1251ee270faf..6721ad6e9047 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ReadAsyncTest.java @@ -19,7 +19,11 @@ import static com.google.cloud.spanner.MockSpannerTestUtil.*; import static com.google.cloud.spanner.SpannerApiFutures.get; 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.assertNull; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.api.core.ApiFuture; @@ -28,16 +32,19 @@ import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.cloud.NoCredentials; import com.google.cloud.spanner.AsyncResultSet.CallbackResponse; +import com.google.cloud.spanner.AsyncResultSet.CursorState; import com.google.cloud.spanner.MockSpannerServiceImpl.SimulatedExecutionTime; import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.common.collect.ContiguousSet; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import com.google.spanner.v1.ExecuteSqlRequest; import io.grpc.Server; import io.grpc.Status; import io.grpc.inprocess.InProcessServerBuilder; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.LinkedList; @@ -45,10 +52,13 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -431,6 +441,284 @@ public void cancel() throws Exception { assertThat(values).containsExactly("v1"); } + @Test(timeout = 10_000) + public void concurrentQueriesOnSingleThreadAsyncExecutorDoNotBlockWhenPausedOrFrozen() + throws Exception { + Statement tenRowStatement = + Statement.of("SELECT * FROM TestTable WHERE Key BETWEEN 'k1' AND 'k10'"); + mockSpanner.putStatementResult( + StatementResult.query( + tenRowStatement, generateKeyValueResultSet(ContiguousSet.closed(1, 10)))); + List expectedValues = + Arrays.asList("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"); + + SpannerOptions.CloseableExecutorProvider singleThreadAsyncProvider = + SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + ExecutorService pausedCallbackExecutor = Executors.newSingleThreadExecutor(); + try (Spanner singleThreadSpanner = createSingleThreadSpanner(singleThreadAsyncProvider)) { + DatabaseClient singleThreadClient = + singleThreadSpanner.getDatabaseClient( + DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE)); + + // Warm up session initialization before freezing mockSpanner so executeQueryAsync starts + // ExecuteStreamingSql directly without waiting on CreateSession. + try (AsyncResultSet warmup = + singleThreadClient.singleUse().executeQueryAsync(READ_ONE_KEY_VALUE_STATEMENT)) { + assertEquals( + Collections.singletonList("v1"), + warmup.toListAsync(row -> row.getString("Value"), executor).get(5, TimeUnit.SECONDS)); + } + + // 1. Stalled server stream (mockSpanner.freeze()) must not pin the 1 async executor thread. + mockSpanner.freeze(); + ApiFuture> frozenRowsFuture; + try (AsyncResultSet frozenResultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + frozenRowsFuture = frozenResultSet.toListAsync(row -> row.getString("Value"), executor); + assertTrue( + singleThreadAsyncProvider.getExecutor().submit(() -> true).get(5, TimeUnit.SECONDS)); + assertFalse(frozenRowsFuture.isDone()); + mockSpanner.unfreeze(); + assertEquals(expectedValues, frozenRowsFuture.get(5, TimeUnit.SECONDS)); + } finally { + mockSpanner.unfreeze(); + } + + // 2. A PAUSED query with a full row buffer (bufferRows(2)) on a 10-row stream must yield the + // 1 async executor thread so 3 concurrent streaming queries complete to DONE without + // deadlocking before the paused query is resumed. + CountDownLatch firstRowPausedLatch = new CountDownLatch(1); + AtomicBoolean pauseOnFirstRow = new AtomicBoolean(true); + List pausedValues = Collections.synchronizedList(new ArrayList<>()); + try (AsyncResultSet pausedResultSet = + singleThreadClient + .singleUse() + .executeQueryAsync(tenRowStatement, Options.bufferRows(2))) { + ApiFuture pausedFinished = + pausedResultSet.setCallback( + pausedCallbackExecutor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + pausedValues.add(cursor.getString("Value")); + if (pauseOnFirstRow.compareAndSet(true, false)) { + firstRowPausedLatch.countDown(); + return CallbackResponse.PAUSE; + } + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + return CallbackResponse.DONE; + } + } + }); + + assertTrue(firstRowPausedLatch.await(5, TimeUnit.SECONDS)); + pausedCallbackExecutor.submit(() -> {}).get(5, TimeUnit.SECONDS); + singleThreadAsyncProvider.getExecutor().submit(() -> null).get(5, TimeUnit.SECONDS); + + List>> concurrentFutures = new ArrayList<>(); + for (int queryIndex = 0; queryIndex < 3; queryIndex++) { + try (AsyncResultSet concurrentResultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + concurrentFutures.add( + concurrentResultSet.toListAsync(row -> row.getString("Value"), executor)); + } + } + List> concurrentResults = + ApiFutures.allAsList(concurrentFutures).get(5, TimeUnit.SECONDS); + for (List rows : concurrentResults) { + assertEquals(expectedValues, rows); + } + assertFalse(pausedFinished.isDone()); + + pausedResultSet.resume(); + assertNull(pausedFinished.get(5, TimeUnit.SECONDS)); + assertEquals(expectedValues, pausedValues); + } + } finally { + mockSpanner.unfreeze(); + pausedCallbackExecutor.shutdownNow(); + singleThreadAsyncProvider.close(); + } + } + + @Test(timeout = 10_000) + public void midStreamUnavailableResumesCleanlyOnSingleThreadAsyncExecutor() throws Exception { + Statement tenRowStatement = + Statement.of("SELECT * FROM TestTable WHERE Key BETWEEN 'k1' AND 'k10' ORDER BY Key"); + mockSpanner.putStatementResult( + StatementResult.query( + tenRowStatement, generateKeyValueResultSet(ContiguousSet.closed(1, 10)))); + List expectedValues = + Arrays.asList("v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10"); + + SpannerOptions.CloseableExecutorProvider singleThreadAsyncProvider = + SpannerOptions.createAsyncExecutorProvider(1, 1L, TimeUnit.SECONDS); + try (Spanner singleThreadSpanner = createSingleThreadSpanner(singleThreadAsyncProvider)) { + DatabaseClient singleThreadClient = + singleThreadSpanner.getDatabaseClient( + DatabaseId.of(TEST_PROJECT, TEST_INSTANCE, TEST_DATABASE)); + + mockSpanner.clearRequests(); + mockSpanner.setExecuteStreamingSqlExecutionTime( + SimulatedExecutionTime.ofStreamException(Status.UNAVAILABLE.asRuntimeException(), 1)); + try (AsyncResultSet resultSet = + singleThreadClient.singleUse().executeQueryAsync(tenRowStatement)) { + List actualValues = + resultSet.toListAsync(row -> row.getString("Value"), executor).get(5, TimeUnit.SECONDS); + assertEquals(expectedValues, actualValues); + } + + List sqlRequests = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class); + assertEquals(2, sqlRequests.size()); + assertTrue(sqlRequests.get(0).getResumeToken().isEmpty()); + assertFalse(sqlRequests.get(1).getResumeToken().isEmpty()); + } finally { + singleThreadAsyncProvider.close(); + } + } + + @Test(timeout = 10_000) + public void schemaGettersWorkOnDoneForMultiRowAndEmptyQueries() throws Exception { + assertSchemaGettersWorkOnDone( + READ_MULTIPLE_KEY_VALUE_STATEMENT, Arrays.asList("v1", "v2", "v3")); + assertSchemaGettersWorkOnDone(READ_ONE_EMPTY_KEY_VALUE_STATEMENT, Collections.emptyList()); + } + + private void assertSchemaGettersWorkOnDone(Statement statement, List expectedValues) + throws Exception { + List actualValues = Collections.synchronizedList(new ArrayList<>()); + AtomicBoolean assertedOnDone = new AtomicBoolean(false); + try (AsyncResultSet resultSet = client.singleUse().executeQueryAsync(statement)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + while (true) { + CursorState state = cursor.tryNext(); + switch (state) { + case OK: + actualValues.add(cursor.getString("Value")); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + assertEquals(READ_TABLE_TYPE, cursor.getType()); + assertEquals(2, cursor.getColumnCount()); + assertEquals(0, cursor.getColumnIndex("Key")); + assertEquals(1, cursor.getColumnIndex("Value")); + assertEquals(Type.string(), cursor.getColumnType(0)); + assertEquals(Type.string(), cursor.getColumnType(1)); + assertEquals(Type.string(), cursor.getColumnType("Key")); + assertEquals(Type.string(), cursor.getColumnType("Value")); + assertedOnDone.set(true); + return CallbackResponse.DONE; + } + } + }); + assertNull(finished.get(5, TimeUnit.SECONDS)); + } + assertTrue(assertedOnDone.get()); + assertEquals(expectedValues, actualValues); + } + + @Test(timeout = 60_000) + public void cancelAfterCursorStateDonePreservesSuccess() throws Exception { + List actualValues = Collections.synchronizedList(new ArrayList<>()); + CountDownLatch doneObservedLatch = new CountDownLatch(1); + CountDownLatch cancelCalledLatch = new CountDownLatch(1); + try (AsyncResultSet resultSet = + client.singleUse().executeQueryAsync(READ_MULTIPLE_KEY_VALUE_STATEMENT)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + while (true) { + switch (cursor.tryNext()) { + case OK: + actualValues.add(cursor.getString("Value")); + break; + case NOT_READY: + return CallbackResponse.CONTINUE; + case DONE: + doneObservedLatch.countDown(); + try { + assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw new RuntimeException(interruptedException); + } + assertEquals(READ_TABLE_TYPE, cursor.getType()); + return CallbackResponse.DONE; + } + } + }); + + assertTrue(doneObservedLatch.await(30, TimeUnit.SECONDS)); + resultSet.cancel(); + cancelCalledLatch.countDown(); + assertNull(finished.get(30, TimeUnit.SECONDS)); + } finally { + cancelCalledLatch.countDown(); + } + assertEquals(Arrays.asList("v1", "v2", "v3"), actualValues); + } + + @Test(timeout = 60_000) + public void cancelAfterCursorExceptionPreservesOriginalError() throws Exception { + Statement failingStatement = Statement.of("SELECT * FROM MissingTable"); + mockSpanner.putStatementResult( + StatementResult.exception( + failingStatement, + Status.INVALID_ARGUMENT.withDescription("missing table").asRuntimeException())); + CountDownLatch exceptionObservedLatch = new CountDownLatch(1); + CountDownLatch cancelCalledLatch = new CountDownLatch(1); + try (AsyncResultSet resultSet = client.singleUse().executeQueryAsync(failingStatement)) { + ApiFuture finished = + resultSet.setCallback( + executor, + cursor -> { + SpannerException thrown = assertThrows(SpannerException.class, cursor::tryNext); + assertEquals(ErrorCode.INVALID_ARGUMENT, thrown.getErrorCode()); + exceptionObservedLatch.countDown(); + try { + assertTrue(cancelCalledLatch.await(30, TimeUnit.SECONDS)); + } catch (InterruptedException interruptedException) { + Thread.currentThread().interrupt(); + throw new RuntimeException(interruptedException); + } + return CallbackResponse.DONE; + }); + + assertTrue(exceptionObservedLatch.await(30, TimeUnit.SECONDS)); + resultSet.cancel(); + cancelCalledLatch.countDown(); + ExecutionException executionException = + assertThrows(ExecutionException.class, () -> finished.get(30, TimeUnit.SECONDS)); + assertEquals( + ErrorCode.INVALID_ARGUMENT, + ((SpannerException) executionException.getCause()).getErrorCode()); + } finally { + cancelCalledLatch.countDown(); + } + } + + private Spanner createSingleThreadSpanner( + SpannerOptions.CloseableExecutorProvider asyncExecutorProvider) { + return SpannerOptions.newBuilder() + .setProjectId(TEST_PROJECT) + .setChannelProvider(channelProvider) + .setCredentials(NoCredentials.getInstance()) + .setAsyncExecutorProvider(asyncExecutorProvider) + .setSessionPoolOption( + SessionPoolOptions.newBuilder().setFailOnSessionLeak().setMinSessions(0).build()) + .build() + .getService(); + } + private boolean isMultiplexedSessionsEnabled() { if (spanner.getOptions() == null || spanner.getOptions().getSessionPoolOptions() == null) { return false; diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java index 12a00a990c05..3cdd3e33f070 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java @@ -71,6 +71,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.DoubleSupplier; import java.util.function.LongSupplier; import org.jspecify.annotations.Nullable; import org.junit.After; @@ -105,14 +106,16 @@ public static List data() { } private static StatusRuntimeException statusWithRetryInfo(ErrorCode code) { + return statusWithRetryInfo(code, 0L, (int) TimeUnit.MILLISECONDS.toNanos(1L)); + } + + private static StatusRuntimeException statusWithRetryInfo( + ErrorCode code, long seconds, int nanos) { Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); Metadata trailers = new Metadata(); RetryInfo retryInfo = RetryInfo.newBuilder() - .setRetryDelay( - Duration.newBuilder() - .setNanos((int) TimeUnit.MILLISECONDS.toNanos(1L)) - .setSeconds(0L)) + .setRetryDelay(Duration.newBuilder().setSeconds(seconds).setNanos(nanos)) .build(); trailers.put(key, retryInfo); return code.getGrpcStatus().asRuntimeException(trailers); @@ -177,6 +180,7 @@ public boolean isLastStatement() { Starter starter = Mockito.mock(Starter.class); ResumableStreamIterator resumableStreamIterator; private LongSupplier nanoTime = System::nanoTime; + private DoubleSupplier jitterRandom = () -> 1.0; @Before public void setUp() { @@ -190,13 +194,15 @@ public void tearDown() { SpannerOptions.resetActiveTracingFramework(); } + private static RetrySettings defaultTestRetrySettings() { + return RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(32)) + .build(); + } + private void initWithLimit(int maxBufferSize) { - initWithLimitAndRetrySettings( - maxBufferSize, - RetrySettings.newBuilder() - .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10)) - .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1000)) - .build()); + initWithLimitAndRetrySettings(maxBufferSize, defaultTestRetrySettings()); } private void initWithLimitAndRetrySettings(int maxBufferSize, RetrySettings retrySettings) { @@ -206,12 +212,29 @@ private void initWithLimitAndRetrySettings(int maxBufferSize, RetrySettings retr new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false)); } + private void initWithRecordingBackoffSleep( + RetrySettings retrySettings, List recordedSleeps) { + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + retrySettings, + new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false), + recordedSleeps); + } + private static OpenTelemetrySpan mockOpenTelemetrySpan() { return new OpenTelemetrySpan(mock(io.opentelemetry.api.trace.Span.class)); } private void initWithLimitAndRetrySettings( int maxBufferSize, RetrySettings retrySettings, TraceWrapper tracer) { + initWithLimitAndRetrySettings(maxBufferSize, retrySettings, tracer, null); + } + + private void initWithLimitAndRetrySettings( + int maxBufferSize, + RetrySettings retrySettings, + TraceWrapper tracer, + @Nullable List recordedSleeps) { resumableStreamIterator = new ResumableStreamIterator( maxBufferSize, @@ -227,6 +250,20 @@ long nanoTime() { return nanoTime.getAsLong(); } + @Override + double nextJitterRandom() { + return jitterRandom.getAsDouble(); + } + + @Override + void backoffSleep(Context context, long backoffMillis) throws SpannerException { + if (recordedSleeps != null) { + recordedSleeps.add(backoffMillis); + } else { + super.backoffSleep(context, backoffMillis); + } + } + @Override CloseableIterator startStream( @Nullable ByteString resumeToken, @@ -527,20 +564,11 @@ private boolean totalTimeoutExceeded(long timeoutMillis, long elapsedMillis, lon RetrySettings.newBuilder() .setTotalTimeoutDuration(java.time.Duration.ofMillis(timeoutMillis)) .build()); - SpannerException exception = - Mockito.spy(new RetryableException(errorCodeParameter, "failed by test")); - when(exception.getRetryDelayInMillis()).thenReturn(0L); + SpannerException exception = new RetryableException(errorCodeParameter, "failed by test"); nanoTime = () -> 0L; - assertEquals(0L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); nanoTime = () -> TimeUnit.MILLISECONDS.toNanos(elapsedMillis); - when(exception.getRetryDelayInMillis()).thenReturn(delayMillis); - try { - assertEquals(delayMillis, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); - return false; - } catch (SpannerException e) { - assertThat(e).isSameInstanceAs(exception); - return true; - } + return resumableStreamIterator.totalTimeoutExceeded(java.time.Duration.ofMillis(delayMillis)); } @Test @@ -565,11 +593,17 @@ public void retryBudget_usesConfiguredBackoffWithoutRetryInfo() { public void rawGapicSettings_useConfiguredTimeoutWithoutSpecialCase() { RetrySettings settings = SpannerStubSettings.newBuilder().executeStreamingSqlSettings().getRetrySettings(); + long totalTimeoutMillis = settings.getTotalTimeoutDuration().toMillis(); initWithLimitAndRetrySettings(Integer.MAX_VALUE, settings); SpannerException exception = - Mockito.spy(new RetryableException(errorCodeParameter, "failed by test")); - when(exception.getRetryDelayInMillis()) - .thenReturn(settings.getTotalTimeoutDuration().toMillis()); + new RetryableException( + errorCodeParameter, + "failed by test", + statusWithRetryInfo( + errorCodeParameter, TimeUnit.MILLISECONDS.toSeconds(totalTimeoutMillis), 0)); + nanoTime = () -> 0L; + assertEquals(32_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + nanoTime = () -> TimeUnit.MILLISECONDS.toNanos(totalTimeoutMillis - 32_000L); assertThat( assertThrows( SpannerException.class, @@ -577,6 +611,363 @@ public void rawGapicSettings_useConfiguredTimeoutWithoutSpecialCase() { .isSameInstanceAs(exception); } + @Test + public void retryInfoWithZeroDelay_fallsBackToExponentialBackoff() { + SpannerException zeroDelayException = + new RetryableException( + errorCodeParameter, "zero delay", statusWithRetryInfo(errorCodeParameter, 0L, 0)); + assertEquals(0L, zeroDelayException.getRetryDelayInMillis()); + long delayMillis = resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException); + assertThat(delayMillis).isAtLeast(5L); + assertThat(delayMillis).isAtMost(15L); + + // Positive sub-millisecond RetryInfo is honored and floored at 1ms rather than spinning at + // zero delay or falling back to exponential backoff. + initWithLimit(Integer.MAX_VALUE); + SpannerException subMillisecondException = + new RetryableException( + errorCodeParameter, + "sub-millisecond delay", + statusWithRetryInfo(errorCodeParameter, 0L, 500_000)); + assertEquals(0L, subMillisecondException.getRetryDelayInMillis()); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(subMillisecondException)); + + List recordedSleeps = new ArrayList<>(); + initWithRecordingBackoffSleep(defaultTestRetrySettings(), recordedSleeps); + ResultSetStream s1 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(null, null)).thenReturn(new ResultSetIterator(s1)); + Mockito.when(s1.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r1"), "a")) + .thenThrow(zeroDelayException); + + ResultSetStream s2 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(ByteString.copyFromUtf8("r1"), null)) + .thenReturn(new ResultSetIterator(s2)); + Mockito.when(s2.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r2"), "b")) + .thenReturn(null); + assertThat(consume(resumableStreamIterator)).containsExactly("a", "b").inOrder(); + assertThat(recordedSleeps).hasSize(1); + assertThat(recordedSleeps.get(0)).isAtLeast(5L); + assertThat(recordedSleeps.get(0)).isAtMost(15L); + } + + @Test + public void retryInfoWithNegativeDelays_fallsBackToExponentialBackoff() { + SpannerException minusOneMsException = + new RetryableException( + errorCodeParameter, + "-1ms delay", + statusWithRetryInfo(errorCodeParameter, 0L, (int) -TimeUnit.MILLISECONDS.toNanos(1L))); + SpannerException minusTwoMsException = + new RetryableException( + errorCodeParameter, + "-2ms delay", + statusWithRetryInfo(errorCodeParameter, 0L, (int) -TimeUnit.MILLISECONDS.toNanos(2L))); + SpannerException minusFiveSecException = + new RetryableException( + errorCodeParameter, "-5s delay", statusWithRetryInfo(errorCodeParameter, -5L, 0)); + assertEquals(-1L, minusOneMsException.getRetryDelayInMillis()); + assertEquals(-2L, minusTwoMsException.getRetryDelayInMillis()); + assertEquals(-5000L, minusFiveSecException.getRetryDelayInMillis()); + + for (SpannerException exception : + ImmutableList.of(minusOneMsException, minusTwoMsException, minusFiveSecException)) { + initWithLimit(Integer.MAX_VALUE); + long delayMillis = resumableStreamIterator.checkRetryBudgetAndGetDelay(exception); + assertThat(delayMillis).isAtLeast(5L); + assertThat(delayMillis).isAtMost(15L); + } + + List recordedSleeps = new ArrayList<>(); + initWithRecordingBackoffSleep(defaultTestRetrySettings(), recordedSleeps); + ResultSetStream s1 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(null, null)).thenReturn(new ResultSetIterator(s1)); + Mockito.when(s1.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r1"), "a")) + .thenThrow(minusFiveSecException); + + ResultSetStream s2 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(ByteString.copyFromUtf8("r1"), null)) + .thenReturn(new ResultSetIterator(s2)); + Mockito.when(s2.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r2"), "b")) + .thenReturn(null); + assertThat(consume(resumableStreamIterator)).containsExactly("a", "b").inOrder(); + assertThat(recordedSleeps).hasSize(1); + assertThat(recordedSleeps.get(0)).isAtLeast(5L); + assertThat(recordedSleeps.get(0)).isAtMost(15L); + } + + @Test + public void retryInfoWithMultiHourDelay_clampedToConfiguredMaxRetryDelay() { + RetrySettings settings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(250L)) + .build(); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, settings); + SpannerException threeHourException = + new RetryableException( + errorCodeParameter, + "3h delay", + statusWithRetryInfo(errorCodeParameter, TimeUnit.HOURS.toSeconds(3L), 0)); + assertEquals(TimeUnit.HOURS.toMillis(3L), threeHourException.getRetryDelayInMillis()); + assertEquals(250L, resumableStreamIterator.checkRetryBudgetAndGetDelay(threeHourException)); + + List recordedSleeps = new ArrayList<>(); + initWithRecordingBackoffSleep(settings, recordedSleeps); + ResultSetStream s1 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(null, null)).thenReturn(new ResultSetIterator(s1)); + Mockito.when(s1.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r1"), "a")) + .thenThrow(threeHourException); + + ResultSetStream s2 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(ByteString.copyFromUtf8("r1"), null)) + .thenReturn(new ResultSetIterator(s2)); + Mockito.when(s2.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r2"), "b")) + .thenReturn(null); + + assertThat(consume(resumableStreamIterator)).containsExactly("a", "b").inOrder(); + assertThat(recordedSleeps).containsExactly(250L); + } + + @Test + public void retryInfoWithMultiHourDelayAndUnsetMaxRetryDelay_clampedToDefaultCap() { + RetrySettings unsetSettings = RetrySettings.newBuilder().build(); + assertTrue(unsetSettings.getMaxRetryDelayDuration().isZero()); + assertTrue(unsetSettings.getTotalTimeoutDuration().isZero()); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, unsetSettings); + + SpannerException threeHourException = + new RetryableException( + errorCodeParameter, + "3h delay", + statusWithRetryInfo(errorCodeParameter, TimeUnit.HOURS.toSeconds(3L), 0)); + assertEquals(32_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(threeHourException)); + + List recordedSleeps = new ArrayList<>(); + initWithRecordingBackoffSleep(unsetSettings, recordedSleeps); + ResultSetStream s1 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(null, null)).thenReturn(new ResultSetIterator(s1)); + Mockito.when(s1.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r1"), "a")) + .thenThrow(threeHourException); + + ResultSetStream s2 = Mockito.mock(ResultSetStream.class); + Mockito.when(starter.startStream(ByteString.copyFromUtf8("r1"), null)) + .thenReturn(new ResultSetIterator(s2)); + Mockito.when(s2.next()) + .thenReturn(resultSet(ByteString.copyFromUtf8("r2"), "b")) + .thenReturn(null); + + assertThat(consume(resumableStreamIterator)).containsExactly("a", "b").inOrder(); + assertThat(recordedSleeps).containsExactly(32_000L); + } + + @Test + public void retryInfoWithinMaxRetryDelay_honorsServerDelayAndChecksTotalTimeout() { + SpannerException fiveSecondException = + new RetryableException( + errorCodeParameter, "5s delay", statusWithRetryInfo(errorCodeParameter, 5L, 0)); + assertEquals(5_000L, fiveSecondException.getRetryDelayInMillis()); + assertEquals(5_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(fiveSecondException)); + + // Clamping occurs before totalTimeoutExceeded: a 3-hour server delay clamped to 250ms fits in + // a 1000ms total timeout at t=0, then throws immediately once remaining budget drops to 250ms. + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(250L)) + .setTotalTimeoutDuration(java.time.Duration.ofMillis(1000L)) + .build()); + SpannerException threeHourException = + new RetryableException( + errorCodeParameter, + "3h delay", + statusWithRetryInfo(errorCodeParameter, TimeUnit.HOURS.toSeconds(3L), 0)); + nanoTime = () -> 0L; + assertEquals(250L, resumableStreamIterator.checkRetryBudgetAndGetDelay(threeHourException)); + nanoTime = () -> TimeUnit.MILLISECONDS.toNanos(750L); + assertThat( + assertThrows( + SpannerException.class, + () -> resumableStreamIterator.checkRetryBudgetAndGetDelay(threeHourException))) + .isSameInstanceAs(threeHourException); + } + + @Test + public void nonPositiveRetryInfo_floorsMinimumBackoffToOneMs() { + SpannerException zeroDelayException = + new RetryableException( + errorCodeParameter, "zero delay", statusWithRetryInfo(errorCodeParameter, 0L, 0)); + SpannerException absentDelayException = + new RetryableException( + errorCodeParameter, + "absent delay", + errorCodeParameter.getGrpcStatus().asRuntimeException()); + + initWithLimitAndRetrySettings(Integer.MAX_VALUE, RetrySettings.newBuilder().build()); + jitterRandom = () -> 0.0; + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(1L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(1L)) + .build()); + for (int i = 0; i < 100; i++) { + assertThat(resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException)) + .isAtLeast(1L); + } + } + + @Test + public void effectiveMaxRetryDelayAndBackoff_handleSubMillisecondAndOverflowingDurations() { + SpannerException twoHundredMsException = + new RetryableException( + errorCodeParameter, + "200ms delay", + statusWithRetryInfo(errorCodeParameter, 0L, (int) TimeUnit.MILLISECONDS.toNanos(200L))); + SpannerException zeroDelayException = + new RetryableException( + errorCodeParameter, "zero delay", statusWithRetryInfo(errorCodeParameter, 0L, 0)); + + RetrySettings subMsSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofNanos(500_000L)) + .setMaxRetryDelayDuration(java.time.Duration.ofNanos(500_000L)) + .build(); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, subMsSettings); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(twoHundredMsException)); + assertThat(resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException)) + .isAtLeast(1L); + + RetrySettings overflowMaxSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(Long.MAX_VALUE)) + .build(); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, overflowMaxSettings); + assertEquals(200L, resumableStreamIterator.checkRetryBudgetAndGetDelay(twoHundredMsException)); + long backoffDelay = resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException); + assertThat(backoffDelay).isAtLeast(5L); + assertThat(backoffDelay).isAtMost(10L); + + RetrySettings overflowInitialAndMaxSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(Long.MAX_VALUE)) + .setMaxRetryDelayDuration(java.time.Duration.ofSeconds(Long.MAX_VALUE)) + .build(); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, overflowInitialAndMaxSettings); + assertThat(resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException)) + .isAtLeast(1L); + } + + @Test + public void unsetMaxRetryDelayUsesDefaultCeilingForClientBackoff() { + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, RetrySettings.newBuilder().setRetryDelayMultiplier(10.0).build()); + SpannerException absentDelayException = + new RetryableException( + errorCodeParameter, + "absent delay", + errorCodeParameter.getGrpcStatus().asRuntimeException()); + long maxObserved = 0L; + for (int i = 0; i < 6; i++) { + long delayMillis = resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException); + assertThat(delayMillis).isAtLeast(1L); + assertThat(delayMillis).isAtMost(32_000L); + maxObserved = Math.max(maxObserved, delayMillis); + } + // Intervals 1, 10, 100, 1000, 10000, 32000 ([0.5x, 1.0x] jitter): the 32s ceiling is reached. + assertThat(maxObserved).isAtLeast(16_000L); + } + + @Test + public void corruptRetryInfoTrailerFallsBackToBackoff() { + Metadata badTrailers = new Metadata(); + badTrailers.put( + Metadata.Key.of("google.rpc.retryinfo-bin", Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + StatusRuntimeException corruptError = + Status.UNAVAILABLE.withDescription("corrupt").asRuntimeException(badTrailers); + SpannerException spannerException = SpannerExceptionFactory.newSpannerException(corruptError); + jitterRandom = () -> 1.0; + long delayMillis = resumableStreamIterator.checkRetryBudgetAndGetDelay(spannerException); + assertThat(delayMillis).isAtLeast(5L); + assertThat(delayMillis).isAtMost(10L); + } + + @Test + public void totalTimeoutHandlesSubMillisecondAndOverflow() { + // Positive sub-millisecond totalTimeout must be enforced rather than truncated to 0 + // (unlimited). + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setTotalTimeoutDuration(java.time.Duration.ofNanos(500_000L)) + .build()); + SpannerException exception = new RetryableException(errorCodeParameter, "failed by test"); + nanoTime = () -> 0L; + assertThat( + assertThrows( + SpannerException.class, + () -> resumableStreamIterator.checkRetryBudgetAndGetDelay(exception))) + .isSameInstanceAs(exception); + + // Maximum buildable totalTimeoutDuration must not overflow. + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, + RetrySettings.newBuilder() + .setTotalTimeoutDuration(java.time.Duration.ofMillis(Long.MAX_VALUE)) + .build()); + nanoTime = () -> 0L; + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); + } + + @Test + public void backoffRespectsDeterministicJitterBoundsAndFloor() { + SpannerException absentDelayException = + new RetryableException( + errorCodeParameter, + "absent delay", + errorCodeParameter.getGrpcStatus().asRuntimeException()); + + // [0.5x, 1.0x] jitter: 0.0 -> 50ms, 1.0 -> 100ms, capped strictly at 250ms maxRetryDelay. + RetrySettings bounded = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(100L)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(250L)) + .build(); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, bounded); + jitterRandom = () -> 0.0; + assertEquals(50L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + jitterRandom = () -> 1.0; + assertEquals(200L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + assertEquals(250L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + + // Unset initialRetryDelay and maxRetryDelay: floored at 1ms on attempt 1, capped at 32s. + initWithLimitAndRetrySettings( + Integer.MAX_VALUE, RetrySettings.newBuilder().setRetryDelayMultiplier(10.0).build()); + jitterRandom = () -> 0.0; + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + jitterRandom = () -> 1.0; + assertEquals(10L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + assertEquals(100L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + assertEquals(1_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + assertEquals( + 10_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + assertEquals( + 32_000L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + } + @Test(timeout = 60000L) public void customTotalTimeoutSmallerThanRetryDelay_doesNotRetry() { // Retrying is only allowed if the retry delay still fits in the remaining total timeout diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterTest.java index 15bf91fa9205..ae70487cc30c 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerCloudMonitoringExporterTest.java @@ -99,15 +99,17 @@ public class SpannerCloudMonitoringExporterTest { private InstrumentationScopeInfo scope; private String client_uid; + private Map clientAttributes; @Before public void setUp() { mockMetricServiceStub = Mockito.mock(MetricServiceStub.class, Mockito.withSettings().withoutAnnotations()); fakeMetricServiceClient = new FakeMetricServiceClient(mockMetricServiceStub); - exporter = new SpannerCloudMonitoringExporter(fakeMetricServiceClient); - - this.client_uid = BuiltInMetricsProvider.INSTANCE.createClientAttributes().get("client_uid"); + this.clientAttributes = new BuiltInMetricsProvider().createClientAttributes(); + this.client_uid = this.clientAttributes.get("client_uid"); + exporter = + new SpannerCloudMonitoringExporter(() -> null, clientAttributes, fakeMetricServiceClient); attributes = Attributes.builder() @@ -270,7 +272,8 @@ public void testExportingSkipsMetricsWithoutPointProjectOrFallbackProject() { @Test public void testExportingUsesFallbackProjectForMetricsWithUndefinedPointProject() { exporter = - new SpannerCloudMonitoringExporter(() -> "fallback-project", fakeMetricServiceClient); + new SpannerCloudMonitoringExporter( + () -> "fallback-project", clientAttributes, fakeMetricServiceClient); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(CreateTimeSeriesRequest.class); @@ -311,7 +314,8 @@ public void testExportingUsesFallbackProjectForMetricsWithUndefinedPointProject( @Test public void testExportingRoutesPointProjectAndFallbackProject() { exporter = - new SpannerCloudMonitoringExporter(() -> "fallback-project", fakeMetricServiceClient); + new SpannerCloudMonitoringExporter( + () -> "fallback-project", clientAttributes, fakeMetricServiceClient); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(CreateTimeSeriesRequest.class); @@ -655,31 +659,107 @@ public void testExportingHistogramDataWithExemplars() { .isEqualTo("test"); } + @Test + public void testExportingStampsPerProviderClientAttributes() { + ArgumentCaptor argumentCaptor = + ArgumentCaptor.forClass(CreateTimeSeriesRequest.class); + + UnaryCallable mockCallable = + mock(UnaryCallable.class, withSettings().withoutAnnotations()); + when(mockMetricServiceStub.createServiceTimeSeriesCallable()).thenReturn(mockCallable); + ApiFuture future = ApiFutures.immediateFuture(Empty.getDefaultInstance()); + when(mockCallable.futureCall(argumentCaptor.capture())).thenReturn(future); + + Map attrsA = new BuiltInMetricsProvider().createClientAttributes(); + Map attrsB = new BuiltInMetricsProvider().createClientAttributes(); + assertThat(attrsA.get(CLIENT_UID_KEY.getKey())) + .isNotEqualTo(attrsB.get(CLIENT_UID_KEY.getKey())); + + SpannerCloudMonitoringExporter exporterA = + new SpannerCloudMonitoringExporter(() -> null, attrsA, fakeMetricServiceClient); + SpannerCloudMonitoringExporter exporterB = + new SpannerCloudMonitoringExporter(() -> null, attrsB, fakeMetricServiceClient); + + LongPointData pointData = + ImmutableLongPointData.create( + 10, 15, Attributes.builder().put(PROJECT_ID_KEY, projectId).build(), 1L); + MetricData metricData = + ImmutableMetricData.createLongSum( + resource, + scope, + "spanner.googleapis.com/internal/client/" + OPERATION_COUNT_NAME, + "description", + "1", + ImmutableSumData.create( + true, AggregationTemporality.CUMULATIVE, ImmutableList.of(pointData))); + + exporterA.export(Collections.singletonList(metricData)); + exporterB.export(Collections.singletonList(metricData)); + + assertThat(argumentCaptor.getAllValues()).hasSize(2); + assertThat( + argumentCaptor + .getAllValues() + .get(0) + .getTimeSeries(0) + .getMetric() + .getLabelsMap() + .get(CLIENT_UID_KEY.getKey())) + .isEqualTo(attrsA.get(CLIENT_UID_KEY.getKey())); + assertThat( + argumentCaptor + .getAllValues() + .get(1) + .getTimeSeries(0) + .getMetric() + .getLabelsMap() + .get(CLIENT_UID_KEY.getKey())) + .isEqualTo(attrsB.get(CLIENT_UID_KEY.getKey())); + } + @Test public void getAggregationTemporality() throws IOException { SpannerCloudMonitoringExporter actualExporter = - SpannerCloudMonitoringExporter.create(() -> null, null, null, null); - assertThat(actualExporter.getAggregationTemporality(InstrumentType.COUNTER)) - .isEqualTo(AggregationTemporality.CUMULATIVE); + SpannerCloudMonitoringExporter.create(() -> null, clientAttributes, null, null, null); + try { + assertThat(actualExporter.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } finally { + actualExporter.shutdown(); + } } @Test public void testUniverseDomain() throws IOException { SpannerCloudMonitoringExporter actualExporter = - SpannerCloudMonitoringExporter.create(() -> null, null, null, "abc.goog"); - MetricServiceSettings metricServiceSettings = - actualExporter.getMetricServiceClient().getSettings(); - - assertEquals("abc.goog", metricServiceSettings.getUniverseDomain()); - assertEquals("monitoring.abc.goog:443", metricServiceSettings.getEndpoint()); - - actualExporter = SpannerCloudMonitoringExporter.create( - () -> null, null, "monitoringa.abc.goog:443", "abc.goog"); - metricServiceSettings = actualExporter.getMetricServiceClient().getSettings(); + () -> null, clientAttributes, null, null, "partner.example"); + try { + MetricServiceSettings metricServiceSettings = + actualExporter.getMetricServiceClient().getSettings(); + + assertEquals("partner.example", metricServiceSettings.getUniverseDomain()); + assertEquals("monitoring.partner.example:443", metricServiceSettings.getEndpoint()); + } finally { + actualExporter.shutdown(); + } - assertEquals("abc.goog", metricServiceSettings.getUniverseDomain()); - assertEquals("monitoringa.abc.goog:443", metricServiceSettings.getEndpoint()); + SpannerCloudMonitoringExporter overrideExporter = + SpannerCloudMonitoringExporter.create( + () -> null, + clientAttributes, + null, + "monitoringa.partner.example:443", + "partner.example"); + try { + MetricServiceSettings metricServiceSettings = + overrideExporter.getMetricServiceClient().getSettings(); + + assertEquals("partner.example", metricServiceSettings.getUniverseDomain()); + assertEquals("monitoringa.partner.example:443", metricServiceSettings.getEndpoint()); + } finally { + overrideExporter.shutdown(); + } } private static class FakeMetricServiceClient extends MetricServiceClient { diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerExceptionFactoryTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerExceptionFactoryTest.java index e7d45cee864c..f9c3c300357a 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerExceptionFactoryTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerExceptionFactoryTest.java @@ -276,4 +276,45 @@ public void resourceExhaustedWithGrpcStatusDetails() { assertThat(e.isRetryable()).isTrue(); assertThat(e.getRetryDelayInMillis()).isEqualTo(1001); } + + @Test + public void resourceExhaustedWithCorruptRetryInfoDoesNotThrow() { + Status status = + Status.fromCodeValue(Status.Code.RESOURCE_EXHAUSTED.value()) + .withDescription("Memory pushback"); + Metadata badRetryInfoTrailers = new Metadata(); + badRetryInfoTrailers.put( + Metadata.Key.of("google.rpc.retryinfo-bin", Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + SpannerException corruptTrailerEx = + SpannerExceptionFactory.newSpannerException( + new StatusRuntimeException(status, badRetryInfoTrailers)); + assertThat(corruptTrailerEx.getErrorCode()).isEqualTo(ErrorCode.RESOURCE_EXHAUSTED); + assertThat(corruptTrailerEx.isRetryable()).isFalse(); + assertThat(corruptTrailerEx.getRetryDelayInMillis()).isEqualTo(-1L); + + Metadata corruptAnyTrailers = new Metadata(); + com.google.protobuf.Any corruptAny = + com.google.protobuf.Any.newBuilder() + .setTypeUrl("type.googleapis.com/google.rpc.RetryInfo") + .setValue( + com.google.protobuf.ByteString.copyFrom( + new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF})) + .build(); + com.google.rpc.Status rpcStatus = + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.RESOURCE_EXHAUSTED_VALUE) + .setMessage("Memory pushback") + .addDetails(corruptAny) + .build(); + corruptAnyTrailers.put( + Metadata.Key.of("grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER), + rpcStatus.toByteArray()); + SpannerException corruptAnyEx = + SpannerExceptionFactory.newSpannerException( + new StatusRuntimeException(status, corruptAnyTrailers)); + assertThat(corruptAnyEx.getErrorCode()).isEqualTo(ErrorCode.RESOURCE_EXHAUSTED); + assertThat(corruptAnyEx.isRetryable()).isFalse(); + assertThat(corruptAnyEx.getRetryDelayInMillis()).isEqualTo(-1L); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerImplTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerImplTest.java index 1bcfde7d4e27..616d68d49846 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerImplTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerImplTest.java @@ -22,6 +22,9 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -49,6 +52,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.After; import org.junit.AfterClass; @@ -390,6 +394,54 @@ public void testCreateInstanceAdminClient_whenMockAdminSettings_assertException( assertNotNull(instanceAdminClient); } + @Test + public void testCloseClosesBuiltInMetrics() { + SpannerImpl spanner = new SpannerImpl(rpc, spannerOptions); + spanner.close(); + verify(spannerOptions).closeBuiltInMetrics(); + } + + @Test + public void testTimedCloseCallsTimedCloseBuiltInMetrics() { + SpannerImpl spanner = new SpannerImpl(rpc, spannerOptions); + spanner.close(500L, TimeUnit.MILLISECONDS); + verify(spannerOptions).closeBuiltInMetrics(anyLong(), eq(TimeUnit.NANOSECONDS)); + } + + @Test + public void testCloseSwallowsRuntimeExceptionFromCloseBuiltInMetrics() { + doThrow(new RuntimeException("metrics shutdown failed")) + .when(spannerOptions) + .closeBuiltInMetrics(); + SpannerImpl spanner = new SpannerImpl(rpc, spannerOptions); + spanner.close(); + verify(rpc).shutdown(); + verify(spannerOptions).closeBuiltInMetrics(); + } + + @Test + public void testTimedClosePassesRemainingDeadlineToCloseBuiltInMetrics() { + // Consume ~100ms inside rpc.shutdown() without sleeping, so the remaining budget must shrink. + Mockito.doAnswer( + invocation -> { + long start = System.nanoTime(); + while (System.nanoTime() - start < TimeUnit.MILLISECONDS.toNanos(100L)) { + Thread.yield(); + } + return null; + }) + .when(rpc) + .shutdown(); + SpannerImpl spanner = new SpannerImpl(rpc, spannerOptions); + ArgumentCaptor remaining = ArgumentCaptor.forClass(Long.class); + + spanner.close(500L, TimeUnit.MILLISECONDS); + + verify(spannerOptions).closeBuiltInMetrics(remaining.capture(), eq(TimeUnit.NANOSECONDS)); + assertThat(remaining.getValue()).isAtLeast(0L); + assertThat(remaining.getValue()).isAtMost(TimeUnit.MILLISECONDS.toNanos(400L)); + } + private void closeSpannerAndIncludeStacktrace(Spanner spanner) { spanner.close(); } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerOptionsTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerOptionsTest.java index 8406f2cf5d1b..024ff529d70c 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerOptionsTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/SpannerOptionsTest.java @@ -37,6 +37,10 @@ import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ServerStreamingCallSettings; import com.google.api.gax.rpc.UnaryCallSettings; +import com.google.auth.ApiKeyCredentials; +import com.google.auth.Credentials; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.NoCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.TransportOptions; @@ -53,6 +57,7 @@ import com.google.common.base.Strings; import com.google.common.util.concurrent.Futures; import com.google.spanner.v1.BatchCreateSessionsRequest; +import com.google.spanner.v1.BatchWriteRequest; import com.google.spanner.v1.BeginTransactionRequest; import com.google.spanner.v1.CommitRequest; import com.google.spanner.v1.CreateSessionRequest; @@ -79,7 +84,9 @@ import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.IOException; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -87,9 +94,12 @@ import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; +import java.util.logging.Handler; import java.util.logging.Level; +import java.util.logging.LogRecord; import java.util.logging.Logger; import javax.annotation.Nonnull; +import org.jspecify.annotations.Nullable; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -937,6 +947,11 @@ public void testSpannerCallContextTimeoutConfigurator_NullValues() { inputCallContext, PartitionReadRequest.getDefaultInstance(), SpannerGrpc.getPartitionReadMethod())); + assertNull( + configurator.configure( + inputCallContext, + BatchWriteRequest.getDefaultInstance(), + SpannerGrpc.getBatchWriteMethod())); } @Test @@ -951,6 +966,8 @@ public void testSpannerCallContextTimeoutConfigurator_WithTimeouts() { configurator.withPartitionReadTimeoutDuration(Duration.ofSeconds(6L)); configurator.withReadTimeoutDuration(Duration.ofSeconds(7L)); configurator.withRollbackTimeoutDuration(Duration.ofSeconds(8L)); + configurator.withBatchWriteTimeoutDuration(Duration.ofSeconds(9L)); + assertEquals(Duration.ofSeconds(9L), configurator.getBatchWriteTimeoutDuration()); ApiCallContext inputCallContext = GrpcCallContext.createDefault(); @@ -1056,6 +1073,14 @@ public void testSpannerCallContextTimeoutConfigurator_WithTimeouts() { SpannerGrpc.getPartitionReadMethod()) .getTimeoutDuration()) .isEqualTo(Duration.ofSeconds(6L)); + ApiCallContext batchWriteCallContext = + configurator.configure( + inputCallContext, + BatchWriteRequest.getDefaultInstance(), + SpannerGrpc.getBatchWriteMethod()); + assertThat(batchWriteCallContext.getTimeoutDuration()).isEqualTo(Duration.ofSeconds(9L)); + assertThat(batchWriteCallContext.getStreamWaitTimeoutDuration()) + .isEqualTo(Duration.ofSeconds(9L)); } @Test @@ -1558,6 +1583,7 @@ public void testCustomProviderKeepsCloudMonitoringSinkOnNonOmni() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") + .setEmulatorHost(null) .setCredentials(NoCredentials.getInstance()) .setClientMetricsProvider(provider) .build(); @@ -2243,4 +2269,1041 @@ public void testUniverseDomain_RejectsInvalidAndUrlInjectionValues() { explicitHostException.getMessage().contains("Invalid universe domain")); } } + + @Test + public void testUniverseDomainFromEnvironmentVariable() { + useUniverseDomainEnvironment("partner.example"); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build(); + assertNull(options.getUniverseDomain()); + assertEquals("https://spanner.partner.example", options.getHost()); + assertEquals("spanner.partner.example:443", options.getEndpoint()); + assertEquals("partner.example", options.getSpannerStubSettings().getUniverseDomain()); + assertEquals("spanner.partner.example:443", options.getSpannerStubSettings().getEndpoint()); + assertEquals("partner.example", options.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.partner.example:443", options.getInstanceAdminStubSettings().getEndpoint()); + assertEquals("partner.example", options.getDatabaseAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.partner.example:443", options.getDatabaseAdminStubSettings().getEndpoint()); + String hostDomain = options.getHost().substring("https://spanner.".length()); + assertEquals(hostDomain, options.getSpannerStubSettings().getUniverseDomain()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testExplicitUniverseDomainOverridesEnvironmentVariable() { + useUniverseDomainEnvironment("env.example"); + try { + // Control check: confirm the environment value is active when unset. + SpannerOptions envDefaultOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build(); + assertEquals("https://spanner.env.example", envDefaultOptions.getHost()); + assertEquals("env.example", envDefaultOptions.getSpannerStubSettings().getUniverseDomain()); + + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build(); + assertEquals("explicit.example", options.getUniverseDomain()); + assertEquals("https://spanner.explicit.example", options.getHost()); + assertEquals("spanner.explicit.example:443", options.getEndpoint()); + assertEquals("explicit.example", options.getSpannerStubSettings().getUniverseDomain()); + assertEquals("spanner.explicit.example:443", options.getSpannerStubSettings().getEndpoint()); + assertEquals("explicit.example", options.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.explicit.example:443", options.getInstanceAdminStubSettings().getEndpoint()); + assertEquals("explicit.example", options.getDatabaseAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.explicit.example:443", options.getDatabaseAdminStubSettings().getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testToBuilderClearUniverseDomainRespectsEnvironment() { + useUniverseDomainEnvironment("env.example"); + try { + SpannerOptions initial = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build(); + SpannerOptions cleared = initial.toBuilder().setUniverseDomain("").build(); + assertEquals("", cleared.getUniverseDomain()); + assertEquals("https://spanner.env.example", cleared.getHost()); + assertEquals("spanner.env.example:443", cleared.getEndpoint()); + assertEquals("env.example", cleared.getSpannerStubSettings().getUniverseDomain()); + assertEquals("spanner.env.example:443", cleared.getSpannerStubSettings().getEndpoint()); + assertEquals("env.example", cleared.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals("spanner.env.example:443", cleared.getInstanceAdminStubSettings().getEndpoint()); + assertEquals("env.example", cleared.getDatabaseAdminStubSettings().getUniverseDomain()); + assertEquals("spanner.env.example:443", cleared.getDatabaseAdminStubSettings().getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testToBuilderClearUniverseDomainFallsBackToDefaultWhenEnvUnsetOrEmpty() { + for (String envUniverseDomain : new String[] {null, ""}) { + useUniverseDomainEnvironment(envUniverseDomain); + try { + SpannerOptions initial = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build(); + SpannerOptions cleared = initial.toBuilder().setUniverseDomain("").build(); + assertEquals("", cleared.getUniverseDomain()); + assertEquals("googleapis.com", cleared.getResolvedUniverseDomain()); + assertEquals("https://spanner.googleapis.com", cleared.getHost()); + assertEquals("spanner.googleapis.com:443", cleared.getEndpoint()); + assertEquals("googleapis.com", cleared.getSpannerStubSettings().getUniverseDomain()); + assertEquals("spanner.googleapis.com:443", cleared.getSpannerStubSettings().getEndpoint()); + assertEquals("googleapis.com", cleared.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.googleapis.com:443", cleared.getInstanceAdminStubSettings().getEndpoint()); + assertEquals("googleapis.com", cleared.getDatabaseAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.googleapis.com:443", cleared.getDatabaseAdminStubSettings().getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + } + + @Test + public void testHasValidUniverseDomainWithEnvironmentAndClearedBuilder() throws IOException { + Credentials partnerCredentials = credentialsForUniverseDomain("partner.example"); + Credentials gduCredentials = credentialsForUniverseDomain("googleapis.com"); + + useUniverseDomainEnvironment("partner.example"); + try { + SpannerOptions matchingOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(partnerCredentials) + .setEmulatorHost(null) + .build(); + assertTrue(matchingOptions.hasValidUniverseDomain()); + + SpannerOptions mismatchedOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(gduCredentials) + .setEmulatorHost(null) + .build(); + assertFalse(mismatchedOptions.hasValidUniverseDomain()); + + SpannerOptions clearedMatching = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(partnerCredentials) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build() + .toBuilder() + .setUniverseDomain("") + .build(); + assertTrue(clearedMatching.hasValidUniverseDomain()); + + SpannerOptions clearedMismatched = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(gduCredentials) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build() + .toBuilder() + .setUniverseDomain("") + .build(); + assertFalse(clearedMismatched.hasValidUniverseDomain()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + + for (String envUniverseDomain : new String[] {null, ""}) { + useUniverseDomainEnvironment(envUniverseDomain); + try { + SpannerOptions clearedGdu = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(gduCredentials) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build() + .toBuilder() + .setUniverseDomain("") + .build(); + assertTrue(clearedGdu.hasValidUniverseDomain()); + + SpannerOptions clearedPartner = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(partnerCredentials) + .setEmulatorHost(null) + .setUniverseDomain("explicit.example") + .build() + .toBuilder() + .setUniverseDomain("") + .build(); + assertFalse(clearedPartner.hasValidUniverseDomain()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + } + + @Test + public void testHasValidUniverseDomainWithApiKeyCredentialsAndEnvironment() throws IOException { + useUniverseDomainEnvironment("partner.example"); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(ApiKeyCredentials.create("test-api-key")) + .setEmulatorHost(null) + .build(); + assertTrue(options.hasValidUniverseDomain()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + private static Credentials credentialsForUniverseDomain(String universeDomain) { + return new GoogleCredentials(new AccessToken("test-token", null)) { + @Override + public String getUniverseDomain() { + return universeDomain; + } + }; + } + + @Test + public void testEmptyUniverseDomainEnvironmentVariableFallsBackToDefault() { + useUniverseDomainEnvironment(""); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build(); + assertNull(options.getUniverseDomain()); + assertEquals("https://spanner.googleapis.com", options.getHost()); + assertEquals("spanner.googleapis.com:443", options.getEndpoint()); + assertEquals("googleapis.com", options.getSpannerStubSettings().getUniverseDomain()); + assertEquals("spanner.googleapis.com:443", options.getSpannerStubSettings().getEndpoint()); + assertEquals("googleapis.com", options.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.googleapis.com:443", options.getInstanceAdminStubSettings().getEndpoint()); + assertEquals("googleapis.com", options.getDatabaseAdminStubSettings().getUniverseDomain()); + assertEquals( + "spanner.googleapis.com:443", options.getDatabaseAdminStubSettings().getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testResolveUniverseDomainPrecedenceAndValidation() { + // Precedence: explicit > environment > googleapis.com. + assertEquals("googleapis.com", SpannerOptions.resolveUniverseDomain(null, null)); + assertEquals("googleapis.com", SpannerOptions.resolveUniverseDomain("", null)); + assertEquals("googleapis.com", SpannerOptions.resolveUniverseDomain(null, "")); + assertEquals("googleapis.com", SpannerOptions.resolveUniverseDomain("", "")); + assertEquals("partner.example", SpannerOptions.resolveUniverseDomain(null, "partner.example")); + assertEquals("partner.example", SpannerOptions.resolveUniverseDomain("", "partner.example")); + assertEquals( + "explicit.example", + SpannerOptions.resolveUniverseDomain("explicit.example", "env.example")); + assertEquals("explicit.example", SpannerOptions.resolveUniverseDomain("explicit.example", "")); + + IllegalArgumentException invalidEnvException = + assertThrows( + IllegalArgumentException.class, + () -> SpannerOptions.resolveUniverseDomain(null, "evil.com/path")); + assertTrue(invalidEnvException.getMessage().contains("Invalid universe domain")); + + IllegalArgumentException invalidConfiguredException = + assertThrows( + IllegalArgumentException.class, + () -> SpannerOptions.resolveUniverseDomain("evil.com/path", "partner.example")); + assertTrue(invalidConfiguredException.getMessage().contains("Invalid universe domain")); + + // End-to-end fail-closed validation across default, emulator, and explicit-host builders. + useUniverseDomainEnvironment("evil.com/path"); + try { + IllegalArgumentException defaultException = + assertThrows( + IllegalArgumentException.class, + () -> + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build()); + assertTrue(defaultException.getMessage().contains("Invalid universe domain")); + + IllegalArgumentException emulatorException = + assertThrows( + IllegalArgumentException.class, + () -> + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setEmulatorHost("localhost:9010") + .build()); + assertTrue(emulatorException.getMessage().contains("Invalid universe domain")); + + IllegalArgumentException explicitHostException = + assertThrows( + IllegalArgumentException.class, + () -> + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setHost("https://custom.host") + .build()); + assertTrue(explicitHostException.getMessage().contains("Invalid universe domain")); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testCloudMonitoringExporterHonorsResolvedUniverseDomain() throws Exception { + for (String[] envAndExpected : + new String[][] {{"partner.example", "partner.example"}, {"", "googleapis.com"}}) { + String envUniverseDomain = envAndExpected[0]; + String expected = envAndExpected[1]; + useUniverseDomainEnvironment(envUniverseDomain); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build(); + assertEquals(expected, options.getResolvedUniverseDomain()); + SpannerCloudMonitoringExporter exporter = + SpannerCloudMonitoringExporter.create( + () -> "test-project", + Collections.emptyMap(), + NoCredentials.getInstance(), + null, + options.getResolvedUniverseDomain()); + try { + assertEquals( + expected, exporter.getMetricServiceClient().getSettings().getUniverseDomain()); + assertEquals( + "monitoring." + expected + ":443", + exporter.getMetricServiceClient().getSettings().getEndpoint()); + } finally { + exporter.shutdown(); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + } + + @Test + public void testBuiltInMetricsProviderReceivesResolvedUniverseDomain() { + for (String[] envAndExpected : + new String[][] {{"partner.example", "partner.example"}, {"", "googleapis.com"}}) { + String envUniverseDomain = envAndExpected[0]; + String expected = envAndExpected[1]; + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public @Nullable String getUniverseDomain() { + return envUniverseDomain; + } + + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + try { + // The Cloud Monitoring tracer factory is only created for clients with real credentials. + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .setEmulatorHost(null) + .build(); + assertNull(options.getUniverseDomain()); + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + + options.getBuiltInOpenTelemetry(); + options.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + options.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); + + assertEquals(Arrays.asList(expected, expected, expected), provider.universeDomains); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + } + + @Test + public void testEnableGrpcMetricsSkipsCloudMonitoringWithNoCredentials() { + useGrpcBuiltInMetricsEnabledEnvironment(); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder = + InstantiatingGrpcChannelProvider.newBuilder(); + + options.enablegRPCMetrics(channelProviderBuilder, /* isEmulatorEnabled= */ false); + + assertTrue(provider.credentials.isEmpty()); + assertNull(channelProviderBuilder.getChannelConfigurator()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testEnableGrpcMetricsSkipsCloudMonitoringWithUsePlainText() { + useGrpcBuiltInMetricsEnabledEnvironment(); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setHost("http://localhost:1234") + .usePlainText() + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder = + InstantiatingGrpcChannelProvider.newBuilder(); + + options.enablegRPCMetrics(channelProviderBuilder, /* isEmulatorEnabled= */ false); + + assertTrue(provider.credentials.isEmpty()); + assertNull(channelProviderBuilder.getChannelConfigurator()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testEnableGrpcMetricsKeepsCustomSinkWithNoCredentials() { + useGrpcBuiltInMetricsEnabledEnvironment(); + OpenTelemetrySdk customOpenTelemetry = + OpenTelemetrySdk.builder() + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader(InMemoryMetricReader.create()) + .build()) + .build(); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .setClientMetricsProvider( + CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + .build(); + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder = + InstantiatingGrpcChannelProvider.newBuilder(); + + options.enablegRPCMetrics(channelProviderBuilder, /* isEmulatorEnabled= */ false); + + assertTrue(provider.credentials.isEmpty()); + assertEquals(Collections.singletonList(customOpenTelemetry), provider.customOpenTelemetries); + assertNotNull(channelProviderBuilder.getChannelConfigurator()); + } finally { + customOpenTelemetry.close(); + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testNoCredentialsFirstDoesNotLockSingletonForLaterAuthenticatedClient() { + useGrpcBuiltInMetricsEnabledEnvironment(); + try { + RecordingBuiltInMetricsProvider sharedProvider = new RecordingBuiltInMetricsProvider(); + SpannerOptions noCredOptions = + SpannerOptions.newBuilder() + .setProjectId("unauth-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + noCredOptions.builtInMetricsProvider = sharedProvider; + + GoogleCredentials googleCredentials = + GoogleCredentials.create(new AccessToken("test-token", null)); + SpannerOptions authOptions = + SpannerOptions.newBuilder() + .setProjectId("auth-project") + .setCredentials(googleCredentials) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + authOptions.builtInMetricsProvider = sharedProvider; + + noCredOptions.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + assertNull(noCredOptions.getBuiltInOpenTelemetry()); + + authOptions.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + assertNotNull(authOptions.getBuiltInOpenTelemetry()); + + assertEquals(Arrays.asList(googleCredentials, googleCredentials), sharedProvider.credentials); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testEnableGrpcMetricsRespectsJmhOverrideWithNoCredentials() { + useGrpcBuiltInMetricsEnabledEnvironment(); + String previousJmhEnabled = System.getProperty("jmh.enabled"); + System.setProperty("jmh.enabled", "true"); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + + options.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + assertNotNull(options.getBuiltInOpenTelemetry()); + + assertEquals( + Arrays.asList(NoCredentials.getInstance(), NoCredentials.getInstance()), + provider.credentials); + } finally { + if (previousJmhEnabled == null) { + System.clearProperty("jmh.enabled"); + } else { + System.setProperty("jmh.enabled", previousJmhEnabled); + } + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testGetBuiltInOpenTelemetryReturnsNullWithoutCredentialsOrWhenDisabled() { + useGrpcBuiltInMetricsEnabledEnvironment(); + try { + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + + SpannerOptions noCredOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build(); + noCredOptions.builtInMetricsProvider = provider; + assertNull(noCredOptions.getBuiltInOpenTelemetry()); + + SpannerOptions disabledOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(false) + .build(); + disabledOptions.builtInMetricsProvider = provider; + assertNull(disabledOptions.getBuiltInOpenTelemetry()); + + SpannerOptions nullCredOptions = + new TestSpannerOptions( + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true)) { + @Override + public Credentials getCredentials() { + return null; + } + }; + nullCredOptions.builtInMetricsProvider = provider; + assertNull(nullCredOptions.getBuiltInOpenTelemetry()); + nullCredOptions.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + + assertTrue(provider.credentials.isEmpty()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + private static void useGrpcBuiltInMetricsEnabledEnvironment() { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + } + + @Test + public void testBuiltInMetricsDisabledForCustomHostWithoutExplicitTarget() { + useGrpcBuiltInMetricsEnabledEnvironment(); + try { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .build(); + assertFalse(options.isEnableBuiltInMetrics()); + assertFalse(options.isEnableChannelPoolBuiltInMetrics()); + + RecordingBuiltInMetricsProvider provider = new RecordingBuiltInMetricsProvider(); + options.builtInMetricsProvider = provider; + + assertNull(options.getBuiltInOpenTelemetry()); + options.enablegRPCMetrics( + InstantiatingGrpcChannelProvider.newBuilder(), /* isEmulatorEnabled= */ false); + options.getApiTracerFactory(/* isAdminClient= */ false, /* isEmulatorEnabled= */ false); + options.initializeBuiltInMetrics(DatabaseId.of("tpc-project", "i", "d")); + + assertTrue(provider.universeDomains.isEmpty()); + assertTrue(provider.fallbackProjects.isEmpty()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testBuiltInMetricsEnabledForDefaultUniverseHosts() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + String[] defaultUniverseHosts = { + null, + "", + "https://spanner.googleapis.com", + "https://SPANNER.GOOGLEAPIS.COM:443/", + "https://spanner.us-central1.rep.googleapis.com", + "https://private.googleapis.com", + "https://restricted.googleapis.com", + }; + for (String host : defaultUniverseHosts) { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setHost(host) + .build(); + assertTrue( + "Expected built-in metrics enabled for host: " + host, + options.isEnableBuiltInMetrics()); + } + // Contrast check: ensure the default-universe allowlist is not vacuously true for all hosts. + SpannerOptions nonDefaultHost = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .build(); + assertFalse(nonDefaultHost.isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testBuiltInMetricsFailClosedForSpoofedAndMalformedHosts() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + String[] nonDefaultOrMalformedHosts = { + "https://spanner.googleapis.com.evil.com", + "https://googleapis.com", + "https://.googleapis.com", + "http://localhost:9010", + "spanner.googleapis.com:443", + "not-a-url", + }; + for (String host : nonDefaultOrMalformedHosts) { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setHost(host) + .build(); + assertFalse( + "Expected built-in metrics disabled for host: " + host, + options.isEnableBuiltInMetrics()); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testBuiltInMetricsEnabledForCustomHostWithExplicitTarget() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + SpannerOptions withBuilderUniverse = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setUniverseDomain("tpc.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(withBuilderUniverse.isEnableBuiltInMetrics()); + + @SuppressWarnings("deprecation") + SpannerOptions withBuilderMonitoringHost = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setMonitoringHost("monitoring.tpc.example:443") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(withBuilderMonitoringHost.isEnableBuiltInMetrics()); + + @SuppressWarnings("deprecation") + SpannerOptions withBlankMonitoringHost = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setMonitoringHost(" ") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse(withBlankMonitoringHost.isEnableBuiltInMetrics()); + + SpannerOptions withEmptyUniverse = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setUniverseDomain("") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse(withEmptyUniverse.isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + + useUniverseDomainEnvironment("tpc.example"); + try { + SpannerOptions withEnvUniverse = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(withEnvUniverse.isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public String getMonitoringHost() { + return "monitoring.tpc.example:443"; + } + }); + try { + SpannerOptions withEnvMonitoringHost = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(withEnvMonitoringHost.isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testCustomHostToBuilderReEvaluatesBuiltInMetrics() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + SpannerOptions customOnly = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse(customOnly.isEnableBuiltInMetrics()); + + assertTrue( + customOnly.toBuilder().setUniverseDomain("tpc.example").build().isEnableBuiltInMetrics()); + @SuppressWarnings("deprecation") + SpannerOptions withMonitoringHost = + customOnly.toBuilder().setMonitoringHost("monitoring.tpc.example:443").build(); + assertTrue(withMonitoringHost.isEnableBuiltInMetrics()); + assertTrue(customOnly.toBuilder().setHost(null).build().isEnableBuiltInMetrics()); + + SpannerOptions explicitlyDisabled = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setBuiltInMetricsEnabled(false) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse( + explicitlyDisabled.toBuilder() + .setUniverseDomain("tpc.example") + .build() + .isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testCustomHostPreservesCustomMetricsProvider() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + CustomOpenTelemetryMetricsProvider provider = + CustomOpenTelemetryMetricsProvider.create(OpenTelemetry.noop()); + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(NoCredentials.getInstance()) + .setClientMetricsProvider(provider) + .build(); + assertFalse(options.isEnableBuiltInMetrics()); + assertSame(provider, options.getClientMetricsProvider()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testCustomHostWarningSuppressedForEmulatorAndPlainText() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + Logger spannerOptionsLogger = Logger.getLogger(SpannerOptions.class.getName()); + Level previousLevel = spannerOptionsLogger.getLevel(); + List warnings = new ArrayList<>(); + Handler handler = + new Handler() { + @Override + public void publish(LogRecord record) { + if (record.getLevel().intValue() >= Level.WARNING.intValue()) { + warnings.add(record); + } + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + spannerOptionsLogger.addHandler(handler); + spannerOptionsLogger.setLevel(Level.WARNING); + try { + SpannerOptions customHttps = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .build(); + assertFalse(customHttps.isEnableBuiltInMetrics()); + assertEquals(1, warnings.size()); + assertTrue(warnings.get(0).getMessage().contains("Disabling built-in Cloud Monitoring")); + + warnings.clear(); + SpannerOptions emulatorOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setEmulatorHost("localhost:9010") + .build(); + assertFalse(emulatorOptions.isEnableBuiltInMetrics()); + assertTrue(warnings.isEmpty()); + + SpannerOptions plainTextCustom = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setHost("http://localhost:9010") + .usePlainText() + .build(); + assertFalse(plainTextCustom.isEnableBuiltInMetrics()); + assertTrue(warnings.isEmpty()); + } finally { + spannerOptionsLogger.removeHandler(handler); + spannerOptionsLogger.setLevel(previousLevel); + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testCustomHostEdgeCasesAndToBuilderFromDefaultHost() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + // Additional fail-closed malformed / spoofed host shapes. + String[] additionalNonDefaultHosts = { + " ", "https://spanner.googleapis.com@evil.com", "https://spanner.googleapis.com.", + }; + for (String host : additionalNonDefaultHosts) { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setHost(host) + .build(); + assertFalse( + "Expected built-in metrics disabled for host: " + host, + options.isEnableBuiltInMetrics()); + } + + // Explicit opt-in to googleapis.com keeps built-in metrics enabled on a custom host. + SpannerOptions explicitDefaultUniverse = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setUniverseDomain("googleapis.com") + .build(); + assertTrue(explicitDefaultUniverse.isEnableBuiltInMetrics()); + + // Reverse toBuilder() transition: default host (enabled) -> custom host (disabled). + SpannerOptions defaultOptions = + SpannerOptions.newBuilder() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .build(); + assertTrue(defaultOptions.isEnableBuiltInMetrics()); + assertFalse( + defaultOptions.toBuilder() + .setHost("https://spanner.tpc.example") + .build() + .isEnableBuiltInMetrics()); + + // Clearing monitoringHost via toBuilder() re-disables built-in metrics on a custom host. + @SuppressWarnings("deprecation") + SpannerOptions withMonitoringHost = + SpannerOptions.newBuilder() + .setProjectId("tpc-project") + .setEmulatorHost(null) + .setHost("https://spanner.tpc.example") + .setMonitoringHost("monitoring.tpc.example:443") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(withMonitoringHost.isEnableBuiltInMetrics()); + @SuppressWarnings("deprecation") + SpannerOptions clearedMonitoringHost = + withMonitoringHost.toBuilder().setMonitoringHost(null).build(); + assertFalse(clearedMonitoringHost.isEnableBuiltInMetrics()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + /** + * Records the universe domain, credentials, custom OpenTelemetry instances, and fallback projects + * that {@link SpannerOptions} passes to the metrics provider. + */ + private static final class RecordingBuiltInMetricsProvider extends BuiltInMetricsProvider { + private final List universeDomains = new ArrayList<>(); + private final List credentials = new ArrayList<>(); + private final List customOpenTelemetries = new ArrayList<>(); + private final List fallbackProjects = new ArrayList<>(); + + @Override + synchronized OpenTelemetry getOrCreateOpenTelemetry( + String projectId, Credentials credentials, String monitoringHost, String universeDomain) { + universeDomains.add(universeDomain); + this.credentials.add(credentials); + return OpenTelemetry.noop(); + } + + @Override + void enableGrpcMetrics( + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder, + String projectId, + Credentials credentials, + String monitoringHost, + String universeDomain) { + universeDomains.add(universeDomain); + this.credentials.add(credentials); + } + + @Override + void enableGrpcMetrics( + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder, + OpenTelemetry openTelemetry) { + customOpenTelemetries.add(openTelemetry); + super.enableGrpcMetrics(channelProviderBuilder, openTelemetry); + } + + @Override + synchronized void setProjectIdIfAbsent(String projectId) { + fallbackProjects.add(projectId); + } + } + + private static void useUniverseDomainEnvironment(@Nullable String universeDomain) { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public @Nullable String getUniverseDomain() { + return universeDomain; + } + }); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryBudgetMockServerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryBudgetMockServerTest.java index d920c16e07bb..86d791aecf57 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryBudgetMockServerTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryBudgetMockServerTest.java @@ -285,7 +285,7 @@ public void defaultStreamingRetrySettings_areNormalized() { .setTotalTimeoutDuration(Duration.ZERO) .setMaxAttempts(0) .setInitialRetryDelayDuration(Duration.ofMillis(10)) - .setMaxRetryDelayDuration(Duration.ofMillis(1000)) + .setMaxRetryDelayDuration(Duration.ofSeconds(32)) .build(); assertEquals(expected, spanner.getOptions().getSpannerRpcV1().getExecuteQueryRetrySettings()); assertEquals(expected, spanner.getOptions().getSpannerRpcV1().getReadRetrySettings()); diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryHelperTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryHelperTest.java new file mode 100644 index 000000000000..aa3573d4f909 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryHelperTest.java @@ -0,0 +1,425 @@ +/* + * 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 com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.api.gax.grpc.GrpcStatusCode; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; +import com.google.api.gax.rpc.ErrorDetails; +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.util.Durations; +import com.google.rpc.RetryInfo; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.ProtoUtils; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link StreamingRetryHelper}. */ +@RunWith(JUnit4.class) +public class StreamingRetryHelperTest { + + private static final Metadata.Key KEY_RETRY_INFO = + ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + private static final Metadata.Key KEY_RETRY_INFO_RAW = + Metadata.Key.of("google.rpc.retryinfo-bin", Metadata.BINARY_BYTE_MARSHALLER); + private static final Metadata.Key KEY_ERROR_DETAILS = + Metadata.Key.of("grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER); + private static final Duration ONE_MILLI = Duration.ofMillis(1L); + + private static StatusRuntimeException statusWithRetryInfo(long seconds, int nanos) { + Metadata trailers = new Metadata(); + RetryInfo retryInfo = + RetryInfo.newBuilder() + .setRetryDelay( + com.google.protobuf.Duration.newBuilder().setSeconds(seconds).setNanos(nanos)) + .build(); + trailers.put(KEY_RETRY_INFO, retryInfo); + return Status.UNAVAILABLE.withDescription("transient").asRuntimeException(trailers); + } + + private static Any corruptRetryInfoAny() { + return Any.newBuilder() + .setTypeUrl("type.googleapis.com/google.rpc.RetryInfo") + .setValue(ByteString.copyFrom(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF})) + .build(); + } + + @Test + public void isMaxAttemptsExhaustedCoversUnlimitedDisabledAndBounded() { + RetrySettings unlimited = RetrySettings.newBuilder().setMaxAttempts(0).build(); + assertFalse(StreamingRetryHelper.isMaxAttemptsExhausted(unlimited, 0)); + assertFalse(StreamingRetryHelper.isMaxAttemptsExhausted(unlimited, 100)); + + RetrySettings disabled = RetrySettings.newBuilder().setMaxAttempts(1).build(); + assertFalse(StreamingRetryHelper.isMaxAttemptsExhausted(disabled, 0)); + assertTrue(StreamingRetryHelper.isMaxAttemptsExhausted(disabled, 1)); + + RetrySettings bounded = RetrySettings.newBuilder().setMaxAttempts(3).build(); + assertFalse(StreamingRetryHelper.isMaxAttemptsExhausted(bounded, 2)); + assertTrue(StreamingRetryHelper.isMaxAttemptsExhausted(bounded, 3)); + assertTrue(StreamingRetryHelper.isMaxAttemptsExhausted(bounded, 4)); + + assertThrows( + NullPointerException.class, () -> StreamingRetryHelper.isMaxAttemptsExhausted(null, 1)); + } + + @Test + public void isTotalTimeoutExceededHandlesUnsetSubMsNegativeElapsedAndOverflow() { + RetrySettings unset = RetrySettings.newBuilder().build(); + assertFalse(StreamingRetryHelper.isTotalTimeoutExceeded(unset, 1_000_000L, Duration.ofDays(1))); + + RetrySettings subMs = + RetrySettings.newBuilder().setTotalTimeoutDuration(Duration.ofNanos(500_000L)).build(); + assertFalse(StreamingRetryHelper.isTotalTimeoutExceeded(subMs, 0L, Duration.ofNanos(100_000L))); + assertTrue(StreamingRetryHelper.isTotalTimeoutExceeded(subMs, 0L, Duration.ofNanos(500_000L))); + assertTrue(StreamingRetryHelper.isTotalTimeoutExceeded(subMs, 500_000L, Duration.ZERO)); + + RetrySettings oneSecond = + RetrySettings.newBuilder().setTotalTimeoutDuration(Duration.ofSeconds(1L)).build(); + assertFalse( + StreamingRetryHelper.isTotalTimeoutExceeded( + oneSecond, -TimeUnit.SECONDS.toNanos(60L), null)); + assertFalse( + StreamingRetryHelper.isTotalTimeoutExceeded( + oneSecond, -TimeUnit.SECONDS.toNanos(60L), Duration.ofMillis(-5L))); + assertTrue( + StreamingRetryHelper.isTotalTimeoutExceeded( + oneSecond, -TimeUnit.SECONDS.toNanos(60L), Duration.ofSeconds(1L))); + assertTrue( + StreamingRetryHelper.isTotalTimeoutExceeded( + oneSecond, TimeUnit.SECONDS.toNanos(60L), Duration.ofMillis(-5L))); + assertTrue( + StreamingRetryHelper.isTotalTimeoutExceeded( + oneSecond, TimeUnit.MILLISECONDS.toNanos(100L), Duration.ofMillis(Long.MAX_VALUE))); + + RetrySettings hugeTimeout = + RetrySettings.newBuilder() + .setTotalTimeoutDuration(Duration.ofMillis(Long.MAX_VALUE)) + .build(); + assertFalse(StreamingRetryHelper.isTotalTimeoutExceeded(hugeTimeout, 0L, Duration.ofDays(1))); + assertTrue( + StreamingRetryHelper.isTotalTimeoutExceeded( + hugeTimeout, 0L, Duration.ofSeconds(Long.MAX_VALUE))); + } + + @Test + public void extractServerRetryDelayCoversTrailersErrorDetailsCorruptAndBoundaries() { + assertNull(StreamingRetryHelper.extractServerRetryDelay(null)); + assertNull(StreamingRetryHelper.extractRawServerRetryDelay(null, null)); + + // Zero and negative delays return null for streaming retries while + // extractRawServerRetryDelay preserves valid protobuf durations. + StatusRuntimeException zero = statusWithRetryInfo(0L, 0); + assertNull(StreamingRetryHelper.extractServerRetryDelay(zero)); + assertEquals( + com.google.protobuf.Duration.getDefaultInstance(), + StreamingRetryHelper.extractRawServerRetryDelay(zero, null)); + + StatusRuntimeException negative = statusWithRetryInfo(-1L, 0); + assertNull(StreamingRetryHelper.extractServerRetryDelay(negative)); + assertEquals( + com.google.protobuf.Duration.newBuilder().setSeconds(-1L).build(), + StreamingRetryHelper.extractRawServerRetryDelay(negative, null)); + + // Positive sub-millisecond (including 1ns), 1ms, and multi-second values succeed. + assertEquals( + Duration.ofNanos(1L), + StreamingRetryHelper.extractServerRetryDelay(statusWithRetryInfo(0L, 1))); + assertEquals( + Duration.ofNanos(500_000L), + StreamingRetryHelper.extractServerRetryDelay(statusWithRetryInfo(0L, 500_000))); + assertEquals( + Duration.ofMillis(1L), + StreamingRetryHelper.extractServerRetryDelay(statusWithRetryInfo(0L, 1_000_000))); + assertEquals( + Duration.ofSeconds(2L, 500_000L), + StreamingRetryHelper.extractServerRetryDelay(statusWithRetryInfo(2L, 500_000))); + + // RetryInfo without retry_delay set returns null. + Metadata emptyRetryInfoTrailers = new Metadata(); + emptyRetryInfoTrailers.put(KEY_RETRY_INFO, RetryInfo.getDefaultInstance()); + assertNull( + StreamingRetryHelper.extractServerRetryDelay( + Status.UNAVAILABLE.asRuntimeException(emptyRetryInfoTrailers))); + + // Invalid protobuf Duration (out of range seconds or mismatched sign) returns null. + StatusRuntimeException invalidDuration = statusWithRetryInfo(400_000_000_000L, 0); + assertNull(StreamingRetryHelper.extractServerRetryDelay(invalidDuration)); + assertNull(StreamingRetryHelper.extractRawServerRetryDelay(invalidDuration, null)); + + // Corrupt google.rpc.retryinfo-bin trailer returns null instead of throwing. + Metadata corruptTrailer = new Metadata(); + corruptTrailer.put(KEY_RETRY_INFO_RAW, new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + assertNull( + StreamingRetryHelper.extractServerRetryDelay( + Status.UNAVAILABLE.asRuntimeException(corruptTrailer))); + + // Corrupt Any RetryInfo inside grpc-status-details-bin returns null instead of throwing. + com.google.rpc.Status corruptRpcStatus = + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.UNAVAILABLE_VALUE) + .addDetails(corruptRetryInfoAny()) + .build(); + Metadata corruptDetailsTrailers = new Metadata(); + corruptDetailsTrailers.put(KEY_ERROR_DETAILS, corruptRpcStatus.toByteArray()); + assertNull( + StreamingRetryHelper.extractServerRetryDelay( + Status.UNAVAILABLE.asRuntimeException(corruptDetailsTrailers))); + + // Corrupt ErrorDetails falls through independently to a valid google.rpc.retryinfo-bin trailer. + Metadata mixedTrailers = new Metadata(); + mixedTrailers.put(KEY_ERROR_DETAILS, corruptRpcStatus.toByteArray()); + mixedTrailers.put( + KEY_RETRY_INFO, RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(450L)).build()); + assertEquals( + Duration.ofMillis(450L), + StreamingRetryHelper.extractServerRetryDelay( + Status.UNAVAILABLE.asRuntimeException(mixedTrailers))); + + // ApiException with corrupt ErrorDetails falls through to cause's valid retryinfo-bin trailer. + ApiException corruptApiException = + ApiExceptionFactory.createException( + "corrupt error details", + statusWithRetryInfo(0L, (int) TimeUnit.MILLISECONDS.toNanos(450L)), + GrpcStatusCode.of(Status.Code.UNAVAILABLE), + /* retryable= */ true, + ErrorDetails.builder() + .setRawErrorMessages(Collections.singletonList(corruptRetryInfoAny())) + .build()); + assertEquals( + Duration.ofMillis(450L), StreamingRetryHelper.extractServerRetryDelay(corruptApiException)); + + // ApiException with valid ErrorDetails extracted via apiException parameter when error is null. + ApiException validApiException = + ApiExceptionFactory.createException( + "valid error details", + null, + GrpcStatusCode.of(Status.Code.UNAVAILABLE), + /* retryable= */ true, + ErrorDetails.builder() + .setRawErrorMessages( + Collections.singletonList( + Any.pack( + RetryInfo.newBuilder() + .setRetryDelay(Durations.fromMillis(678L)) + .build()))) + .build()); + assertEquals( + Durations.fromMillis(678L), + StreamingRetryHelper.extractRawServerRetryDelay(null, validApiException)); + + // Valid grpc-status-details-bin on wrapped cause chain is discovered. + com.google.rpc.Status validRpcStatus = + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.UNAVAILABLE_VALUE) + .addDetails( + Any.pack(RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(321L)).build())) + .build(); + Metadata detailsTrailers = new Metadata(); + detailsTrailers.put(KEY_ERROR_DETAILS, validRpcStatus.toByteArray()); + Throwable wrapped = + new RuntimeException("wrapper", Status.UNAVAILABLE.asRuntimeException(detailsTrailers)); + assertEquals(Duration.ofMillis(321L), StreamingRetryHelper.extractServerRetryDelay(wrapped)); + + // ErrorDetails containing RetryInfo without retry_delay falls through to trailer. + ApiException emptyDetailsWithTrailer = + ApiExceptionFactory.createException( + "empty retry info", + statusWithRetryInfo(0L, (int) TimeUnit.MILLISECONDS.toNanos(222L)), + GrpcStatusCode.of(Status.Code.UNAVAILABLE), + /* retryable= */ true, + ErrorDetails.builder() + .setRawErrorMessages( + Collections.singletonList(Any.pack(RetryInfo.getDefaultInstance()))) + .build()); + assertEquals( + Duration.ofMillis(222L), + StreamingRetryHelper.extractServerRetryDelay(emptyDetailsWithTrailer)); + } + + @Test + public void effectiveMaxRetryDelayCoversDefaultConfiguredSubMsAndValidation() { + RetrySettings unset = RetrySettings.newBuilder().build(); + assertEquals( + StreamingRetryHelper.DEFAULT_MAX_RETRY_DELAY, + StreamingRetryHelper.effectiveMaxRetryDelay(unset, Duration.ZERO)); + assertEquals( + StreamingRetryHelper.DEFAULT_MAX_RETRY_DELAY, + StreamingRetryHelper.effectiveMaxRetryDelay(unset, ONE_MILLI)); + + RetrySettings subMs = + RetrySettings.newBuilder().setMaxRetryDelayDuration(Duration.ofNanos(500_000L)).build(); + assertEquals( + Duration.ofNanos(500_000L), + StreamingRetryHelper.effectiveMaxRetryDelay(subMs, Duration.ZERO)); + assertEquals(ONE_MILLI, StreamingRetryHelper.effectiveMaxRetryDelay(subMs, ONE_MILLI)); + + assertThrows( + IllegalArgumentException.class, + () -> StreamingRetryHelper.effectiveMaxRetryDelay(unset, Duration.ofMillis(-1L))); + } + + @Test + public void computeRetryDelayClampsServerDelayAndAppliesUnifiedJitterAndEdgeCases() { + RetrySettings settings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(100L)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelayDuration(Duration.ofSeconds(10L)) + .build(); + + // Server delay within cap honored verbatim; below minDelay floored; above cap clamped. + assertEquals( + Duration.ofNanos(1L), + StreamingRetryHelper.computeRetryDelay( + settings, statusWithRetryInfo(0L, 1), 1, () -> 0.0, Duration.ZERO)); + assertEquals( + ONE_MILLI, + StreamingRetryHelper.computeRetryDelay( + settings, statusWithRetryInfo(0L, 500_000), 1, () -> 0.0, ONE_MILLI)); + assertEquals( + Duration.ofMillis(345L), + StreamingRetryHelper.computeRetryDelay( + settings, statusWithRetryInfo(0L, 345_000_000), 1, () -> 0.0, ONE_MILLI)); + assertEquals( + Duration.ofSeconds(10L), + StreamingRetryHelper.computeRetryDelay( + settings, + statusWithRetryInfo(TimeUnit.HOURS.toSeconds(3L), 0), + 1, + () -> 0.0, + ONE_MILLI)); + + // Unset initialRetryDelay: Duration.ZERO with minDelay=0, 1ms with minDelay=1ms. + RetrySettings unset = RetrySettings.newBuilder().setRetryDelayMultiplier(10.0).build(); + assertEquals( + Duration.ZERO, + StreamingRetryHelper.computeRetryDelay(unset, null, 1, () -> 1.0, Duration.ZERO)); + assertEquals( + ONE_MILLI, StreamingRetryHelper.computeRetryDelay(unset, null, 1, () -> 0.0, ONE_MILLI)); + assertEquals( + Duration.ofSeconds(32L), + StreamingRetryHelper.computeRetryDelay(unset, null, 6, () -> 1.0, ONE_MILLI)); + + // Sub-millisecond initialDelay: preserved with minDelay=0, floored to 1ms with minDelay=1ms. + RetrySettings subMs = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofNanos(500_000L)) + .setMaxRetryDelayDuration(Duration.ofNanos(500_000L)) + .build(); + assertEquals( + Duration.ofNanos(500_000L), + StreamingRetryHelper.computeRetryDelay(subMs, null, 1, () -> 1.0, Duration.ZERO)); + assertEquals( + ONE_MILLI, StreamingRetryHelper.computeRetryDelay(subMs, null, 1, () -> 0.0, ONE_MILLI)); + + // Huge maxRetryDelay: server delay of 120s is honored unclamped and backoff gives 100ms. + RetrySettings hugeMax = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(100L)) + .setMaxRetryDelayDuration(Duration.ofSeconds(Long.MAX_VALUE)) + .build(); + assertEquals( + Duration.ofSeconds(120L), + StreamingRetryHelper.computeRetryDelay( + hugeMax, statusWithRetryInfo(120L, 0), 1, () -> 1.0, Duration.ZERO)); + assertEquals( + Duration.ofMillis(100L), + StreamingRetryHelper.computeRetryDelay(hugeMax, null, 1, () -> 1.0, Duration.ZERO)); + + // Jitter random out-of-range (< 0, > 1, NaN, Infinity) and extreme attempt count (<= 0, 1000). + assertEquals( + Duration.ofMillis(50L), + StreamingRetryHelper.computeRetryDelay(settings, null, 0, () -> -5.0, Duration.ZERO)); + assertEquals( + Duration.ofMillis(100L), + StreamingRetryHelper.computeRetryDelay(settings, null, 1, () -> 5.0, Duration.ZERO)); + assertEquals( + Duration.ofMillis(100L), + StreamingRetryHelper.computeRetryDelay(settings, null, 1, () -> Double.NaN, Duration.ZERO)); + assertEquals( + Duration.ofMillis(100L), + StreamingRetryHelper.computeRetryDelay( + settings, null, 1, () -> Double.POSITIVE_INFINITY, Duration.ZERO)); + assertEquals( + Duration.ofSeconds(10L), + StreamingRetryHelper.computeRetryDelay(settings, null, 1000, () -> 1.0, Duration.ZERO)); + + // Overflowing initialRetryDelay and maxRetryDelay saturate cleanly without throwing. + RetrySettings overflowing = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(Long.MAX_VALUE)) + .setMaxRetryDelayDuration(Duration.ofSeconds(Long.MAX_VALUE)) + .build(); + assertEquals( + Duration.ofNanos(Long.MAX_VALUE), + StreamingRetryHelper.computeRetryDelay(overflowing, null, 1, () -> 1.0, Duration.ZERO)); + + // Sub-nanosecond jitter result rounds down to ZERO with minDelay=0, floored to 1ms with 1ms. + RetrySettings oneNano = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofNanos(1L)) + .setMaxRetryDelayDuration(Duration.ofNanos(1L)) + .build(); + assertEquals( + Duration.ZERO, + StreamingRetryHelper.computeRetryDelay(oneNano, null, 1, () -> 0.0, Duration.ZERO)); + assertEquals( + Duration.ofNanos(1L), + StreamingRetryHelper.computeRetryDelay(oneNano, null, 1, () -> 1.0, Duration.ZERO)); + } + + @Test + public void saturatedDurationMillisAndToSaturatedNanosHandleBoundariesAndOverflow() { + assertEquals(42L, StreamingRetryHelper.saturatedDurationMillis(null, 42L, 100L)); + assertEquals(42L, StreamingRetryHelper.saturatedDurationMillis(Duration.ZERO, 42L, 100L)); + assertEquals( + 42L, StreamingRetryHelper.saturatedDurationMillis(Duration.ofMillis(-5L), 42L, 100L)); + assertEquals(1L, StreamingRetryHelper.saturatedDurationMillis(Duration.ofNanos(1L), 42L, 100L)); + assertEquals( + 50L, StreamingRetryHelper.saturatedDurationMillis(Duration.ofMillis(50L), 42L, 100L)); + assertEquals( + 100L, StreamingRetryHelper.saturatedDurationMillis(Duration.ofMillis(500L), 42L, 100L)); + assertEquals( + 100L, + StreamingRetryHelper.saturatedDurationMillis( + Duration.ofSeconds(Long.MAX_VALUE), 42L, 100L)); + + assertEquals(0L, StreamingRetryHelper.toSaturatedNanos(Duration.ZERO)); + assertEquals(1_000_000L, StreamingRetryHelper.toSaturatedNanos(Duration.ofMillis(1L))); + assertEquals( + Long.MAX_VALUE, StreamingRetryHelper.toSaturatedNanos(Duration.ofSeconds(Long.MAX_VALUE))); + assertEquals( + Long.MIN_VALUE, StreamingRetryHelper.toSaturatedNanos(Duration.ofSeconds(Long.MIN_VALUE))); + assertThat(StreamingRetryHelper.DEFAULT_MAX_RETRY_DELAY).isEqualTo(Duration.ofSeconds(32L)); + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionOptionsTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionOptionsTest.java index a64dce849dd7..81257037a8ed 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionOptionsTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionOptionsTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -37,25 +38,40 @@ import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.NoCredentials; +import com.google.cloud.spanner.Dialect; import com.google.cloud.spanner.ErrorCode; +import com.google.cloud.spanner.ForceCloseSpannerFunction; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; +import com.google.cloud.spanner.connection.ConnectionOptions.StartupPropertyPolicy; +import com.google.cloud.spanner.connection.SpannerPool.CheckAndCloseSpannersMode; import com.google.cloud.spanner.omni.SpannerOmniCredentials; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; import com.google.common.io.Files; +import java.io.BufferedReader; import java.io.File; import java.io.IOException; +import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Objects; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.regex.Matcher; +import org.jspecify.annotations.Nullable; +import org.junit.Assume; import org.junit.Test; import org.junit.function.ThrowingRunnable; import org.junit.runner.RunWith; @@ -685,6 +701,14 @@ public void testLenient() { .setCredentialsUrl(FILE_TEST_PATH) .build()); assertTrue(exception.getMessage(), exception.getMessage().contains("bar")); + + ConnectionOptions validLenientOptions = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database?lenient=true") + .setCredentialsUrl(FILE_TEST_PATH) + .build(); + assertNull(validLenientOptions.getWarnings()); } @Test @@ -2080,7 +2104,10 @@ public void testUniverseDomain() { optionsBuilder -> { executedConfigurator.set(true); SpannerOptions spannerOptions = optionsBuilder.build(); - assertEquals("googleapis.com", spannerOptions.getUniverseDomain()); + assertNull(spannerOptions.getUniverseDomain()); + assertEquals( + "googleapis.com", + spannerOptions.getSpannerStubSettings().getUniverseDomain()); assertEquals("https://spanner.googleapis.com", spannerOptions.getHost()); }) .build(); @@ -2312,4 +2339,1126 @@ public void testCertificateAndTrustOptions() { assertEquals("/path/to/client.key", optionsFromUri.getClientCertificateKey()); assertEquals("/path/to/ca.crt", optionsFromUri.getCaCertificate()); } + + @Test + public void testProgrammaticPropertiesAllowedAndTrusted() throws Throwable { + runWithSystemPropertyEnabled( + ConnectionOptions.ENABLE_CHANNEL_PROVIDER_SYSTEM_PROPERTY, + () -> { + String baseUri = + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database" + + "?autocommit=true;endpoint=url-endpoint.example.com:443"; + + ConnectionOptions options = + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.ENDPOINT, "trusted.example.com:443")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USER_AGENT, "pg-adapter")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USE_PLAIN_TEXT, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 8)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.GRPC_KEEPALIVE_TIME, Duration.ofSeconds(30))) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.GRPC_KEEPALIVE_TIMEOUT, Duration.ofSeconds(10))) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.MIN_SESSIONS, 10)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.MAX_SESSIONS, 20)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.DATABASE_ROLE, "trusted-role")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.ENABLE_END_TO_END_TRACING, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.CHANNEL_PROVIDER, + TestChannelProvider.class.getName())) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.CREDENTIALS_URL, FILE_TEST_PATH)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.AUTOCOMMIT, false)) + .build(); + assertEquals("http://trusted.example.com:443", options.getHost()); + assertEquals(Dialect.POSTGRESQL, options.getDialect()); + assertEquals("pg-adapter", options.getUserAgent()); + assertTrue(options.isUsePlainText()); + assertEquals(Integer.valueOf(8), options.getNumChannels()); + assertEquals(Duration.ofSeconds(30), options.getGrpcKeepAliveTime()); + assertEquals(Duration.ofSeconds(10), options.getGrpcKeepAliveTimeout()); + assertEquals(Integer.valueOf(10), options.getMinSessions()); + assertEquals(Integer.valueOf(20), options.getMaxSessions()); + assertEquals("trusted-role", options.getDatabaseRole()); + assertTrue(options.isEndToEndTracingEnabled()); + assertNotNull(options.getChannelProvider()); + assertEquals(FILE_TEST_PATH, options.getCredentialsUrl()); + assertFalse(options.isAutocommit()); + + // Setting programmatic properties before setUri also overrides URI values. + ConnectionOptions propsBeforeUri = + ConnectionOptions.newBuilder() + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.ENDPOINT, "trusted.example.com:443")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.AUTOCOMMIT, false)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 6)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("https://trusted.example.com:443", propsBeforeUri.getHost()); + assertFalse(propsBeforeUri.isAutocommit()); + assertEquals(Integer.valueOf(6), propsBeforeUri.getNumChannels()); + assertEquals(Dialect.POSTGRESQL, propsBeforeUri.getDialect()); + + assertThrows( + NullPointerException.class, + () -> ConnectionOptions.newBuilder().setConnectionPropertyValue(null)); + + SpannerException nullPrimitiveException = + assertThrows( + SpannerException.class, + () -> ConnectionPropertyValue.of(ConnectionProperties.AUTOCOMMIT, null)); + assertEquals(ErrorCode.INVALID_ARGUMENT, nullPrimitiveException.getErrorCode()); + + // Programmatic lenient=true allows unknown URI properties before setUri and yields null + // warnings when the URI has no unknown properties. + ConnectionOptions lenientWithUnknownUriProp = + ConnectionOptions.newBuilder() + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, true)) + .setUri( + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database?unknownProp=value") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNotNull(lenientWithUnknownUriProp.getWarnings()); + assertTrue(lenientWithUnknownUriProp.getWarnings().contains("unknownProp")); + + ConnectionOptions lenientWithValidUri = + ConnectionOptions.newBuilder() + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, true)) + .setUri( + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNull(lenientWithValidUri.getWarnings()); + }); + } + + @Test + public void testChannelProviderUsesUniverseDomainEnvironmentVariable() throws Throwable { + String baseUri = + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database" + + "?channelProvider=com.google.cloud.spanner.connection.TestChannelProvider"; + runWithSystemPropertyEnabled( + ConnectionOptions.ENABLE_CHANNEL_PROVIDER_SYSTEM_PROPERTY, + () -> { + useUniverseDomainEnvironment("partner.example"); + try { + // Plain URI without universeDomain should inherit the environment universe domain. + ConnectionOptions plainOptions = + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNull(plainOptions.getUniverseDomain()); + assertEquals( + "spanner.partner.example:443", + ((InstantiatingGrpcChannelProvider) plainOptions.getChannelProvider()) + .getEndpoint()); + + ConnectionOptions emptyPropOptions = + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setConnectionPropertyValue(ConnectionProperties.UNIVERSE_DOMAIN, "") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals( + "spanner.partner.example:443", + ((InstantiatingGrpcChannelProvider) emptyPropOptions.getChannelProvider()) + .getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + + useUniverseDomainEnvironment(""); + try { + ConnectionOptions emptyEnvOptions = + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals( + "spanner.googleapis.com:443", + ((InstantiatingGrpcChannelProvider) emptyEnvOptions.getChannelProvider()) + .getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + + useUniverseDomainEnvironment("evil.example/path"); + try { + // Unset universeDomain fails closed eagerly during ConnectionOptions.Builder#build(). + IllegalArgumentException exception = + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .build()); + assertTrue( + exception.getMessage(), exception.getMessage().contains("Invalid universe domain")); + + // Empty universeDomain property also falls back to env and fails closed eagerly. + IllegalArgumentException emptyPropException = + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setConnectionPropertyValue(ConnectionProperties.UNIVERSE_DOMAIN, "") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertTrue( + emptyPropException.getMessage(), + emptyPropException.getMessage().contains("Invalid universe domain")); + + // Malformed GOOGLE_CLOUD_UNIVERSE_DOMAIN still fails closed even with an explicit host + // or emulator configuration. + IllegalArgumentException explicitHostException = + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner://custom.example:443/projects/test-project-123/instances/test-instance/databases/test-database") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertTrue( + explicitHostException.getMessage(), + explicitHostException.getMessage().contains("Invalid universe domain")); + + IllegalArgumentException emulatorException = + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri + ";autoConfigEmulator=true") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertTrue( + emulatorException.getMessage(), + emulatorException.getMessage().contains("Invalid universe domain")); + + // An explicit valid universeDomain property overrides an invalid environment variable. + ConnectionOptions explicitOverrideOptions = + ConnectionOptions.newBuilder() + .setUri(baseUri + ";universeDomain=explicit.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("explicit.example", explicitOverrideOptions.getUniverseDomain()); + assertEquals( + "spanner.explicit.example:443", + ((InstantiatingGrpcChannelProvider) explicitOverrideOptions.getChannelProvider()) + .getEndpoint()); + } finally { + SpannerOptions.useDefaultEnvironment(); + } + }); + } + + @Test + public void testProgrammaticPropertiesEdgeCasesAndUnhappyPaths() { + String baseUri = + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database"; + + // Programmatic lenient=false overrides URI lenient=true regardless of call order. + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, false)) + .setUri(baseUri + "?lenient=true;unknownProp=bar") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri + "?lenient=true;unknownProp=bar") + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, false)) + .setCredentials(NoCredentials.getInstance()) + .build()); + + // setUri validates unknown URI properties eagerly if programmatic LENIENT=true was not set + // beforehand. + assertThrows( + IllegalArgumentException.class, + () -> ConnectionOptions.newBuilder().setUri(baseUri + "?unknownProp=bar")); + + // Calling setConnectionPropertyValue twice for the same property keeps the latest value, and + // reusing a Builder does not mutate previously built ConnectionOptions instances. + ConnectionOptions.Builder reusedBuilder = + ConnectionOptions.newBuilder() + .setUri(baseUri + "?numChannels=4") + .setCredentials(NoCredentials.getInstance()) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 6)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 10)); + ConnectionOptions firstBuilt = reusedBuilder.build(); + reusedBuilder.setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 12)); + ConnectionOptions secondBuilt = reusedBuilder.build(); + assertEquals(Integer.valueOf(10), firstBuilt.getNumChannels()); + assertEquals(Integer.valueOf(12), secondBuilt.getNumChannels()); + + // Guarded properties set via ConnectionPropertyValue still enforce system property guards. + for (ConnectionProperty guardedProperty : + Arrays.asList( + ConnectionProperties.CHANNEL_PROVIDER, + ConnectionProperties.CREDENTIALS_PROVIDER, + ConnectionProperties.ENCODED_CREDENTIALS, + ConnectionProperties.GRPC_INTERCEPTOR_PROVIDER)) { + SpannerException guardedException = + assertThrows( + "Expected guarded property " + guardedProperty.getKey() + " to fail without flag", + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(guardedProperty, "com.example.Test")) + .build()); + assertEquals(ErrorCode.FAILED_PRECONDITION, guardedException.getErrorCode()); + } + + // Conflicting credential properties set via ConnectionPropertyValue are rejected. + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.CREDENTIALS_URL, FILE_TEST_PATH)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.OAUTH_TOKEN, "token")) + .build()); + + // Programmatic TYPE overrides URI TYPE and updates isSpannerOmni()/getInstanceType(). + ConnectionOptions cloudOverridingOmniUri = + ConnectionOptions.newBuilder() + .setUri(baseUri + "?type=omni") + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.TYPE, SpannerOptions.InstanceType.CLOUD)) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse(cloudOverridingOmniUri.isSpannerOmni()); + assertEquals(SpannerOptions.InstanceType.CLOUD, cloudOverridingOmniUri.getInstanceType()); + + // setTracingPrefix(null) and setType(null) fail fast with INVALID_ARGUMENT, while nullable + // credentialsUrl/oauthToken continue to allow null. + SpannerException nullTracingPrefix = + assertThrows( + SpannerException.class, () -> ConnectionOptions.newBuilder().setTracingPrefix(null)); + assertEquals(ErrorCode.INVALID_ARGUMENT, nullTracingPrefix.getErrorCode()); + SpannerException nullType = + assertThrows(SpannerException.class, () -> ConnectionOptions.newBuilder().setType(null)); + assertEquals(ErrorCode.INVALID_ARGUMENT, nullType.getErrorCode()); + assertNull( + ConnectionOptions.newBuilder() + .setCredentialsUrl(null) + .setOAuthToken(null) + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .build() + .getCredentialsUrl()); + + // setUri validates property values eagerly. + SpannerException eagerBadInt = + assertThrows( + SpannerException.class, + () -> ConnectionOptions.newBuilder().setUri(baseUri + "?numChannels=notAnInt")); + assertEquals(ErrorCode.INVALID_ARGUMENT, eagerBadInt.getErrorCode()); + + // Malformed tokens without '=' or empty keys are flagged as invalid tokens (never ignored). + for (String malformedSuffix : new String[] {"?bypass", "?autocommit", "?=value"}) { + assertThrows( + "Expected malformed token " + malformedSuffix + " to fail without lenient", + IllegalArgumentException.class, + () -> ConnectionOptions.newBuilder().setUri(baseUri + malformedSuffix)); + ConnectionOptions lenientMalformed = + ConnectionOptions.newBuilder() + .setUri(baseUri + malformedSuffix + ";lenient=true") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNotNull(lenientMalformed.getWarnings()); + } + } + + @Test + public void testStartupPropertyPolicy() throws Throwable { + String baseUri = + "cloudspanner:/projects/test-project-123/instances/test-instance/databases/test-database"; + String spannerSchemeUri = + "spanner:/projects/test-project-123/instances/test-instance/databases/test-database"; + String omniUri = + "cloudspanner://custom.host:443/instances/test-instance/databases/test-database"; + + // Default policy is ALLOW. + ConnectionOptions.Builder defaultBuilder = ConnectionOptions.newBuilder(); + assertEquals(StartupPropertyPolicy.ALLOW, defaultBuilder.getStartupPropertyPolicy()); + assertThrows(NullPointerException.class, () -> defaultBuilder.setStartupPropertyPolicy(null)); + + // Toggle between REJECT and ALLOW on the same Builder restores URI startup property allowance. + defaultBuilder.setStartupPropertyPolicy(StartupPropertyPolicy.REJECT); + assertEquals(StartupPropertyPolicy.REJECT, defaultBuilder.getStartupPropertyPolicy()); + defaultBuilder.setStartupPropertyPolicy(StartupPropertyPolicy.ALLOW); + assertEquals(StartupPropertyPolicy.ALLOW, defaultBuilder.getStartupPropertyPolicy()); + ConnectionOptions restoredAllowOptions = + defaultBuilder + .setUri(baseUri + "?endpoint=restored.example.com:443;usePlainText=true") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("http://restored.example.com:443", restoredAllowOptions.getHost()); + + // Programmatic startup properties + USER URI properties succeed when policy is REJECT, + // regardless of whether setUri is called before or after setting the policy. + for (boolean setPolicyBeforeUri : new boolean[] {true, false}) { + ConnectionOptions.Builder builder = ConnectionOptions.newBuilder(); + String userOnlyUri = baseUri + "?autocommit=false;readonly=true;maxPartitions=5"; + if (setPolicyBeforeUri) { + builder.setStartupPropertyPolicy(StartupPropertyPolicy.REJECT).setUri(userOnlyUri); + } else { + builder.setUri(userOnlyUri).setStartupPropertyPolicy(StartupPropertyPolicy.REJECT); + } + ConnectionOptions options = + builder + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USER_AGENT, "pg-adapter")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USE_PLAIN_TEXT, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of( + ConnectionProperties.ENDPOINT, "trusted-server.example.com:443")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.CREDENTIALS_URL, FILE_TEST_PATH)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DATABASE_ROLE, "server-role")) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, 6)) + .build(); + + assertEquals("http://trusted-server.example.com:443", options.getHost()); + assertEquals(Dialect.POSTGRESQL, options.getDialect()); + assertEquals("pg-adapter", options.getUserAgent()); + assertTrue(options.isUsePlainText()); + assertEquals("server-role", options.getDatabaseRole()); + assertEquals(Integer.valueOf(6), options.getNumChannels()); + assertEquals(FILE_TEST_PATH, options.getCredentialsUrl()); + assertFalse(options.isAutocommit()); + assertTrue(options.isReadOnly()); + assertEquals(5, options.getMaxPartitions()); + assertNull(options.getWarnings()); + } + + // Any Context.STARTUP property in the URI is rejected under REJECT, regardless of call order, + // casing, invalid startup values, parser smuggling prefixes, URI format, or programmatic + // lenient=true. + for (String startupParam : + new String[] { + "endpoint=evil.example.com:443", + "Endpoint=evil.example.com:443", + "dialect=postgresql", + "numChannels=2", + "numChannels=-1", + "type=omni", + "autoConfigEmulator=true", + "lenient=true", + "lenient=notabool", + "lenient=true;unknownProp=foo", + "autocommit=false;endpoint=evil.example.com:443", + "unknownProp=foo;endpoint=evil.example.com:443", + "bypass;minSessions=100", + "bypass?endpoint=evil.example.com:443", + "=val;minSessions=100", + }) { + for (String uriPrefix : + new String[] {baseUri + "?", baseUri + ";", spannerSchemeUri + "?", omniUri + "?"}) { + String rejectedUri = uriPrefix + startupParam; + SpannerException beforeUriException = + assertThrows( + "Expected REJECT before setUri for " + rejectedUri, + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(rejectedUri) + .setCredentials(NoCredentials.getInstance()) + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, beforeUriException.getErrorCode()); + + SpannerException programmaticLenientException = + assertThrows( + "Expected REJECT even with programmatic lenient=true for " + rejectedUri, + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, true)) + .setUri(rejectedUri) + .setCredentials(NoCredentials.getInstance()) + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, programmaticLenientException.getErrorCode()); + } + } + + // Eager USER property value validation still applies under REJECT. + SpannerException badUserValueInSetUri = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?maxPartitions=notAnInt")); + assertEquals(ErrorCode.INVALID_ARGUMENT, badUserValueInSetUri.getErrorCode()); + + // Valid startup property set in URI before REJECT still fails on build(). + for (String validStartupParam : + new String[] { + "endpoint=evil.example.com:443", + "lenient=true;unknownProp=foo", + "bypass;minSessions=100;lenient=true", + }) { + SpannerException afterUriException = + assertThrows( + "Expected REJECT after setUri for " + validStartupParam, + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setUri(baseUri + "?" + validStartupParam) + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setCredentials(NoCredentials.getInstance()) + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, afterUriException.getErrorCode()); + } + + // Verify all Context.STARTUP properties in VALID_CONNECTION_PROPERTIES are rejected under + // REJECT, and all Context.USER properties are accepted. + Map, String> userPropertySamples = new HashMap<>(); + userPropertySamples.put(ConnectionProperties.AUTOCOMMIT, "false"); + userPropertySamples.put(ConnectionProperties.READONLY, "true"); + userPropertySamples.put(ConnectionProperties.DEFAULT_ISOLATION_LEVEL, "SERIALIZABLE"); + userPropertySamples.put(ConnectionProperties.READ_LOCK_MODE, "PESSIMISTIC"); + userPropertySamples.put(ConnectionProperties.STATEMENT_TIMEOUT, "'10s'"); + userPropertySamples.put(ConnectionProperties.TRANSACTION_TIMEOUT, "'10s'"); + userPropertySamples.put(ConnectionProperties.AUTOCOMMIT_DML_MODE, "PARTITIONED_NON_ATOMIC"); + userPropertySamples.put(ConnectionProperties.RETRY_ABORTS_INTERNALLY, "false"); + userPropertySamples.put(ConnectionProperties.RETURN_COMMIT_STATS, "true"); + userPropertySamples.put(ConnectionProperties.DELAY_TRANSACTION_START_UNTIL_FIRST_WRITE, "true"); + userPropertySamples.put(ConnectionProperties.KEEP_TRANSACTION_ALIVE, "true"); + userPropertySamples.put(ConnectionProperties.READ_ONLY_STALENESS, "STRONG"); + userPropertySamples.put(ConnectionProperties.AUTO_PARTITION_MODE, "true"); + userPropertySamples.put(ConnectionProperties.DATA_BOOST_ENABLED, "true"); + userPropertySamples.put(ConnectionProperties.MAX_PARTITIONS, "5"); + userPropertySamples.put(ConnectionProperties.MAX_PARTITIONED_PARALLELISM, "2"); + userPropertySamples.put( + ConnectionProperties.DIRECTED_READ, + "{\"includeReplicas\":{\"replicaSelections\":[{\"location\":\"us-central1\",\"type\":\"READ_ONLY\"}]}}"); + userPropertySamples.put(ConnectionProperties.OPTIMIZER_VERSION, "1"); + userPropertySamples.put(ConnectionProperties.OPTIMIZER_STATISTICS_PACKAGE, "pkg"); + userPropertySamples.put(ConnectionProperties.RPC_PRIORITY, "LOW"); + userPropertySamples.put(ConnectionProperties.SAVEPOINT_SUPPORT, "ENABLED"); + userPropertySamples.put( + ConnectionProperties.DDL_IN_TRANSACTION_MODE, "AUTO_COMMIT_TRANSACTION"); + userPropertySamples.put(ConnectionProperties.DEFAULT_SEQUENCE_KIND, "bit_reversed_positive"); + userPropertySamples.put(ConnectionProperties.MAX_COMMIT_DELAY, "'10ms'"); + userPropertySamples.put(ConnectionProperties.AUTO_BATCH_DML, "true"); + userPropertySamples.put(ConnectionProperties.AUTO_BATCH_DML_UPDATE_COUNT, "2"); + userPropertySamples.put(ConnectionProperties.AUTO_BATCH_DML_UPDATE_COUNT_VERIFICATION, "false"); + userPropertySamples.put(ConnectionProperties.BATCH_DML_UPDATE_COUNT, "2"); + userPropertySamples.put(ConnectionProperties.UNKNOWN_LENGTH, "100"); + + for (ConnectionProperty property : ConnectionProperties.VALID_CONNECTION_PROPERTIES) { + if (property.getContext() == ConnectionProperty.Context.STARTUP) { + SpannerException startupRejected = + assertThrows( + "Expected startup property " + property.getKey() + " to be rejected", + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?" + property.getKey() + "=value") + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, startupRejected.getErrorCode()); + } else { + String sampleValue = userPropertySamples.get(property); + assertNotNull("Missing sample value for USER property " + property.getKey(), sampleValue); + ConnectionOptions userAllowed = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?" + property.getKey() + "=" + sampleValue) + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNull(userAllowed.getWarnings()); + } + } + + // Multiple disallowed startup properties are all reported in the error message. + SpannerException multiException = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?endpoint=evil.example.com:443;dialect=postgresql") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, multiException.getErrorCode()); + assertTrue(multiException.getMessage().contains("endpoint")); + assertTrue(multiException.getMessage().contains("dialect")); + + // Unknown URI properties without startup properties fail unless programmatic lenient=true. + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?unknownProp=foo") + .setCredentials(NoCredentials.getInstance()) + .build()); + ConnectionOptions lenientWithUnknown = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, true)) + .setUri(baseUri + "?unknownProp=foo;autocommit=false") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertFalse(lenientWithUnknown.isAutocommit()); + assertEquals( + "Invalid properties found in connection URI: unknownProp", + lenientWithUnknown.getWarnings()); + + // URL attempting to set startupPropertyPolicy or allowStartupPropertiesInUrl cannot bypass + // REJECT. + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?allowStartupPropertiesInUrl=true") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?startupPropertyPolicy=ALLOW") + .setCredentials(NoCredentials.getInstance()) + .build()); + SpannerException urlBypassAttemptWithStartup = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?startupPropertyPolicy=ALLOW;endpoint=evil.example.com:443") + .setCredentials(NoCredentials.getInstance()) + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, urlBypassAttemptWithStartup.getErrorCode()); + + // Even with programmatic lenient=true, startupPropertyPolicy/allowStartupPropertiesInUrl in URI + // are treated as unknown properties and never unlock startup properties. + ConnectionOptions urlBypassWarning = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.LENIENT, true)) + .setUri(baseUri + "?allowStartupPropertiesInUrl=true;startupPropertyPolicy=ALLOW") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertNotNull(urlBypassWarning.getWarnings()); + assertTrue(urlBypassWarning.getWarnings().contains("allowStartupPropertiesInUrl")); + assertTrue(urlBypassWarning.getWarnings().contains("startupPropertyPolicy")); + + // URI property tokenization edge cases: '=' in value, empty value, trailing '?' / ';', ';;', + // duplicate startup keys, and '?' inside HOSTGROUP. + assertEquals( + "abc==", + ConnectionOptions.parseUriProperty( + baseUri + "?encodedCredentials=abc==", "encodedCredentials")); + ConnectionOptions eqAndEmptyDelimiterOptions = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?optimizerVersion=a=b;;maxPartitions=3;") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals( + "a=b", + eqAndEmptyDelimiterOptions + .getInitialConnectionPropertyValues() + .get(ConnectionProperties.OPTIMIZER_VERSION.getKey()) + .getValue()); + assertEquals(3, eqAndEmptyDelimiterOptions.getMaxPartitions()); + + ConnectionOptions emptyValueAndTrailingDelimiter = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?optimizerVersion=") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals( + "", + emptyValueAndTrailingDelimiter + .getInitialConnectionPropertyValues() + .get(ConnectionProperties.OPTIMIZER_VERSION.getKey()) + .getValue()); + assertNull( + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?") + .setCredentials(NoCredentials.getInstance()) + .build() + .getWarnings()); + assertNull( + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + ";") + .setCredentials(NoCredentials.getInstance()) + .build() + .getWarnings()); + + SpannerException duplicateStartupRejected = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?endpoint=a;endpoint=b") + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, duplicateStartupRejected.getErrorCode()); + + // Duplicate Context.USER property in URI uses first-occurrence-wins semantics. + ConnectionOptions duplicateUserFirstWins = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?autocommit=true;autocommit=false;maxPartitions=5;maxPartitions=bad") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertTrue(duplicateUserFirstWins.isAutocommit()); + assertEquals(5, duplicateUserFirstWins.getMaxPartitions()); + + // REJECT checks startup properties before validateValues runs on USER property values. + SpannerException invalidUserAndStartup = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri + "?maxPartitions=bad;minSessions=100") + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, invalidUserAndStartup.getErrorCode()); + assertTrue( + invalidUserAndStartup.getMessage(), + invalidUserAndStartup.getMessage().contains("minSessions")); + + // Setting the same STARTUP property programmatically does not exempt it in the URI. + SpannerException programmaticAndUriStartup = + assertThrows( + SpannerException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.MIN_SESSIONS, 50)) + .setUri(baseUri + "?minSessions=100") + .build()); + assertEquals(ErrorCode.INVALID_ARGUMENT, programmaticAndUriStartup.getErrorCode()); + + // Invalid SessionPoolOptions combination via ConnectionPropertyValue fails at build(). + assertThrows( + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(baseUri) + .setCredentials(NoCredentials.getInstance()) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.MIN_SESSIONS, 100)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.MAX_SESSIONS, 10)) + .build()); + + // Tightened HOSTGROUP rejects query/path/userinfo delimiters before /projects/, and + // SPANNER_URI_FORMAT rejects '|' as a property delimiter. + for (String invalidHostOrDelimiterUri : + Arrays.asList( + "cloudspanner://host?minSessions=100/projects/test-project-123/instances/test-instance/databases/test-database", + "cloudspanner://user@host/projects/test-project-123/instances/test-instance/databases/test-database", + "cloudspanner://host;minSessions=100/projects/test-project-123/instances/test-instance/databases/test-database", + baseUri + "|minSessions=100", + baseUri + "|autocommit=false")) { + assertThrows( + "Expected invalid URI " + invalidHostOrDelimiterUri + " to be rejected", + IllegalArgumentException.class, + () -> + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(invalidHostOrDelimiterUri)); + } + + // Query parameter containing /projects/... cannot hijack HOSTGROUP or projectId. + ConnectionOptions projectInQuerySafe = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri( + "cloudspanner://trusted.host:443/projects/trusted-proj/instances/test-instance/databases/test-database?optimizerVersion=1/projects/evil-proj/instances/evil-inst/databases/evil-db") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("https://trusted.host:443", projectInQuerySafe.getHost()); + assertEquals("trusted-proj", projectInQuerySafe.getProjectId()); + + // IPv6 bracketed literal remains supported in HOSTGROUP. + ConnectionOptions ipv6HostOptions = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri( + "cloudspanner://[::1]:9010/projects/test-project-123/instances/test-instance/databases/test-database") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("https://[::1]:9010", ipv6HostOptions.getHost()); + + // Scoped contract: StartupPropertyPolicy.REJECT governs URI properties while still allowing + // HOSTGROUP and Omni URI structure when only USER properties are in the query string. + ConnectionOptions omniWithUserParam = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(omniUri + "?autocommit=false") + .setCredentials(NoCredentials.getInstance()) + .build(); + assertEquals("https://custom.host:443", omniWithUserParam.getHost()); + assertFalse(omniWithUserParam.isAutocommit()); + } + + @Test + public void testSpannerPoolUsesUniverseDomainEnvironmentVariable() { + ConnectionImpl connection = mock(ConnectionImpl.class); + ConnectionImpl secondConnection = mock(ConnectionImpl.class); + useUniverseDomainEnvironment("partner.example"); + try { + AtomicBoolean executedConfigurator = new AtomicBoolean(false); + ConnectionOptions plainOptions = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/default/instances/default/databases/singers-db?usePlainText=true") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + executedConfigurator.set(true); + SpannerOptions spannerOptions = optionsBuilder.build(); + assertNull(spannerOptions.getUniverseDomain()); + assertEquals("https://spanner.partner.example", spannerOptions.getHost()); + assertEquals("spanner.partner.example:443", spannerOptions.getEndpoint()); + assertEquals( + "partner.example", + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + assertEquals( + "partner.example", + spannerOptions.getInstanceAdminStubSettings().getUniverseDomain()); + assertEquals( + "partner.example", + spannerOptions.getDatabaseAdminStubSettings().getUniverseDomain()); + }) + .build(); + Spanner plainSpanner = SpannerPool.INSTANCE.getSpanner(plainOptions, connection); + try { + assertTrue(executedConfigurator.get()); + + // An empty universeDomain on the same database shares the exact same pooled Spanner client. + ConnectionOptions samePoolEmptyOptions = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/default/instances/default/databases/singers-db;universeDomain=;usePlainText=true") + .setCredentials(NoCredentials.getInstance()) + .build(); + Spanner samePoolEmptySpanner = + SpannerPool.INSTANCE.getSpanner(samePoolEmptyOptions, secondConnection); + try { + assertSame(plainSpanner, samePoolEmptySpanner); + } finally { + SpannerPool.INSTANCE.removeConnection(samePoolEmptyOptions, secondConnection); + } + } finally { + SpannerPool.INSTANCE.removeConnection(plainOptions, connection); + } + + // Empty universeDomain in the URI leaves SpannerOptions unset and falls back to env. + executedConfigurator.set(false); + ConnectionOptions emptyOptions = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/default-empty/instances/default/databases/singers-db;universeDomain=;usePlainText=true") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + executedConfigurator.set(true); + SpannerOptions spannerOptions = optionsBuilder.build(); + assertNull(spannerOptions.getUniverseDomain()); + assertEquals("https://spanner.partner.example", spannerOptions.getHost()); + assertEquals("spanner.partner.example:443", spannerOptions.getEndpoint()); + assertEquals( + "partner.example", + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + }) + .build(); + SpannerPool.INSTANCE.getSpanner(emptyOptions, connection); + try { + assertTrue(executedConfigurator.get()); + } finally { + SpannerPool.INSTANCE.removeConnection(emptyOptions, connection); + } + + // Explicit universeDomain in the URI takes precedence over the environment value. + executedConfigurator.set(false); + ConnectionOptions explicitOptions = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/default/instances/default/databases/singers-db;universeDomain=explicit.example;usePlainText=true") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + executedConfigurator.set(true); + SpannerOptions spannerOptions = optionsBuilder.build(); + assertEquals("explicit.example", spannerOptions.getUniverseDomain()); + assertEquals("https://spanner.explicit.example", spannerOptions.getHost()); + assertEquals( + "explicit.example", + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + }) + .build(); + SpannerPool.INSTANCE.getSpanner(explicitOptions, connection); + try { + assertTrue(executedConfigurator.get()); + } finally { + SpannerPool.INSTANCE.removeConnection(explicitOptions, connection); + } + + // Invalid GOOGLE_CLOUD_UNIVERSE_DOMAIN fails closed when creating a Spanner instance. + useUniverseDomainEnvironment("evil.example/path"); + IllegalArgumentException invalidEnvException = + assertThrows( + IllegalArgumentException.class, + () -> + SpannerPool.INSTANCE.createSpanner( + SpannerPool.SpannerPoolKey.of(plainOptions), plainOptions)); + assertTrue( + invalidEnvException.getMessage(), + invalidEnvException.getMessage().contains("Invalid universe domain")); + } finally { + SpannerOptions.useDefaultEnvironment(); + connection.close(); + secondConnection.close(); + SpannerPool.INSTANCE.checkAndCloseSpanners( + CheckAndCloseSpannersMode.ERROR, + new ForceCloseSpannerFunction(5L, TimeUnit.MILLISECONDS)); + } + } + + private static void useUniverseDomainEnvironment(@Nullable String universeDomain) { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public @Nullable String getUniverseDomain() { + return universeDomain; + } + }); + } + + /** + * Forked-JVM entry point that exercises real {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} process + * environment resolution without mutating the parent test JVM's environment. + */ + public static final class UniverseDomainEnvProbe { + public static void main(String[] args) { + String baseUri = "cloudspanner:/projects/test-project/instances/test-instance/databases/db"; + + // 1. Omitted universeDomain inherits GOOGLE_CLOUD_UNIVERSE_DOMAIN end-to-end. + AtomicReference omittedSpannerUniverseDomain = new AtomicReference<>("UNSET"); + AtomicReference omittedStubUniverseDomain = new AtomicReference<>("UNSET"); + ConnectionOptions omittedOptions = + ConnectionOptions.newBuilder() + .setUri( + baseUri + + "?usePlainText=true;channelProvider=com.google.cloud.spanner.connection.TestChannelProvider") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + SpannerOptions spannerOptions = optionsBuilder.build(); + omittedSpannerUniverseDomain.set( + String.valueOf(spannerOptions.getUniverseDomain())); + omittedStubUniverseDomain.set( + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + }) + .build(); + String omittedEndpoint = + ((InstantiatingGrpcChannelProvider) omittedOptions.getChannelProvider()).getEndpoint(); + Spanner omittedSpanner = + SpannerPool.INSTANCE.createSpanner( + SpannerPool.SpannerPoolKey.of(omittedOptions), omittedOptions); + omittedSpanner.close(); + + // 2. Empty universeDomain normalizes to null and inherits GOOGLE_CLOUD_UNIVERSE_DOMAIN. + AtomicReference emptySpannerUniverseDomain = new AtomicReference<>("UNSET"); + AtomicReference emptyStubUniverseDomain = new AtomicReference<>("UNSET"); + ConnectionOptions emptyOptions = + ConnectionOptions.newBuilder() + .setUri( + baseUri + + "?universeDomain=;usePlainText=true;channelProvider=com.google.cloud.spanner.connection.TestChannelProvider") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + SpannerOptions spannerOptions = optionsBuilder.build(); + emptySpannerUniverseDomain.set( + String.valueOf(spannerOptions.getUniverseDomain())); + emptyStubUniverseDomain.set( + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + }) + .build(); + String emptyEndpoint = + ((InstantiatingGrpcChannelProvider) emptyOptions.getChannelProvider()).getEndpoint(); + Spanner emptySpanner = + SpannerPool.INSTANCE.createSpanner( + SpannerPool.SpannerPoolKey.of(emptyOptions), emptyOptions); + emptySpanner.close(); + + // 3. Explicit universeDomain overrides GOOGLE_CLOUD_UNIVERSE_DOMAIN end-to-end. + AtomicReference explicitSpannerUniverseDomain = new AtomicReference<>("UNSET"); + AtomicReference explicitStubUniverseDomain = new AtomicReference<>("UNSET"); + ConnectionOptions explicitOptions = + ConnectionOptions.newBuilder() + .setUri( + baseUri + + "?universeDomain=custom.example;usePlainText=true;channelProvider=com.google.cloud.spanner.connection.TestChannelProvider") + .setCredentials(NoCredentials.getInstance()) + .setConfigurator( + optionsBuilder -> { + SpannerOptions spannerOptions = optionsBuilder.build(); + explicitSpannerUniverseDomain.set( + String.valueOf(spannerOptions.getUniverseDomain())); + explicitStubUniverseDomain.set( + spannerOptions.getSpannerStubSettings().getUniverseDomain()); + }) + .build(); + String explicitEndpoint = + ((InstantiatingGrpcChannelProvider) explicitOptions.getChannelProvider()).getEndpoint(); + Spanner explicitSpanner = + SpannerPool.INSTANCE.createSpanner( + SpannerPool.SpannerPoolKey.of(explicitOptions), explicitOptions); + explicitSpanner.close(); + + System.out.println("omittedChannelProviderEndpoint=" + omittedEndpoint); + System.out.println("omittedSpannerUniverseDomain=" + omittedSpannerUniverseDomain.get()); + System.out.println("omittedStubUniverseDomain=" + omittedStubUniverseDomain.get()); + System.out.println("emptyChannelProviderEndpoint=" + emptyEndpoint); + System.out.println("emptySpannerUniverseDomain=" + emptySpannerUniverseDomain.get()); + System.out.println("emptyStubUniverseDomain=" + emptyStubUniverseDomain.get()); + System.out.println("explicitChannelProviderEndpoint=" + explicitEndpoint); + System.out.println("explicitSpannerUniverseDomain=" + explicitSpannerUniverseDomain.get()); + System.out.println("explicitStubUniverseDomain=" + explicitStubUniverseDomain.get()); + } + } + + @Test + public void testUniverseDomain_RealEnvVarEndToEndSubprocess() throws Exception { + boolean isWindows = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win"); + File javaExe = + new File(new File(System.getProperty("java.home"), "bin"), isWindows ? "java.exe" : "java"); + Assume.assumeTrue("Java executable not found for subprocess test", javaExe.isFile()); + + ProcessBuilder processBuilder = + new ProcessBuilder( + javaExe.getAbsolutePath(), + "-cp", + System.getProperty("java.class.path"), + "-D" + ConnectionOptions.ENABLE_CHANNEL_PROVIDER_SYSTEM_PROPERTY + "=true", + UniverseDomainEnvProbe.class.getName()); + processBuilder.environment().put("GOOGLE_CLOUD_UNIVERSE_DOMAIN", "universe.example"); + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + List outputLines = Collections.synchronizedList(new ArrayList<>()); + Thread drainThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader( + new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + outputLines.add(line); + } + } catch (IOException ignore) { + // Stream closed on process termination. + } + }, + "universe-domain-probe-drain"); + drainThread.start(); + + boolean exited; + try { + exited = process.waitFor(30, TimeUnit.SECONDS); + } finally { + if (process.isAlive()) { + process.destroyForcibly(); + } + } + drainThread.join(TimeUnit.SECONDS.toMillis(5)); + assertFalse("Output drain thread did not terminate", drainThread.isAlive()); + assertTrue("Subprocess timed out: " + outputLines, exited); + assertEquals("Subprocess exited with error: " + outputLines, 0, process.exitValue()); + + Map parsed = new HashMap<>(); + synchronized (outputLines) { + for (String line : outputLines) { + int idx = line.indexOf('='); + if (idx > 0) { + parsed.put(line.substring(0, idx), line.substring(idx + 1)); + } + } + } + assertEquals("spanner.universe.example:443", parsed.get("omittedChannelProviderEndpoint")); + assertEquals("null", parsed.get("omittedSpannerUniverseDomain")); + assertEquals("universe.example", parsed.get("omittedStubUniverseDomain")); + assertEquals("spanner.universe.example:443", parsed.get("emptyChannelProviderEndpoint")); + assertEquals("null", parsed.get("emptySpannerUniverseDomain")); + assertEquals("universe.example", parsed.get("emptyStubUniverseDomain")); + assertEquals("spanner.custom.example:443", parsed.get("explicitChannelProviderEndpoint")); + assertEquals("custom.example", parsed.get("explicitSpannerUniverseDomain")); + assertEquals("custom.example", parsed.get("explicitStubUniverseDomain")); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertyTest.java index f86809ce13f6..9da769aca841 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertyTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertyTest.java @@ -19,14 +19,23 @@ import static com.google.cloud.spanner.connection.ConnectionProperty.create; import static com.google.cloud.spanner.connection.ConnectionProperty.createKey; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import com.google.cloud.spanner.Dialect; +import com.google.cloud.spanner.ErrorCode; import com.google.cloud.spanner.SpannerException; +import com.google.cloud.spanner.connection.ClientSideStatementValueConverters.DialectConverter; import com.google.cloud.spanner.connection.ClientSideStatementValueConverters.NonNegativeIntegerConverter; import com.google.cloud.spanner.connection.ClientSideStatementValueConverters.StringValueConverter; import com.google.cloud.spanner.connection.ConnectionProperty.Context; +import com.google.spanner.v1.TransactionOptions.IsolationLevel; +import com.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode; +import java.time.Duration; import java.util.Objects; import org.junit.Test; import org.junit.runner.RunWith; @@ -56,6 +65,7 @@ public void testCreate() { "my_property", "Description of my_property", "default_value", + /* nullAllowed= */ false, StringValueConverter.INSTANCE, Context.USER); assertEquals("my_property", property.getName()); @@ -64,12 +74,14 @@ public void testCreate() { assertEquals("my_value", Objects.requireNonNull(property.convert("my_value")).getValue()); assertEquals(property.getContext(), Context.USER); assertEquals("my_property", property.getKey()); + assertFalse(property.isNullAllowed()); ConnectionProperty startupProperty = create( "STARTUP_PROPERTY", "Description of STARTUP_PROPERTY", 1, + /* nullAllowed= */ true, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); // The name is folded to lower-case. @@ -80,6 +92,18 @@ public void testCreate() { Integer.valueOf(2), Objects.requireNonNull(startupProperty.convert("2")).getValue()); assertEquals(startupProperty.getContext(), Context.STARTUP); assertEquals("startup_property", startupProperty.getKey()); + assertTrue(startupProperty.isNullAllowed()); + + assertThrows( + SpannerException.class, + () -> + create( + "invalid_property", + "Description", + null, + /* nullAllowed= */ false, + StringValueConverter.INSTANCE, + Context.USER)); } @Test @@ -91,6 +115,7 @@ public void testEquals() { "Description of property1", "default_value_1", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property2 = @@ -100,6 +125,7 @@ public void testEquals() { "Description of property2", "default_value_2", null, + false, StringValueConverter.INSTANCE, Context.USER); ConnectionProperty property3 = @@ -109,6 +135,7 @@ public void testEquals() { "Description of property3", "default_value_3", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property4 = @@ -118,6 +145,7 @@ public void testEquals() { "Description of property4", "default_value_4", null, + false, StringValueConverter.INSTANCE, Context.USER); ConnectionProperty property5 = @@ -127,6 +155,7 @@ public void testEquals() { "Description of property5", "default_value_5", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property6 = @@ -136,6 +165,7 @@ public void testEquals() { "Description of property6", "default_value_6", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property7 = @@ -145,6 +175,7 @@ public void testEquals() { "Description of property7", "default_value_7", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property8 = @@ -154,6 +185,7 @@ public void testEquals() { "Description of property8", "default_value_8", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); ConnectionProperty property9 = @@ -163,6 +195,7 @@ public void testEquals() { "Description of property9", "default_value_9", null, + false, StringValueConverter.INSTANCE, Context.STARTUP); @@ -268,6 +301,7 @@ public void testConvert() { "my_property", "Description of my_property", 1, + /* nullAllowed= */ false, NonNegativeIntegerConverter.INSTANCE, Context.STARTUP); assertEquals(Integer.valueOf(100), Objects.requireNonNull(property.convert("100")).getValue()); @@ -282,6 +316,7 @@ public void testCreateInitialValue() { "my_property", "Description of my_property", "default_value", + /* nullAllowed= */ false, StringValueConverter.INSTANCE, Context.USER); @@ -298,4 +333,152 @@ public void testCreateInitialValue() { assertEquals("other_value", initialValueWithStartupValue.getResetValue()); assertSame(initialValueWithStartupValue.getProperty(), property); } + + @Test + public void testCreateConnectionPropertyValue() { + ConnectionPropertyValue stringValue = + ConnectionPropertyValue.of(ConnectionProperties.ENDPOINT, "localhost:9010"); + assertSame(ConnectionProperties.ENDPOINT, stringValue.getProperty()); + assertEquals("localhost:9010", stringValue.getValue()); + assertEquals("localhost:9010", stringValue.getResetValue()); + + ConnectionPropertyValue boolValue = + ConnectionPropertyValue.of(ConnectionProperties.AUTOCOMMIT, false); + assertSame(ConnectionProperties.AUTOCOMMIT, boolValue.getProperty()); + assertEquals(Boolean.FALSE, boolValue.getValue()); + + ConnectionPropertyValue dialectValue = + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL); + assertSame(ConnectionProperties.DIALECT, dialectValue.getProperty()); + assertEquals(Dialect.POSTGRESQL, dialectValue.getValue()); + + // Nullable / optional properties accept null, including those with bounded validValues. + for (ConnectionProperty nullableProperty : + new ConnectionProperty[] { + ConnectionProperties.CONNECTION_STATE_TYPE, + ConnectionProperties.ENABLE_DIRECT_ACCESS, + ConnectionProperties.ENABLE_EXTENDED_TRACING, + ConnectionProperties.ENABLE_API_TRACING, + ConnectionProperties.ENABLE_DYNAMIC_CHANNEL_POOL, + ConnectionProperties.ENABLE_GRPC_GCP, + ConnectionProperties.MIN_SESSIONS, + ConnectionProperties.ENDPOINT, + ConnectionProperties.STATEMENT_TIMEOUT, + ConnectionProperties.AUTOCOMMIT_DML_MODE, + ConnectionProperties.RPC_PRIORITY, + ConnectionProperties.UNIVERSE_DOMAIN, + }) { + assertTrue(nullableProperty.isNullAllowed()); + assertNull(ConnectionPropertyValue.of(nullableProperty, null).getValue()); + } + assertEquals( + Boolean.TRUE, + ConnectionPropertyValue.of(ConnectionProperties.ENABLE_API_TRACING, true).getValue()); + + assertThrows( + NullPointerException.class, () -> ConnectionPropertyValue.of(null, "localhost:9010")); + + for (ConnectionProperty nonNullProperty : + new ConnectionProperty[] { + ConnectionProperties.AUTOCOMMIT, + ConnectionProperties.MAX_PARTITIONS, + ConnectionProperties.BATCH_DML_UPDATE_COUNT, + ConnectionProperties.DIALECT, + ConnectionProperties.TYPE, + ConnectionProperties.DEFAULT_ISOLATION_LEVEL, + ConnectionProperties.READ_LOCK_MODE, + ConnectionProperties.SAVEPOINT_SUPPORT, + ConnectionProperties.DDL_IN_TRANSACTION_MODE, + ConnectionProperties.TRACING_PREFIX, + ConnectionProperties.OPTIMIZER_VERSION, + ConnectionProperties.READ_ONLY_STALENESS, + }) { + assertFalse(nonNullProperty.isNullAllowed()); + SpannerException exception = + assertThrows( + "Expected null rejection for " + nonNullProperty.getKey(), + SpannerException.class, + () -> ConnectionPropertyValue.of(nonNullProperty, null)); + assertEquals(ErrorCode.INVALID_ARGUMENT, exception.getErrorCode()); + } + + SpannerException unrecognizedLockMode = + assertThrows( + SpannerException.class, + () -> + ConnectionPropertyValue.of( + ConnectionProperties.READ_LOCK_MODE, ReadLockMode.UNRECOGNIZED)); + assertEquals(ErrorCode.INVALID_ARGUMENT, unrecognizedLockMode.getErrorCode()); + + SpannerException unrecognizedIsolationLevel = + assertThrows( + SpannerException.class, + () -> + ConnectionPropertyValue.of( + ConnectionProperties.DEFAULT_ISOLATION_LEVEL, IsolationLevel.UNRECOGNIZED)); + assertEquals(ErrorCode.INVALID_ARGUMENT, unrecognizedIsolationLevel.getErrorCode()); + + // Negative integers, longs, and durations are rejected consistently with string conversion. + SpannerException negativeChannels = + assertThrows( + SpannerException.class, + () -> ConnectionPropertyValue.of(ConnectionProperties.NUM_CHANNELS, -1)); + assertEquals(ErrorCode.INVALID_ARGUMENT, negativeChannels.getErrorCode()); + + SpannerException negativeMaxPartitions = + assertThrows( + SpannerException.class, + () -> ConnectionPropertyValue.of(ConnectionProperties.MAX_PARTITIONS, -1)); + assertEquals(ErrorCode.INVALID_ARGUMENT, negativeMaxPartitions.getErrorCode()); + + SpannerException negativeUpdateCount = + assertThrows( + SpannerException.class, + () -> ConnectionPropertyValue.of(ConnectionProperties.BATCH_DML_UPDATE_COUNT, -1L)); + assertEquals(ErrorCode.INVALID_ARGUMENT, negativeUpdateCount.getErrorCode()); + + SpannerException negativeTimeout = + assertThrows( + SpannerException.class, + () -> + ConnectionPropertyValue.of( + ConnectionProperties.STATEMENT_TIMEOUT, Duration.ofSeconds(-1))); + assertEquals(ErrorCode.INVALID_ARGUMENT, negativeTimeout.getErrorCode()); + + assertEquals( + Integer.valueOf(0), + ConnectionPropertyValue.of(ConnectionProperties.MAX_PARTITIONS, 0).getValue()); + assertEquals( + Long.valueOf(0L), + ConnectionPropertyValue.of(ConnectionProperties.BATCH_DML_UPDATE_COUNT, 0L).getValue()); + assertEquals( + Long.valueOf(1L), + ConnectionPropertyValue.of(ConnectionProperties.BATCH_DML_UPDATE_COUNT, 1L).getValue()); + assertEquals( + Duration.ZERO, + ConnectionPropertyValue.of(ConnectionProperties.STATEMENT_TIMEOUT, Duration.ZERO) + .getValue()); + assertEquals( + Duration.ofSeconds(5), + ConnectionPropertyValue.of(ConnectionProperties.STATEMENT_TIMEOUT, Duration.ofSeconds(5)) + .getValue()); + + ConnectionProperty restrictedDialect = + create( + "restricted_dialect", + "Restricted dialect test property", + Dialect.GOOGLE_STANDARD_SQL, + new Dialect[] {Dialect.GOOGLE_STANDARD_SQL}, + /* nullAllowed= */ false, + DialectConverter.INSTANCE, + Context.USER); + assertEquals( + Dialect.GOOGLE_STANDARD_SQL, + ConnectionPropertyValue.of(restrictedDialect, Dialect.GOOGLE_STANDARD_SQL).getValue()); + SpannerException disallowedDialect = + assertThrows( + SpannerException.class, + () -> ConnectionPropertyValue.of(restrictedDialect, Dialect.POSTGRESQL)); + assertEquals(ErrorCode.INVALID_ARGUMENT, disallowedDialect.getErrorCode()); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/SpannerPoolTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/SpannerPoolTest.java index 456992f2acd4..a34fef8fb3c2 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/SpannerPoolTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/SpannerPoolTest.java @@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -31,6 +32,8 @@ import static org.mockito.Mockito.withSettings; import com.google.auth.Credentials; +import com.google.auth.oauth2.AccessToken; +import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.NoCredentials; import com.google.cloud.spanner.BatchClient; import com.google.cloud.spanner.DatabaseClient; @@ -41,6 +44,7 @@ import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.connection.ConnectionImpl.LeakedConnectionException; +import com.google.cloud.spanner.connection.ConnectionOptions.StartupPropertyPolicy; import com.google.cloud.spanner.connection.SpannerPool.CheckAndCloseSpannersMode; import com.google.cloud.spanner.connection.SpannerPool.CredentialsKey; import com.google.cloud.spanner.connection.SpannerPool.SpannerPoolKey; @@ -1276,4 +1280,153 @@ public void testCredentialsKeyWithNullCredentialsFromProvider() throws IOExcepti assertEquals(defaultKey, keyWithNullProvider); assertEquals(defaultKey.hashCode(), keyWithNullProvider.hashCode()); } + + @Test + public void testSpannerPoolKeyReuseWithStartupPropertyPolicyReject() { + ConnectionOptions optionsA = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(URI + "?autocommit=true;readonly=false;maxPartitions=10;optimizerVersion=1") + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USE_PLAIN_TEXT, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.ENDPOINT, "localhost:9010")) + .setCredentials(NoCredentials.getInstance()) + .build(); + ConnectionOptions optionsB = + ConnectionOptions.newBuilder() + .setStartupPropertyPolicy(StartupPropertyPolicy.REJECT) + .setUri(URI + "?autocommit=false;readonly=true;maxPartitions=20;optimizerVersion=2") + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.DIALECT, Dialect.POSTGRESQL)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.USE_PLAIN_TEXT, true)) + .setConnectionPropertyValue( + ConnectionPropertyValue.of(ConnectionProperties.ENDPOINT, "localhost:9010")) + .setCredentials(NoCredentials.getInstance()) + .build(); + + SpannerPoolKey keyA = SpannerPoolKey.of(optionsA); + SpannerPoolKey keyB = SpannerPoolKey.of(optionsB); + assertEquals(keyA, keyB); + assertEquals(keyA.hashCode(), keyB.hashCode()); + + SpannerPool pool = createSubjectAndMocks(); + Spanner spannerA = pool.getSpanner(optionsA, connection1); + Spanner spannerB = pool.getSpanner(optionsB, connection2); + assertSame(spannerA, spannerB); + + pool.removeConnection(optionsA, connection1); + pool.removeConnection(optionsB, connection2); + pool.checkAndCloseSpanners(CheckAndCloseSpannersMode.ERROR); + } + + @Test + public void testSpannerPoolKeyUniverseDomain() { + ConnectionOptions omitted = + ConnectionOptions.newBuilder() + .setUri(URI) + .setCredentials(NoCredentials.getInstance()) + .build(); + ConnectionOptions empty = + ConnectionOptions.newBuilder() + .setUri(URI + "?universeDomain=") + .setCredentials(NoCredentials.getInstance()) + .build(); + ConnectionOptions explicitGdu = + ConnectionOptions.newBuilder() + .setUri(URI + "?universeDomain=googleapis.com") + .setCredentials(NoCredentials.getInstance()) + .build(); + ConnectionOptions explicitCustom = + ConnectionOptions.newBuilder() + .setUri(URI + "?universeDomain=custom.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + + SpannerPoolKey omittedKey = SpannerPoolKey.of(omitted); + SpannerPoolKey emptyKey = SpannerPoolKey.of(empty); + SpannerPoolKey explicitGduKey = SpannerPoolKey.of(explicitGdu); + SpannerPoolKey explicitCustomKey = SpannerPoolKey.of(explicitCustom); + + // Omitted and explicit empty universeDomain both normalize to null and share one pool key. + assertEquals(omittedKey, emptyKey); + assertEquals(omittedKey.hashCode(), emptyKey.hashCode()); + + // Explicit universeDomain values must remain distinct from unset/empty and from each other. + assertNotEquals(omittedKey, explicitGduKey); + assertNotEquals(omittedKey, explicitCustomKey); + assertNotEquals(explicitGduKey, explicitCustomKey); + } + + @Test + public void testEndpointOnlyJdbcUrlDisablesBuiltInMetrics() { + SpannerOptions.useEnvironment(new SpannerOptions.SpannerEnvironment() {}); + try { + ConnectionOptions endpointOnly = + ConnectionOptions.newBuilder() + .setUri("cloudspanner://spanner.tpc.example/projects/p/instances/i/databases/d") + .setCredentials(NoCredentials.getInstance()) + .build(); + try (Spanner spanner = + SpannerPool.INSTANCE.createSpanner(SpannerPoolKey.of(endpointOnly), endpointOnly)) { + assertFalse(spanner.getOptions().isEnableBuiltInMetrics()); + } + + ConnectionOptions withUniverseDomain = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner://spanner.tpc.example/projects/p/instances/i/databases/d" + + ";universeDomain=tpc.example") + .setCredentials(NoCredentials.getInstance()) + .build(); + try (Spanner spanner = + SpannerPool.INSTANCE.createSpanner( + SpannerPoolKey.of(withUniverseDomain), withUniverseDomain)) { + assertTrue(spanner.getOptions().isEnableBuiltInMetrics()); + } + + ConnectionOptions defaultHost = + ConnectionOptions.newBuilder() + .setUri("cloudspanner:/projects/p/instances/i/databases/d") + .setCredentials(NoCredentials.getInstance()) + .build(); + try (Spanner spanner = + SpannerPool.INSTANCE.createSpanner(SpannerPoolKey.of(defaultHost), defaultHost)) { + assertTrue(spanner.getOptions().isEnableBuiltInMetrics()); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } + + @Test + public void testEndpointPropertyWithCredentialsDisablesBuiltInMetrics() { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + try { + ConnectionOptions endpointPropertyOnly = + ConnectionOptions.newBuilder() + .setUri( + "cloudspanner:/projects/p/instances/i/databases/d" + + "?endpoint=spanner.tpc.example:443") + .setCredentials(GoogleCredentials.create(new AccessToken("test-token", null))) + .build(); + try (Spanner spanner = + SpannerPool.INSTANCE.createSpanner( + SpannerPoolKey.of(endpointPropertyOnly), endpointPropertyOnly)) { + assertFalse(spanner.getOptions().isEnableBuiltInMetrics()); + assertNull(spanner.getOptions().getBuiltInOpenTelemetry()); + } + } finally { + SpannerOptions.useDefaultEnvironment(); + } + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/LoginClientTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/LoginClientTest.java index dcfa9b5be1aa..e0da75458c96 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/LoginClientTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/LoginClientTest.java @@ -17,9 +17,32 @@ package com.google.cloud.spanner.omni; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import com.google.cloud.spanner.SpannerException; +import com.google.cloud.spanner.omni.Authentication.HashParameters; +import com.google.cloud.spanner.omni.Authentication.PasswordAuthenticationHandshakeResponse; +import com.google.cloud.spanner.omni.Authentication.PasswordAuthenticationProtocol; +import com.google.cloud.spanner.omni.Login.AccessToken; +import com.google.cloud.spanner.omni.Login.InitialOpaqueLoginRequest; +import com.google.cloud.spanner.omni.Login.InitialOpaqueLoginResponse; +import com.google.cloud.spanner.omni.Login.LoginRequest; +import com.google.cloud.spanner.omni.Login.LoginResponse; +import com.google.cloud.spanner.omni.Login.OpaqueLoginResponse; +import com.google.crypto.tink.InsecureSecretKeyAccess; +import com.google.crypto.tink.util.SecretBytes; +import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import io.grpc.Server; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -42,4 +65,239 @@ public void testExpectedEnvelopeSize() { org.junit.Assert.assertEquals( "Envelope size should be 97 bytes (33 + 32 + 32)", 97, LoginClient.EXPECTED_ENVELOPE_SIZE); } + + /** + * Verifies that {@link LoginClient#login} aborts with a {@link SpannerException} when a rogue + * server returns the point at infinity ({@code {0x00}}) as {@code evaluated_message}, even if the + * server forges an otherwise valid OPAQUE envelope and server MAC from {@code oprf = {0x00}}. + */ + @Test + public void testLoginRejectsPointAtInfinityEvaluatedMessage() throws Exception { + HashParameters fastHashParams = createFastArgon2HashParameters(); + LoginServiceGrpc.LoginServiceImplBase rogueServer = + createRoguePointAtInfinityServer(fastHashParams); + + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService(rogueServer) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + try { + LoginClient client = new LoginClient(channel); + SecretBytes password = + SecretBytes.copyFrom( + "super-secret-password".getBytes(StandardCharsets.UTF_8), + InsecureSecretKeyAccess.get()); + + SpannerException exception = + assertThrows(SpannerException.class, () -> client.login("alice", password)); + assertTrue(exception.getCause() instanceof GeneralSecurityException); + assertTrue(exception.getCause().getMessage().contains("evaluatedMessage")); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + channel.awaitTermination(5, TimeUnit.SECONDS); + server.awaitTermination(5, TimeUnit.SECONDS); + } + } + + /** Creates minimal Argon2id parameters so the OPAQUE test executes quickly. */ + private static HashParameters createFastArgon2HashParameters() { + return HashParameters.newBuilder() + .setArgon2IdParameters( + HashParameters.Argon2IdParameters.newBuilder() + .setIterationCount(1) + .setMemoryUsage(8) + .setParallelism(1) + .setHashSize(32) + .build()) + .build(); + } + + /** + * Builds a fake {@code LoginService} that negotiates OPAQUE, responds to the initial request with + * {@code evaluated_message = {0x00}} and forged envelope/MAC material, and would issue an access + * token if the client did not reject the point at infinity. + */ + private static LoginServiceGrpc.LoginServiceImplBase createRoguePointAtInfinityServer( + HashParameters hashParams) { + return new LoginServiceGrpc.LoginServiceImplBase() { + @Override + public StreamObserver login(StreamObserver responseObserver) { + return new StreamObserver() { + @Override + public void onNext(LoginRequest request) { + try { + if (request.hasHandshakeRequest()) { + responseObserver.onNext(buildHandshakeResponse(hashParams)); + } else if (request.hasOpaqueRequest() + && request.getOpaqueRequest().hasInitialRequest()) { + responseObserver.onNext( + buildForgedInitialOpaqueResponse( + request.getUsername(), + request.getOpaqueRequest().getInitialRequest(), + hashParams)); + } else if (request.hasOpaqueRequest() + && request.getOpaqueRequest().hasFinalRequest()) { + responseObserver.onNext( + LoginResponse.newBuilder() + .setAccessToken(AccessToken.newBuilder().build()) + .build()); + responseObserver.onCompleted(); + } + } catch (Exception e) { + responseObserver.onError(e); + } + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + }; + } + }; + } + + /** Builds the OPAQUE handshake response advertising the test Argon2id parameters. */ + private static LoginResponse buildHandshakeResponse(HashParameters hashParams) { + return LoginResponse.newBuilder() + .setHandshakeResponse( + PasswordAuthenticationHandshakeResponse.newBuilder() + .setPasswordAuthenticationProtocol( + PasswordAuthenticationProtocol.PASSWORD_AUTHENTICATION_PROTOCOL_OPAQUE) + .setHashParameters(hashParams) + .build()) + .build(); + } + + /** + * Builds a forged initial OPAQUE response using {@code evaluated_message = {0x00}} (point at + * infinity). Without point validation, {@code OpaqueUtil.finalize} would return {@code {0x00}}, + * allowing a rogue server without the password to derive the same envelope and AKE keys. + */ + private static LoginResponse buildForgedInitialOpaqueResponse( + String username, InitialOpaqueLoginRequest initReq, HashParameters hashParams) + throws GeneralSecurityException { + byte[] infinity = new byte[] {0x00}; + + // Derive password-independent OPRF output keys assuming finalize(blind, {0x00}) == {0x00}. + byte[] stretched = OpaqueUtil.stretch(infinity, hashParams); + byte[] randomizedPassword = OpaqueUtil.extract(OpaqueUtil.concat(infinity, stretched)); + byte[] maskingKey = + OpaqueUtil.expand( + randomizedPassword, OpaqueUtil.MASKING_KEY_INFO.getBytes(StandardCharsets.UTF_8), 32); + + byte[] maskingNonce = new byte[32]; + Arrays.fill(maskingNonce, (byte) 0x11); + byte[] pad = + OpaqueUtil.expand( + maskingKey, + OpaqueUtil.concat( + maskingNonce, "CredentialResponsePad".getBytes(StandardCharsets.UTF_8)), + LoginClient.EXPECTED_ENVELOPE_SIZE); + + // Forge an envelope containing the attacker's public key and a matching auth tag. + byte[][] serverKeyPair = + OpaqueUtil.generateKeyPair("rogue-server".getBytes(StandardCharsets.UTF_8)); + byte[] envelopeNonce = new byte[32]; + Arrays.fill(envelopeNonce, (byte) 0x22); + byte[] authKey = + OpaqueUtil.expand( + randomizedPassword, + OpaqueUtil.concat( + envelopeNonce, OpaqueUtil.AUTH_KEY_INFO.getBytes(StandardCharsets.UTF_8)), + 32); + byte[] authTag = + OpaqueUtil.mac( + authKey, + OpaqueUtil.concat( + envelopeNonce, serverKeyPair[1], username.getBytes(StandardCharsets.UTF_8))); + byte[] maskedResponse = + OpaqueUtil.xorBytes(OpaqueUtil.concat(serverKeyPair[1], envelopeNonce, authTag), pad); + + // Derive the client's static public key from the known randomizedPassword to forge AKE DH3. + byte[] clientSeed = + OpaqueUtil.expand( + randomizedPassword, + OpaqueUtil.concat( + envelopeNonce, OpaqueUtil.PRIVATE_KEY_INFO.getBytes(StandardCharsets.UTF_8)), + 32); + byte[][] clientKeyPair = + OpaqueUtil.generateKeyPair( + OpaqueUtil.concat( + clientSeed, OpaqueUtil.DIFFIE_HELLMAN_KEY_INFO.getBytes(StandardCharsets.UTF_8))); + + byte[][] serverKeysharePair = + OpaqueUtil.generateKeyPair("rogue-keyshare".getBytes(StandardCharsets.UTF_8)); + byte[] serverNonce = new byte[32]; + Arrays.fill(serverNonce, (byte) 0x33); + + byte[] serverMac = + computeForgedServerMac( + username, + initReq, + infinity, + serverNonce, + serverKeyPair, + serverKeysharePair, + clientKeyPair[1]); + + return LoginResponse.newBuilder() + .setOpaqueResponse( + OpaqueLoginResponse.newBuilder() + .setInitialResponse( + InitialOpaqueLoginResponse.newBuilder() + .setEvaluatedMessage(ByteString.copyFrom(infinity)) + .setMaskingNonce(ByteString.copyFrom(maskingNonce)) + .setMaskedResponse(ByteString.copyFrom(maskedResponse)) + .setServerNonce(ByteString.copyFrom(serverNonce)) + .setServerPublicKeyshare(ByteString.copyFrom(serverKeysharePair[1])) + .setServerMac(ByteString.copyFrom(serverMac)) + .build()) + .build()) + .build(); + } + + /** Computes the OPAQUE 3DH handshake secret and server MAC for the forged initial response. */ + private static byte[] computeForgedServerMac( + String username, + InitialOpaqueLoginRequest initReq, + byte[] evaluatedMessage, + byte[] serverNonce, + byte[][] serverKeyPair, + byte[][] serverKeysharePair, + byte[] clientPublicKey) + throws GeneralSecurityException { + byte[] clientPublicKeyshare = initReq.getClientPublicKeyshare().toByteArray(); + byte[] dh1 = OpaqueUtil.diffieHellman(serverKeysharePair[0], clientPublicKeyshare); + byte[] dh2 = OpaqueUtil.diffieHellman(serverKeyPair[0], clientPublicKeyshare); + byte[] dh3 = OpaqueUtil.diffieHellman(serverKeysharePair[0], clientPublicKey); + + byte[] preamble = + OpaqueUtil.concat( + "OPAQUEv1-".getBytes(StandardCharsets.UTF_8), + username.getBytes(StandardCharsets.UTF_8), + initReq.getClientNonce().toByteArray(), + clientPublicKeyshare, + serverKeyPair[1], + evaluatedMessage, + serverNonce, + serverKeysharePair[1]); + byte[] prk = OpaqueUtil.extract(OpaqueUtil.concat(dh1, dh2, dh3)); + byte[] preambleHash = OpaqueUtil.sha256(preamble); + byte[] handshakeSecret = + OpaqueUtil.expand( + prk, + OpaqueUtil.concat( + "OPAQUE-HandshakeSecret".getBytes(StandardCharsets.UTF_8), preambleHash), + 32); + byte[] km2 = + OpaqueUtil.expand(handshakeSecret, "OPAQUE-ServerMAC".getBytes(StandardCharsets.UTF_8), 32); + return OpaqueUtil.mac(km2, preambleHash); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/OpaqueUtilTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/OpaqueUtilTest.java index d411af2704fe..f0bdb5bb0751 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/OpaqueUtilTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/omni/OpaqueUtilTest.java @@ -18,11 +18,13 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigInteger; import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; import java.security.SecureRandom; import java.util.Arrays; import org.bouncycastle.asn1.x9.X9ECParameters; @@ -589,4 +591,157 @@ public void testOpfrEvaluate() throws Exception { assertArrayEquals(oprf, prf); } + + @Test + public void testFinalizeRejectsPointAtInfinity() { + byte[] validBlind = new byte[32]; + validBlind[31] = 7; + + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, + () -> OpaqueUtil.finalize(validBlind, new byte[] {0x00})); + assertTrue(exception.getMessage().contains("evaluatedMessage")); + } + + @Test + public void testFinalizeRejectsInvalidPointEncodings() { + X9ECParameters params = CustomNamedCurves.getByName(OpaqueUtil.CURVE_NAME); + ECPoint generator = params.getG(); + byte[] validBlind = new byte[32]; + validBlind[31] = 7; + + byte[] uncompressed = generator.getEncoded(false); + byte[] hybridEven = Arrays.copyOf(uncompressed, uncompressed.length); + hybridEven[0] = 0x06; + byte[] hybridOdd = Arrays.copyOf(uncompressed, uncompressed.length); + hybridOdd[0] = 0x07; + + byte[] validCompressed = generator.getEncoded(true); + byte[] invalidPrefix = Arrays.copyOf(validCompressed, validCompressed.length); + invalidPrefix[0] = 0x01; + byte[] tooShort = Arrays.copyOf(validCompressed, OpaqueUtil.PUBLIC_KEY_LENGTH - 1); + byte[] tooLong = Arrays.copyOf(validCompressed, OpaqueUtil.PUBLIC_KEY_LENGTH + 1); + + // Non-canonical x >= p (all 0xFF bytes exceed the secp256r1 field prime p). + byte[] xGreaterOrEqualP = new byte[OpaqueUtil.PUBLIC_KEY_LENGTH]; + Arrays.fill(xGreaterOrEqualP, (byte) 0xFF); + xGreaterOrEqualP[0] = 0x02; + + // Deterministic off-curve x = 1: x^3 - 3x + b is a quadratic non-residue mod p on secp256r1. + byte[] offCurveX = new byte[OpaqueUtil.PUBLIC_KEY_LENGTH]; + offCurveX[0] = 0x02; + offCurveX[32] = 0x01; + + byte[][] invalidPoints = + new byte[][] { + null, + new byte[0], + uncompressed, + hybridEven, + hybridOdd, + invalidPrefix, + tooShort, + tooLong, + xGreaterOrEqualP, + offCurveX + }; + + for (byte[] invalidPoint : invalidPoints) { + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, () -> OpaqueUtil.finalize(validBlind, invalidPoint)); + assertTrue(exception.getMessage().contains("evaluatedMessage")); + } + } + + @Test + public void testFinalizeRejectsInvalidBlindScalar() { + X9ECParameters params = CustomNamedCurves.getByName(OpaqueUtil.CURVE_NAME); + byte[] validPoint = params.getG().getEncoded(true); + + byte[][] invalidBlinds = + new byte[][] {null, new byte[0], new byte[32], params.getN().toByteArray()}; + + for (byte[] invalidBlind : invalidBlinds) { + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, () -> OpaqueUtil.finalize(invalidBlind, validPoint)); + assertTrue(exception.getMessage().contains("blind")); + } + } + + @Test + public void testDiffieHellmanRejectsPointAtInfinityAndInvalidEncodings() { + X9ECParameters params = CustomNamedCurves.getByName(OpaqueUtil.CURVE_NAME); + ECPoint generator = params.getG(); + byte[] validPrivateKey = new byte[32]; + validPrivateKey[31] = 5; + byte[] validPeerPublicKey = generator.getEncoded(true); + + byte[] uncompressed = generator.getEncoded(false); + byte[] hybridEven = Arrays.copyOf(uncompressed, uncompressed.length); + hybridEven[0] = 0x06; + byte[] offCurveX = new byte[OpaqueUtil.PUBLIC_KEY_LENGTH]; + offCurveX[0] = 0x02; + offCurveX[32] = 0x01; + + byte[][] invalidPeerKeys = + new byte[][] {new byte[] {0x00}, null, new byte[0], uncompressed, hybridEven, offCurveX}; + for (byte[] invalidPeerKey : invalidPeerKeys) { + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, + () -> OpaqueUtil.diffieHellman(validPrivateKey, invalidPeerKey)); + assertTrue(exception.getMessage().contains("peerPublicKey")); + } + + byte[][] invalidPrivateKeys = + new byte[][] {null, new byte[0], new byte[32], params.getN().toByteArray()}; + for (byte[] invalidPrivateKey : invalidPrivateKeys) { + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, + () -> OpaqueUtil.diffieHellman(invalidPrivateKey, validPeerPublicKey)); + assertTrue(exception.getMessage().contains("privateKey")); + } + } + + @Test + public void testBlindRejectsInvalidBlindScalar() { + X9ECParameters params = CustomNamedCurves.getByName(OpaqueUtil.CURVE_NAME); + byte[] password = "password1234".getBytes(StandardCharsets.UTF_8); + + byte[][] invalidScalars = + new byte[][] {null, new byte[0], new byte[32], params.getN().toByteArray()}; + + for (byte[] invalidScalar : invalidScalars) { + GeneralSecurityException exception = + assertThrows( + GeneralSecurityException.class, () -> OpaqueUtil.blind(password, invalidScalar)); + assertTrue(exception.getMessage().contains("blindScalar")); + } + } + + @Test + public void testOversizedScalarReducedModuloOrder() throws Exception { + X9ECParameters params = CustomNamedCurves.getByName(OpaqueUtil.CURVE_NAME); + byte[] validPoint = params.getG().getEncoded(true); + byte[] password = "password1234".getBytes(StandardCharsets.UTF_8); + + // 2^65536 has bitLength >= 65536 (which exceeds BouncyCastle WNafUtil's limit if unreduced) + // and is non-zero modulo the prime curve order. + byte[] oversizedScalar = new byte[8193]; + oversizedScalar[0] = 1; + byte[] reducedScalar = new BigInteger(1, oversizedScalar).mod(params.getN()).toByteArray(); + + assertArrayEquals( + OpaqueUtil.diffieHellman(reducedScalar, validPoint), + OpaqueUtil.diffieHellman(oversizedScalar, validPoint)); + assertArrayEquals( + OpaqueUtil.blind(password, reducedScalar), OpaqueUtil.blind(password, oversizedScalar)); + assertArrayEquals( + OpaqueUtil.finalize(reducedScalar, validPoint), + OpaqueUtil.finalize(oversizedScalar, validPoint)); + } } diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionStateTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionStateTest.java new file mode 100644 index 000000000000..0b2c10ed97a0 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteResumptionStateTest.java @@ -0,0 +1,236 @@ +/* + * 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.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.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.StatusCode.Code; +import com.google.protobuf.ListValue; +import com.google.protobuf.Value; +import com.google.rpc.Status; +import com.google.spanner.v1.BatchWriteRequest; +import com.google.spanner.v1.BatchWriteResponse; +import com.google.spanner.v1.Mutation; +import com.google.spanner.v1.RequestOptions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link BatchWriteResumptionState}. */ +@RunWith(JUnit4.class) +public class BatchWriteResumptionStateTest { + + private static final Status STATUS_OK = + Status.newBuilder().setCode(com.google.rpc.Code.OK_VALUE).build(); + private static final Status STATUS_ABORTED = + Status.newBuilder().setCode(com.google.rpc.Code.ABORTED_VALUE).build(); + + private static BatchWriteRequest.MutationGroup groupWithKey(String key) { + return BatchWriteRequest.MutationGroup.newBuilder() + .addMutations( + Mutation.newBuilder() + .setInsert( + Mutation.Write.newBuilder() + .setTable("T") + .addColumns("K") + .addValues( + ListValue.newBuilder() + .addValues(Value.newBuilder().setStringValue(key).build()) + .build()) + .build()) + .build()) + .build(); + } + + private static BatchWriteRequest requestWithGroups(String... keys) { + BatchWriteRequest.Builder builder = + BatchWriteRequest.newBuilder() + .setSession("projects/p/instances/i/databases/d/sessions/s1") + .setRequestOptions(RequestOptions.newBuilder().setTransactionTag("tag-1").build()) + .setExcludeTxnFromChangeStreams(true); + for (String key : keys) { + builder.addMutationGroups(groupWithKey(key)); + } + return builder.build(); + } + + @Test + public void emptyRequestIsImmediatelyAcknowledged() { + BatchWriteResumptionState state = new BatchWriteResumptionState(requestWithGroups()); + assertTrue(state.isAllAcknowledged()); + assertEquals(0, state.getRemainingCount()); + assertEquals(0, state.getTotalCount()); + assertEquals(0, state.getRequestTemplate().getMutationGroupsCount()); + } + + @Test + public void translatesIndexesAcrossMultipleCompactedAttemptsAndPreservesRequestMetadata() { + BatchWriteRequest initial = requestWithGroups("g0", "g1", "g2", "g3", "g4"); + BatchWriteResumptionState state = new BatchWriteResumptionState(initial); + + // Attempt 0: all 5 groups [0, 1, 2, 3, 4] + BatchWriteRequest attempt0 = state.buildNextAttemptRequest(); + assertEquals(5, attempt0.getMutationGroupsCount()); + assertEquals("tag-1", attempt0.getRequestOptions().getTransactionTag()); + assertTrue(attempt0.getExcludeTxnFromChangeStreams()); + + // Acknowledge relative 1 (orig 1) with OK and relative 3 (orig 3) with non-OK ABORTED. + // On the initial full-batch attempt, response is returned directly without copying. + BatchWriteResponse rawResp0 = + BatchWriteResponse.newBuilder().setStatus(STATUS_OK).addIndexes(1).build(); + BatchWriteResponse resp0 = state.translateAndAcknowledge(rawResp0); + assertSame(rawResp0, resp0); + assertThat(resp0.getIndexesList()).containsExactly(1); + BatchWriteResponse resp1 = + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder().setStatus(STATUS_ABORTED).addIndexes(3).build()); + assertThat(resp1.getIndexesList()).containsExactly(3); + assertEquals(3, state.getRemainingCount()); + assertFalse(state.isAllAcknowledged()); + + // Attempt 1: compacted to remaining [g0 -> 0, g2 -> 1, g4 -> 2] + BatchWriteRequest attempt1 = state.buildNextAttemptRequest(); + assertEquals(3, attempt1.getMutationGroupsCount()); + assertEquals(groupWithKey("g0"), attempt1.getMutationGroups(0)); + assertEquals(groupWithKey("g2"), attempt1.getMutationGroups(1)); + assertEquals(groupWithKey("g4"), attempt1.getMutationGroups(2)); + assertEquals("tag-1", attempt1.getRequestOptions().getTransactionTag()); + assertTrue(attempt1.getExcludeTxnFromChangeStreams()); + + // Acknowledge relative [2, 0] -> original [4, 0] + BatchWriteResponse resp2 = + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder() + .setStatus(STATUS_OK) + .addIndexes(2) + .addIndexes(0) + .build()); + assertThat(resp2.getIndexesList()).containsExactly(4, 0).inOrder(); + assertEquals(1, state.getRemainingCount()); + + // Attempt 2: compacted to [g2 -> 0] + BatchWriteRequest attempt2 = state.buildNextAttemptRequest(); + assertEquals(1, attempt2.getMutationGroupsCount()); + assertEquals(groupWithKey("g2"), attempt2.getMutationGroups(0)); + + BatchWriteResponse resp3 = + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder().setStatus(STATUS_OK).addIndexes(0).build()); + assertThat(resp3.getIndexesList()).containsExactly(2); + assertTrue(state.isAllAcknowledged()); + assertEquals(0, state.getRemainingCount()); + } + + @Test + public void duplicateIndexesAreTranslatedAndDecrementedOnlyOnce() { + BatchWriteResumptionState state = new BatchWriteResumptionState(requestWithGroups("g0", "g1")); + state.buildNextAttemptRequest(); + + BatchWriteResponse resp = + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder() + .setStatus(STATUS_OK) + .addIndexes(0) + .addIndexes(0) + .build()); + assertThat(resp.getIndexesList()).containsExactly(0, 0); + assertEquals(1, state.getRemainingCount()); + assertFalse(state.isAllAcknowledged()); + } + + @Test + public void translateAndAcknowledgeBeforeBuildNextAttemptRequestThrowsIllegalState() { + BatchWriteResumptionState state = new BatchWriteResumptionState(requestWithGroups("g0")); + assertThrows( + IllegalStateException.class, + () -> + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder().setStatus(STATUS_OK).build())); + } + + @Test + public void outOfBoundsIndexThrowsNonRetryableInternalWithoutMutatingState() { + BatchWriteResumptionState state = new BatchWriteResumptionState(requestWithGroups("g0", "g1")); + state.buildNextAttemptRequest(); + + // Mixed valid index 0 + invalid index 2 must leave tracking state unmodified. + ApiException highEx = + assertThrows( + ApiException.class, + () -> + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder() + .setStatus(STATUS_OK) + .addIndexes(0) + .addIndexes(2) + .build())); + assertEquals(Code.INTERNAL, highEx.getStatusCode().getCode()); + assertFalse(highEx.isRetryable()); + assertEquals(2, state.getRemainingCount()); + + // Negative index also rejected atomically. + ApiException negEx = + assertThrows( + ApiException.class, + () -> + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder().setStatus(STATUS_OK).addIndexes(-1).build())); + assertEquals(Code.INTERNAL, negEx.getStatusCode().getCode()); + assertFalse(negEx.isRetryable()); + assertEquals(2, state.getRemainingCount()); + } + + @Test + public void requestTemplateAndPendingSlotClearAcknowledgedPayloads() { + BatchWriteRequest.MutationGroup group0 = groupWithKey("payload-0"); + BatchWriteRequest.MutationGroup group1 = groupWithKey("payload-1"); + BatchWriteRequest initial = + BatchWriteRequest.newBuilder() + .setSession("projects/p/instances/i/databases/d/sessions/s1") + .addMutationGroups(group0) + .addMutationGroups(group1) + .build(); + BatchWriteResumptionState state = new BatchWriteResumptionState(initial); + + // Request template must not retain any mutation group payloads. + assertEquals(0, state.getRequestTemplate().getMutationGroupsCount()); + assertSame(group0, state.getPending(0)); + assertSame(group1, state.getPending(1)); + + state.buildNextAttemptRequest(); + state.translateAndAcknowledge( + BatchWriteResponse.newBuilder().setStatus(STATUS_OK).addIndexes(0).build()); + + // Acknowledged slot must be nulled out while unacknowledged group remains intact. + assertNull(state.getPending(0)); + assertNotNull(state.getPending(1)); + assertSame(group1, state.getPending(1)); + assertEquals(1, state.getRemainingCount()); + + BatchWriteRequest retryRequest = state.buildNextAttemptRequest(); + assertEquals(1, retryRequest.getMutationGroupsCount()); + assertEquals(group1, retryRequest.getMutationGroups(0)); + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicyTest.java new file mode 100644 index 000000000000..2fa609be7e43 --- /dev/null +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicyTest.java @@ -0,0 +1,615 @@ +/* + * 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.spi.v1; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import com.google.api.core.ApiClock; +import com.google.api.gax.grpc.GrpcStatusCode; +import com.google.api.gax.retrying.RetrySettings; +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.ApiExceptionFactory; +import com.google.api.gax.rpc.ErrorDetails; +import com.google.api.gax.rpc.StatusCode.Code; +import com.google.api.gax.rpc.WatchdogTimeoutException; +import com.google.cloud.spanner.StreamingRetryHelper; +import com.google.cloud.spanner.spi.v1.BatchWriteRetryPolicy.Action; +import com.google.cloud.spanner.spi.v1.BatchWriteRetryPolicy.RetryDecision; +import com.google.common.collect.ImmutableSet; +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.util.Durations; +import com.google.rpc.RetryInfo; +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.ProtoUtils; +import java.lang.reflect.Constructor; +import java.time.Duration; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link BatchWriteRetryPolicy}. */ +@RunWith(JUnit4.class) +public class BatchWriteRetryPolicyTest { + + private static final Set DEFAULT_CODES = + ImmutableSet.of(Code.UNAVAILABLE, Code.RESOURCE_EXHAUSTED); + + private static RetrySettings defaultSettings() { + return RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofMillis(100)) + .setRetryDelayMultiplier(2.0) + .setMaxRetryDelayDuration(Duration.ofSeconds(10)) + .setMaxAttempts(5) + .setInitialRpcTimeoutDuration(Duration.ofSeconds(30)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeoutDuration(Duration.ofSeconds(30)) + .setTotalTimeoutDuration(Duration.ofMinutes(5)) + .build(); + } + + private static ApiException apiException(Status.Code code, String msg) { + return ApiExceptionFactory.createException( + msg, null, GrpcStatusCode.of(code), /* retryable= */ false); + } + + private static WatchdogTimeoutException watchdogTimeout(boolean retryable) { + try { + Constructor ctor = + WatchdogTimeoutException.class.getDeclaredConstructor(String.class, boolean.class); + ctor.setAccessible(true); + return ctor.newInstance(retryable ? "wait timeout" : "idle timeout", retryable); + } catch (ReflectiveOperationException e) { + throw new AssertionError("Failed to construct WatchdogTimeoutException", e); + } + } + + private static final class FakeClock extends Deadline.Ticker implements ApiClock { + private final AtomicLong nanos = new AtomicLong(1_000_000_000L); + + @Override + public long nanoTime() { + return nanos.get(); + } + + @Override + public long millisTime() { + return TimeUnit.NANOSECONDS.toMillis(nanos.get()); + } + + void advanceMillis(long millis) { + nanos.addAndGet(TimeUnit.MILLISECONDS.toNanos(millis)); + } + } + + @Test + public void isRetryableCoversRetryableCodesInternalErrorsAndWatchdogTimeouts() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + + assertTrue(policy.isRetryable(apiException(Status.Code.UNAVAILABLE, "transient"))); + assertTrue(policy.isRetryable(apiException(Status.Code.RESOURCE_EXHAUSTED, "throttled"))); + assertTrue(policy.isRetryable(Status.UNAVAILABLE.withDescription("grpc").asRuntimeException())); + assertTrue(policy.isRetryable(Status.RESOURCE_EXHAUSTED.withDescription("grpc").asException())); + assertTrue( + policy.isRetryable( + apiException(Status.Code.INTERNAL, "HTTP/2 error code: INTERNAL_ERROR"))); + assertTrue(policy.isRetryable(watchdogTimeout(true))); + + assertFalse(policy.isRetryable(apiException(Status.Code.INVALID_ARGUMENT, "bad"))); + assertFalse(policy.isRetryable(Status.INVALID_ARGUMENT.asRuntimeException())); + assertFalse(policy.isRetryable(Status.PERMISSION_DENIED.asException())); + assertFalse(policy.isRetryable(apiException(Status.Code.INTERNAL, "unexpected bug"))); + assertFalse(policy.isRetryable(watchdogTimeout(false))); + + // Empty retryableCodes disables all retries including retryable INTERNAL and wait watchdog. + BatchWriteRetryPolicy disabledPolicy = + new BatchWriteRetryPolicy(defaultSettings(), Collections.emptySet(), clock, () -> 1.0); + assertFalse(disabledPolicy.isRetryable(apiException(Status.Code.UNAVAILABLE, "transient"))); + assertFalse( + disabledPolicy.isRetryable( + apiException(Status.Code.INTERNAL, "HTTP/2 error code: INTERNAL_ERROR"))); + assertFalse(disabledPolicy.isRetryable(watchdogTimeout(true))); + } + + @Test + public void backoffAppliesJitterAndCapsAtMaxRetryDelay() { + FakeClock clock = new FakeClock(); + // jitterRandom = 0.0 -> factor 0.5; jitterRandom = 1.0 -> factor 1.0 + BatchWriteRetryPolicy minJitter = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 0.0); + BatchWriteRetryPolicy maxJitter = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + + Throwable err = apiException(Status.Code.UNAVAILABLE, "transient"); + assertEquals(Duration.ofMillis(50), minJitter.computeNextRetryDelay(err, 1)); + assertEquals(Duration.ofMillis(100), maxJitter.computeNextRetryDelay(err, 1)); + assertEquals(Duration.ofMillis(100), minJitter.computeNextRetryDelay(err, 2)); + assertEquals(Duration.ofMillis(200), maxJitter.computeNextRetryDelay(err, 2)); + // Attempt 10 would exceed 10s cap -> capped at 10_000ms * factor + assertEquals(Duration.ofSeconds(5), minJitter.computeNextRetryDelay(err, 10)); + assertEquals(Duration.ofSeconds(10), maxJitter.computeNextRetryDelay(err, 10)); + } + + @Test + public void retryInfoTrailerOverridesExponentialBackoffAndCorruptedTrailerFallsBack() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + + Metadata trailers = new Metadata(); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + trailers.put(key, RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(345)).build()); + StatusRuntimeException withRetryInfo = + Status.UNAVAILABLE.withDescription("retry later").asRuntimeException(trailers); + + assertEquals(Duration.ofMillis(345), policy.computeNextRetryDelay(withRetryInfo, 1)); + + // RetryInfo provided via ApiException.getErrorDetails() overrides exponential backoff. + RetryInfo detailsRetryInfo = + RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(678)).build(); + ApiException withErrorDetails = + ApiExceptionFactory.createException( + "retry via error details", + null, + GrpcStatusCode.of(Status.Code.UNAVAILABLE), + /* retryable= */ true, + ErrorDetails.builder() + .setRawErrorMessages(Collections.singletonList(Any.pack(detailsRetryInfo))) + .build()); + assertEquals(Duration.ofMillis(678), policy.computeNextRetryDelay(withErrorDetails, 1)); + + // Corrupted RetryInfo bytes must fall back to exponential backoff (100ms). + Metadata badTrailers = new Metadata(); + badTrailers.put( + Metadata.Key.of("google.rpc.retryinfo-bin", Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}); + StatusRuntimeException withBadTrailer = + Status.UNAVAILABLE.withDescription("corrupt trailer").asRuntimeException(badTrailers); + + assertEquals(Duration.ofMillis(100), policy.computeNextRetryDelay(withBadTrailer, 1)); + + // Negative RetryInfo duration must fall back to exponential backoff. + Metadata negativeTrailers = new Metadata(); + negativeTrailers.put( + key, RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(-500)).build()); + StatusRuntimeException withNegativeRetryInfo = + Status.UNAVAILABLE.withDescription("negative delay").asRuntimeException(negativeTrailers); + assertNull(StreamingRetryHelper.extractServerRetryDelay(withNegativeRetryInfo)); + assertEquals(Duration.ofMillis(100), policy.computeNextRetryDelay(withNegativeRetryInfo, 1)); + + // Mutating caller-supplied retryableCodes after construction must not affect the policy. + Set mutableCodes = EnumSet.of(Code.UNAVAILABLE); + BatchWriteRetryPolicy isolatedPolicy = + new BatchWriteRetryPolicy(defaultSettings(), mutableCodes, clock, () -> 1.0); + mutableCodes.clear(); + assertTrue(isolatedPolicy.isRetryable(apiException(Status.Code.UNAVAILABLE, "transient"))); + } + + @Test + public void evaluateEnforcesMaxAttemptsTotalTimeoutContextAndCallOptionsDeadlines() { + FakeClock clock = new FakeClock(); + RetrySettings settings = + defaultSettings().toBuilder() + .setMaxAttempts(3) + .setTotalTimeoutDuration(Duration.ofMillis(500)) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(settings, DEFAULT_CODES, clock, () -> 1.0); + Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); + long startNanos = clock.nanoTime(); + + // Non-retryable error -> PERMANENT_FAILURE + Throwable invalidArgument = apiException(Status.Code.INVALID_ARGUMENT, "bad"); + RetryDecision permanentFailure = + policy.evaluate(invalidArgument, 1, startNanos, Context.ROOT, null); + assertEquals(Action.PERMANENT_FAILURE, permanentFailure.action); + assertEquals(invalidArgument, permanentFailure.terminalError); + + // maxAttempts == 0 means unlimited retries (GAX convention) + BatchWriteRetryPolicy unlimitedPolicy = + new BatchWriteRetryPolicy( + defaultSettings().toBuilder().setMaxAttempts(0).build(), + DEFAULT_CODES, + clock, + () -> 1.0); + RetryDecision unlimitedDecision = + unlimitedPolicy.evaluate(unavailable, 100, startNanos, Context.ROOT, null); + assertEquals(Action.RETRY, unlimitedDecision.action); + + // Attempt 1 -> retry with 100ms delay + RetryDecision d1 = policy.evaluate(unavailable, 1, startNanos, Context.ROOT, null); + assertEquals(Action.RETRY, d1.action); + assertEquals(Duration.ofMillis(100), d1.delay); + + // Attempt 3 == maxAttempts -> retries exhausted + RetryDecision exhausted = policy.evaluate(unavailable, 3, startNanos, Context.ROOT, null); + assertEquals(Action.RETRIES_EXHAUSTED, exhausted.action); + assertEquals(unavailable, exhausted.terminalError); + + // Advance clock to 450ms elapsed; next delay 100ms exceeds remaining 50ms of 500ms totalTimeout + clock.advanceMillis(450); + RetryDecision totalTimeout = policy.evaluate(unavailable, 1, startNanos, Context.ROOT, null); + assertEquals(Action.RETRIES_EXHAUSTED, totalTimeout.action); + assertEquals( + Code.DEADLINE_EXCEEDED, + ((ApiException) totalTimeout.terminalError).getStatusCode().getCode()); + + // Deterministic CallOptions deadlines via FakeClock (Deadline.Ticker): + // deadline larger than 100ms delay -> RETRY; deadline shorter than 100ms delay -> + // RETRIES_EXHAUSTED with DEADLINE_EXCEEDED. + FakeClock freshClock = new FakeClock(); + BatchWriteRetryPolicy freshPolicy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, freshClock, () -> 1.0); + Deadline generousCallDeadline = Deadline.after(500, TimeUnit.MILLISECONDS, freshClock); + RetryDecision generousCallDecision = + freshPolicy.evaluate( + unavailable, 1, freshClock.nanoTime(), Context.ROOT, generousCallDeadline); + assertEquals(Action.RETRY, generousCallDecision.action); + assertEquals(Duration.ofMillis(100), generousCallDecision.delay); + + Deadline tightCallDeadline = Deadline.after(20, TimeUnit.MILLISECONDS, freshClock); + RetryDecision callDeadlineDecision = + freshPolicy.evaluate( + unavailable, 1, freshClock.nanoTime(), Context.ROOT, tightCallDeadline); + assertEquals(Action.RETRIES_EXHAUSTED, callDeadlineDecision.action); + assertEquals( + Code.DEADLINE_EXCEEDED, + ((ApiException) callDeadlineDecision.terminalError).getStatusCode().getCode()); + + // Cancelled gRPC context -> CANCELLED; expired gRPC context -> PERMANENT_FAILURE + // DEADLINE_EXCEEDED + Context.CancellableContext cancelled = Context.ROOT.withCancellation(); + cancelled.cancel(null); + try { + RetryDecision cancelDecision = + freshPolicy.evaluate(unavailable, 1, freshClock.nanoTime(), cancelled, null); + assertEquals(Action.CANCELLED, cancelDecision.action); + assertEquals( + Code.CANCELLED, ((ApiException) cancelDecision.terminalError).getStatusCode().getCode()); + } finally { + cancelled.close(); + } + + ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + // Active (non-cancelled) grpcContext deadline shorter than 100ms retry delay -> + // RETRIES_EXHAUSTED with DEADLINE_EXCEEDED. Schedule wall-clock cancellation far out (10s) and + // advance FakeClock by 9980ms so 20ms deterministically remain without racing the scheduler. + Context.CancellableContext tightContext = + Context.ROOT.withDeadline(Deadline.after(10, TimeUnit.SECONDS, freshClock), scheduler); + try { + freshClock.advanceMillis(9_980); + assertFalse(tightContext.isCancelled()); + RetryDecision tightContextDecision = + freshPolicy.evaluate(unavailable, 1, freshClock.nanoTime(), tightContext, null); + assertEquals(Action.RETRIES_EXHAUSTED, tightContextDecision.action); + assertEquals( + Code.DEADLINE_EXCEEDED, + ((ApiException) tightContextDecision.terminalError).getStatusCode().getCode()); + } finally { + tightContext.close(); + } + + Context.CancellableContext expired = + Context.ROOT.withDeadline(Deadline.after(-1, TimeUnit.SECONDS, freshClock), scheduler); + try { + RetryDecision deadlineDecision = + freshPolicy.evaluate(unavailable, 1, freshClock.nanoTime(), expired, null); + assertEquals(Action.PERMANENT_FAILURE, deadlineDecision.action); + assertEquals( + Code.DEADLINE_EXCEEDED, + ((ApiException) deadlineDecision.terminalError).getStatusCode().getCode()); + } finally { + expired.close(); + scheduler.shutdownNow(); + } + } + + @Test + public void computeAttemptRpcTimeoutScalesCapsAndClampsToRemainingTotalTimeout() { + FakeClock clock = new FakeClock(); + RetrySettings settings = + defaultSettings().toBuilder() + .setInitialRpcTimeoutDuration(Duration.ofSeconds(10)) + .setRpcTimeoutMultiplier(2.0) + .setMaxRpcTimeoutDuration(Duration.ofSeconds(25)) + .setTotalTimeoutDuration(Duration.ofSeconds(60)) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(settings, DEFAULT_CODES, clock, () -> 1.0); + long startNanos = clock.nanoTime(); + + // Attempt 0: initial 10s + assertEquals(Duration.ofSeconds(10), policy.computeAttemptRpcTimeout(0, null, startNanos)); + // Attempt 1: 10s * 2.0 = 20s (verifies rpcTimeoutMultiplier) + assertEquals(Duration.ofSeconds(20), policy.computeAttemptRpcTimeout(1, null, startNanos)); + // Attempt 2: min(10s * 4.0, 25s) = 25s (verifies maxRpcTimeoutDuration cap) + assertEquals(Duration.ofSeconds(25), policy.computeAttemptRpcTimeout(2, null, startNanos)); + // Explicit smaller timeout wins over configured RPC timeout + assertEquals( + Duration.ofSeconds(4), + policy.computeAttemptRpcTimeout(0, Duration.ofSeconds(4), startNanos)); + // Attempt 1 after 57s elapsed: remaining totalTimeout is 3s < 20s scaled RPC timeout + clock.advanceMillis(57_000); + assertEquals(Duration.ofSeconds(3), policy.computeAttemptRpcTimeout(1, null, startNanos)); + + // checkDeadlineExceeded returns null when within budget and DEADLINE_EXCEEDED once past budget + assertNull(policy.checkDeadlineExceeded(startNanos, Context.ROOT, null, Duration.ZERO, null)); + clock.advanceMillis(3_000); + ApiException exceeded = + policy.checkDeadlineExceeded(startNanos, Context.ROOT, null, Duration.ZERO, null); + assertNotNull(exceeded); + assertEquals(Code.DEADLINE_EXCEEDED, exceeded.getStatusCode().getCode()); + } + + @Test + public void zeroInitialRetryDelayProducesZeroBackoff() { + FakeClock clock = new FakeClock(); + RetrySettings zeroDelaySettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ZERO) + .setMaxRetryDelayDuration(Duration.ZERO) + .setMaxAttempts(5) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(zeroDelaySettings, DEFAULT_CODES, clock, () -> 1.0); + Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); + assertEquals(Duration.ZERO, policy.computeNextRetryDelay(unavailable, 1)); + } + + @Test + public void retryInfoExceedingMaxRetryDelayIsClamped() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + Metadata trailers = new Metadata(); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + trailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(Durations.fromSeconds(TimeUnit.HOURS.toSeconds(3L))) + .build()); + StatusRuntimeException threeHourError = + Status.UNAVAILABLE.withDescription("slow down").asRuntimeException(trailers); + + assertEquals(Duration.ofSeconds(10), policy.computeNextRetryDelay(threeHourError, 1)); + RetryDecision decision = + policy.evaluate(threeHourError, 1, clock.nanoTime(), Context.ROOT, null); + assertEquals(Action.RETRY, decision.action); + assertEquals(Duration.ofSeconds(10), decision.delay); + } + + @Test + public void retryInfoWithUnsetMaxRetryDelayIsClampedToDefaultCap() { + FakeClock clock = new FakeClock(); + RetrySettings unsetMaxSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ZERO) + .setMaxRetryDelayDuration(Duration.ZERO) + .setMaxAttempts(5) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(unsetMaxSettings, DEFAULT_CODES, clock, () -> 1.0); + Metadata trailers = new Metadata(); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + trailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(Durations.fromSeconds(TimeUnit.HOURS.toSeconds(3L))) + .build()); + StatusRuntimeException threeHourError = + Status.UNAVAILABLE.withDescription("slow down").asRuntimeException(trailers); + + assertEquals(Duration.ofSeconds(32), policy.computeNextRetryDelay(threeHourError, 1)); + } + + @Test + public void zeroRetryInfoFallsBackToBackoffAndSubMillisecondIsPreserved() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + Metadata.Key key = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + + Metadata zeroTrailers = new Metadata(); + zeroTrailers.put(key, RetryInfo.newBuilder().setRetryDelay(Durations.ZERO).build()); + StatusRuntimeException zeroError = + Status.UNAVAILABLE.withDescription("zero delay").asRuntimeException(zeroTrailers); + assertNull(StreamingRetryHelper.extractServerRetryDelay(zeroError)); + assertEquals(Duration.ofMillis(100), policy.computeNextRetryDelay(zeroError, 1)); + + Metadata oneNanoTrailers = new Metadata(); + oneNanoTrailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(com.google.protobuf.Duration.newBuilder().setNanos(1).build()) + .build()); + StatusRuntimeException oneNanoError = + Status.UNAVAILABLE.withDescription("1ns delay").asRuntimeException(oneNanoTrailers); + assertEquals(Duration.ofNanos(1), StreamingRetryHelper.extractServerRetryDelay(oneNanoError)); + assertEquals(Duration.ofNanos(1), policy.computeNextRetryDelay(oneNanoError, 1)); + + Metadata subMsTrailers = new Metadata(); + subMsTrailers.put( + key, + RetryInfo.newBuilder() + .setRetryDelay(com.google.protobuf.Duration.newBuilder().setNanos(500_000).build()) + .build()); + StatusRuntimeException subMsError = + Status.UNAVAILABLE.withDescription("sub-ms delay").asRuntimeException(subMsTrailers); + assertEquals( + Duration.ofNanos(500_000), StreamingRetryHelper.extractServerRetryDelay(subMsError)); + assertEquals(Duration.ofNanos(500_000), policy.computeNextRetryDelay(subMsError, 1)); + } + + @Test + public void unsetInitialAndMaxRetryDelayPreservesZeroBackoff() { + FakeClock clock = new FakeClock(); + RetrySettings unsetSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ZERO) + .setRetryDelayMultiplier(10.0) + .setMaxRetryDelayDuration(Duration.ZERO) + .setMaxAttempts(10) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(unsetSettings, DEFAULT_CODES, clock, () -> 1.0); + Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); + + assertEquals(Duration.ZERO, policy.computeNextRetryDelay(unavailable, 1)); + assertEquals(Duration.ZERO, policy.computeNextRetryDelay(unavailable, 5)); + } + + @Test + public void extractsRetryInfoFromGrpcStatusDetailsAndSurvivesCorruptAny() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + Metadata.Key detailsKey = + Metadata.Key.of("grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER); + Metadata.Key retryInfoKey = ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); + + // Valid grpc-status-details-bin on a wrapped cause chain. + com.google.rpc.Status validStatus = + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.UNAVAILABLE_VALUE) + .addDetails( + Any.pack(RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(450L)).build())) + .build(); + Metadata validDetails = new Metadata(); + validDetails.put(detailsKey, validStatus.toByteArray()); + Throwable wrappedStatus = + new RuntimeException("outer", Status.UNAVAILABLE.asRuntimeException(validDetails)); + assertEquals(Duration.ofMillis(450), policy.computeNextRetryDelay(wrappedStatus, 1)); + + // Corrupt Any RetryInfo inside grpc-status-details-bin falls back to backoff. + Any corruptRetryInfoAny = + Any.newBuilder() + .setTypeUrl("type.googleapis.com/google.rpc.RetryInfo") + .setValue(ByteString.copyFrom(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF})) + .build(); + com.google.rpc.Status corruptStatus = + com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.UNAVAILABLE_VALUE) + .addDetails(corruptRetryInfoAny) + .build(); + Metadata corruptDetails = new Metadata(); + corruptDetails.put(detailsKey, corruptStatus.toByteArray()); + StatusRuntimeException corruptAnyError = + Status.UNAVAILABLE.withDescription("corrupt any").asRuntimeException(corruptDetails); + assertEquals(Duration.ofMillis(100), policy.computeNextRetryDelay(corruptAnyError, 1)); + + // Corrupt ErrorDetails falls through to a valid google.rpc.retryinfo-bin trailer. + Metadata mixedTrailers = new Metadata(); + mixedTrailers.put(detailsKey, corruptStatus.toByteArray()); + mixedTrailers.put( + retryInfoKey, RetryInfo.newBuilder().setRetryDelay(Durations.fromMillis(450L)).build()); + StatusRuntimeException mixedError = + Status.UNAVAILABLE.withDescription("mixed").asRuntimeException(mixedTrailers); + assertEquals(Duration.ofMillis(450), policy.computeNextRetryDelay(mixedError, 1)); + } + + @Test + public void computeAttemptRpcTimeoutHandlesOverflowAndSubMillisecond() { + FakeClock clock = new FakeClock(); + RetrySettings overflowSettings = + RetrySettings.newBuilder() + .setInitialRpcTimeoutDuration(Duration.ofMillis(Long.MAX_VALUE)) + .setRpcTimeoutMultiplier(2.0) + .setMaxRpcTimeoutDuration(Duration.ofSeconds(Long.MAX_VALUE)) + .setTotalTimeoutDuration(Duration.ofMillis(Long.MAX_VALUE)) + .build(); + BatchWriteRetryPolicy overflowPolicy = + new BatchWriteRetryPolicy(overflowSettings, DEFAULT_CODES, clock, () -> 1.0); + Duration overflowTimeout = overflowPolicy.computeAttemptRpcTimeout(1, null, clock.nanoTime()); + assertNotNull(overflowTimeout); + assertTrue(overflowTimeout.toMillis() >= 1L); + + RetrySettings subMsSettings = + RetrySettings.newBuilder() + .setInitialRpcTimeoutDuration(Duration.ofNanos(500_000L)) + .setRpcTimeoutMultiplier(1.0) + .setMaxRpcTimeoutDuration(Duration.ofNanos(500_000L)) + .setTotalTimeoutDuration(Duration.ofNanos(500_000L)) + .build(); + BatchWriteRetryPolicy subMsPolicy = + new BatchWriteRetryPolicy(subMsSettings, DEFAULT_CODES, clock, () -> 1.0); + assertEquals( + Duration.ofMillis(1L), subMsPolicy.computeAttemptRpcTimeout(0, null, clock.nanoTime())); + } + + @Test + public void subMillisecondRetryDelayIsPreservedInDuration() { + FakeClock clock = new FakeClock(); + RetrySettings subMsSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(Duration.ofNanos(1)) + .setMaxRetryDelayDuration(Duration.ofNanos(1)) + .setMaxAttempts(5) + .build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(subMsSettings, DEFAULT_CODES, clock, () -> 1.0); + Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); + assertEquals(Duration.ofNanos(1), policy.computeNextRetryDelay(unavailable, 1)); + RetryDecision decision = policy.evaluate(unavailable, 1, clock.nanoTime(), Context.ROOT, null); + assertEquals(Action.RETRY, decision.action); + assertEquals(Duration.ofNanos(1), decision.delay); + } + + @Test + public void internalExceptionWithNullMessageIsNotRetryable() { + FakeClock clock = new FakeClock(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); + ApiException nullMessageInternal = apiException(Status.Code.INTERNAL, null); + assertFalse(policy.isRetryable(nullMessageInternal)); + } + + @Test + public void evaluateWithMaxAttemptsOneReturnsRetriesExhaustedForRetryableError() { + FakeClock clock = new FakeClock(); + RetrySettings oneAttemptSettings = defaultSettings().toBuilder().setMaxAttempts(1).build(); + BatchWriteRetryPolicy policy = + new BatchWriteRetryPolicy(oneAttemptSettings, DEFAULT_CODES, clock, () -> 1.0); + Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); + RetryDecision decision = policy.evaluate(unavailable, 1, clock.nanoTime(), Context.ROOT, null); + assertEquals(Action.RETRIES_EXHAUSTED, decision.action); + assertEquals(unavailable, decision.terminalError); + + // Non-retryable errors still classify as PERMANENT_FAILURE when maxAttempts == 1. + Throwable invalidArgument = apiException(Status.Code.INVALID_ARGUMENT, "bad"); + RetryDecision permanent = + policy.evaluate(invalidArgument, 1, clock.nanoTime(), Context.ROOT, null); + assertEquals(Action.PERMANENT_FAILURE, permanent.action); + assertEquals(invalidArgument, permanent.terminalError); + } +} diff --git a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java index f5485a9a2404..f1a609b91849 100644 --- a/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java +++ b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/GapicSpannerRpcTest.java @@ -22,6 +22,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; @@ -2809,6 +2810,21 @@ public boolean isEnableGRPCBuiltInMetrics() { } } + @Test + public void testGetFallbackOpenTelemetryReturnsNoopWithNoCredentials() { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("[PROJECT]") + .setCredentials(NoCredentials.getInstance()) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .setEnableDirectAccess(true) + .build(); + GapicSpannerRpc rpc = new GapicSpannerRpc(options, /* initializeStubs= */ false); + + assertSame(OpenTelemetry.noop(), rpc.getFallbackOpenTelemetry(options)); + } + @Test public void testSetEmulatorHostIsDetectedWithoutEnvironmentVariable() throws Exception { SpannerOptions emulatorOptions = @@ -3289,6 +3305,44 @@ public void testFallbackIntegration_switchesToFallbackOnFailure() throws Excepti } } + @Test + public void testShutdownOneOfTwoRpcsDoesNotCloseOptionsBuiltInMetrics() { + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("[PROJECT]") + .setHost("http://localhost:1") + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) + .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) + .setCredentials(STATIC_CREDENTIALS) + .setEmulatorHost(null) + .build(); + GapicSpannerRpc rpc1 = new GapicSpannerRpc(options); + GapicSpannerRpc rpc2 = new GapicSpannerRpc(options); + try { + OpenTelemetry beforeShutdown = options.getBuiltInOpenTelemetry(); + assertNotNull(beforeShutdown); + + rpc2.shutdown(); + + assertSame(beforeShutdown, options.getBuiltInOpenTelemetry()); + + rpc1.shutdown(); + options.getService().close(); + + OpenTelemetry afterSpannerClose = options.getBuiltInOpenTelemetry(); + assertNotNull(afterSpannerClose); + assertNotSame(beforeShutdown, afterSpannerClose); + } finally { + if (!rpc1.isClosed()) { + rpc1.shutdown(); + } + if (!rpc2.isClosed()) { + rpc2.shutdown(); + } + options.getService().close(); + } + } + private boolean hasValue(MetricData metricData) { return metricData.getLongSumData().getPoints().stream().anyMatch(point -> point.getValue() > 0); } diff --git a/java-storage/CHANGELOG.md b/java-storage/CHANGELOG.md index fb2cdeb25758..8f3ec9b0ceb2 100644 --- a/java-storage/CHANGELOG.md +++ b/java-storage/CHANGELOG.md @@ -946,7 +946,7 @@ ### Features -* Adds TPC support ([#2362](https://github.com/googleapis/java-storage/issues/2362)) ([8b636db](https://github.com/googleapis/java-storage/commit/8b636dbe8a16b9b81afbb51b8d0032bcbdbef635)) +* Adds universe domain support ([#2362](https://github.com/googleapis/java-storage/issues/2362)) ([8b636db](https://github.com/googleapis/java-storage/commit/8b636dbe8a16b9b81afbb51b8d0032bcbdbef635)) ### Bug Fixes diff --git a/sdk-platform-java/api-common-java/src/main/java/com/google/api/core/ApiService.java b/sdk-platform-java/api-common-java/src/main/java/com/google/api/core/ApiService.java index cd3545d8b952..c90254d175ed 100644 --- a/sdk-platform-java/api-common-java/src/main/java/com/google/api/core/ApiService.java +++ b/sdk-platform-java/api-common-java/src/main/java/com/google/api/core/ApiService.java @@ -51,10 +51,10 @@ *

    There are deviations from this if there are failures or if {@link ApiService#stopAsync} is * called before the {@link ApiService} reaches the {@linkplain State#RUNNING RUNNING} state. The * set of legal transitions form a DAG, therefore every method of the - * listener will be called at most once. N.B. The {@link State#FAILED} and {@link State#TERMINATED} - * states are terminal states, once a service enters either of these states it cannot ever leave - * them. + * href="https://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG, therefore every method of + * the listener will be called at most once. N.B. The {@link State#FAILED} and {@link + * State#TERMINATED} states are terminal states, once a service enters either of these states it + * cannot ever leave them. * *

    Implementors of this interface are strongly encouraged to extend {@link AbstractApiService} * which implement this interface and make the threading and state management easier. diff --git a/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java b/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java index 8d4080247ec4..ee16539661ac 100644 --- a/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java +++ b/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/GrpcCallContext.java @@ -643,8 +643,8 @@ public Map> getExtraHeaders() { } /** - * This method is obsolete. Use {@link #withTransportChannel()} instead. Returns a new instance - * with the channel set to the given channel. + * This method is obsolete. Use {@link #withTransportChannel(TransportChannel)} instead. Returns a + * new instance with the channel set to the given channel. */ @ObsoleteApi("Use withTransportChannel() instead") public GrpcCallContext withChannel(@Nullable Channel newChannel) { diff --git a/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java b/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java index a74deca6350e..6642a14eea01 100644 --- a/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java +++ b/sdk-platform-java/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java @@ -118,15 +118,13 @@ public final class InstantiatingGrpcChannelProvider implements TransportChannelP // The public portion of the mTLS MDS root certificate is stored for performing // cert verification when establishing an mTLS connection with the MDS. See - // {@link this - // for more information.} + // https://docs.cloud.google.com/compute/docs/metadata/overview#https-mds-root-certs + // for more information. private static final String MTLS_MDS_ROOT_PATH = "/run/google-mds-mtls/root.crt"; // The mTLS MDS credentials are formatted as the concatenation of a PEM-encoded certificate chain // followed by a PEM-encoded private key. See - // {@link this - // for more information.} + // https://docs.cloud.google.com/compute/docs/metadata/overview#https-mds-client-certs + // for more information. private static final String MTLS_MDS_CERT_CHAIN_AND_KEY_PATH = "/run/google-mds-mtls/client.key"; static final long DIRECT_PATH_KEEP_ALIVE_TIME_SECONDS = 3600; @@ -344,7 +342,7 @@ public TransportChannelProvider withEndpoint(String endpoint) { * *

    The value of {@code mtlsEndpoint} must be of the form {@code host:port}. * - * @param mtlsEndpoint The mtTLS endpoint to connect to + * @param mtlsEndpoint The mTLS endpoint to connect to * @return A new {@link InstantiatingGrpcChannelProvider} with the specified mTLS endpoint * configured */ @@ -358,7 +356,7 @@ public TransportChannelProvider withMtlsEndpoint(String mtlsEndpoint) { /** * Specify whether or not to use S2A. * - * @param useS2A + * @param useS2A whether to use S2A for establishing mTLS connections * @return A new {@link InstantiatingGrpcChannelProvider} with useS2A set. */ @Override @@ -648,15 +646,15 @@ boolean canUseDirectPathWithUniverseDomain() { /** * This method creates {@link TlsChannelCredentials} to be used by the client to establish an mTLS - * connection to S2A. Returns null if any of {@param trustBundle}, {@param privateKey} or {@param + * connection to S2A. Returns null if any of {@code trustBundle}, {@code privateKey} or {@code * certChain} are missing. * - * @param trustBundle the trust bundle to be used to establish the client -> S2A mTLS connection - * @param privateKey the client's private key to be used to establish the client -> S2A mtls + * @param trustBundle the trust bundle to be used to establish the client-to-S2A mTLS connection + * @param privateKey the client's private key to be used to establish the client-to-S2A mTLS * connection - * @param certChain the client's cert chain to be used to establish the client -> S2A mtls + * @param certChain the client's cert chain to be used to establish the client-to-S2A mTLS * connection - * @return {@link ChannelCredentials} to use to create an mtls connection between client and S2A + * @return {@link ChannelCredentials} to use to create an mTLS connection between client and S2A * @throws IOException on error */ @VisibleForTesting @@ -673,7 +671,7 @@ boolean canUseDirectPathWithUniverseDomain() { /** * This method creates {@link ChannelCredentials} to be used by client to establish a plaintext - * connection to S2A. if {@param plaintextAddress} is not present, returns null. + * connection to S2A. If {@code plaintextAddress} is not present, returns null. * * @param plaintextAddress the address to reach S2A which accepts plaintext connections * @return {@link ChannelCredentials} to use to create a plaintext connection between client and @@ -687,15 +685,15 @@ boolean canUseDirectPathWithUniverseDomain() { } /** - * This method creates gRPC {@link ChannelCredentials} configured to use S2A to estbalish a mTLS - * connection. First, the address of S2A is discovered by using the {@link S2A} utility to learn - * the {@code mtlsAddress} to reach S2A and the {@code plaintextAddress} to reach S2A. Prefer to - * use the {@code mtlsAddress} address to reach S2A if it is non-empty and the MTLS-MDS - * credentials can successfully be discovered and used to create {@link TlsChannelCredentials}. If - * there is any failure using mTLS-to-S2A, fallback to using a plaintext connection to S2A using - * the {@code plaintextAddress}. If {@code plaintextAddress} is not available, this function - * returns null; in this case S2A will not be used, and a TLS connection to the service will be - * established. + * This method creates gRPC {@link ChannelCredentials} configured to use S2A to establish an mTLS + * connection. First, the address of S2A is discovered by using the {@link SecureSessionAgent} + * utility to learn the {@code mtlsAddress} to reach S2A and the {@code plaintextAddress} to reach + * S2A. Prefer to use the {@code mtlsAddress} address to reach S2A if it is non-empty and the + * MTLS-MDS credentials can successfully be discovered and used to create {@link + * TlsChannelCredentials}. If there is any failure using mTLS-to-S2A, fallback to using a + * plaintext connection to S2A using the {@code plaintextAddress}. If {@code plaintextAddress} is + * not available, this function returns null; in this case S2A will not be used, and a TLS + * connection to the service will be established. * * @return {@link ChannelCredentials} configured to use S2A to create mTLS connection. */ diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java index e53bfcb80755..ea3fea41a791 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStub.java @@ -209,13 +209,14 @@ public static final HttpJsonOperationsStub create(OperationsStubSettings setting public static final HttpJsonOperationsStub create(ClientContext clientContext) throws IOException { - return new HttpJsonOperationsStub(OperationsStubSettings.newBuilder().build(), clientContext); + return new HttpJsonOperationsStub( + OperationsStubSettings.newBuilder((ClientContext) null).build(), clientContext); } public static final HttpJsonOperationsStub create( ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException { return new HttpJsonOperationsStub( - OperationsStubSettings.newBuilder().build(), + OperationsStubSettings.newBuilder((ClientContext) null).build(), clientContext, callableFactory, TypeRegistry.getEmptyTypeRegistry()); @@ -227,7 +228,10 @@ public static final HttpJsonOperationsStub create( TypeRegistry typeRegistry) throws IOException { return new HttpJsonOperationsStub( - OperationsStubSettings.newBuilder().build(), clientContext, callableFactory, typeRegistry); + OperationsStubSettings.newBuilder((ClientContext) null).build(), + clientContext, + callableFactory, + typeRegistry); } public static final HttpJsonOperationsStub create( @@ -237,7 +241,7 @@ public static final HttpJsonOperationsStub create( Map customHttpBindings) throws IOException { return new HttpJsonOperationsStub( - OperationsStubSettings.newBuilder().build(), + OperationsStubSettings.newBuilder((ClientContext) null).build(), clientContext, callableFactory, typeRegistry, diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java index 5122a8d60863..8541913e7929 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettings.java @@ -33,6 +33,7 @@ import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; +import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; @@ -199,12 +200,19 @@ public OperationsStub createStub() throws IOException { "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } + /** Returns the default service name. */ + @Override + public String getServiceName() { + return "longrunning"; + } + /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ + @ObsoleteApi("Use getEndpoint() instead") public static String getDefaultEndpoint() { return "longrunning.googleapis.com:443"; } @@ -249,7 +257,7 @@ public static Builder newBuilder() { } /** Returns a new builder for this class. */ - public static Builder newBuilder(ClientContext clientContext) { + public static Builder newBuilder(@Nullable ClientContext clientContext) { return new Builder(clientContext); } @@ -350,7 +358,6 @@ private static Builder createDefault() { builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); - builder.setEndpoint(getDefaultEndpoint()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStubTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStubTest.java index b2884a9e9435..46946ffee0d5 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStubTest.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/HttpJsonOperationsStubTest.java @@ -177,4 +177,26 @@ void testMethodDescriptorsAdditionalBindings() throws IOException { .toRawString()) .isEqualTo(operationCancelAdditionalBindingURI); } + + @Test + void testCreateWithClientContext_preservesOperationCallables() throws IOException { + HttpJsonOperationsStub stub = + HttpJsonOperationsStub.create( + ClientContext.newBuilder() + .setCredentials(NoCredentialsProvider.create().getCredentials()) + .setDefaultCallContext(FakeCallContext.createDefault()) + .setUniverseDomain("example.com") + .setEndpoint("myservice.example.com:443") + .build()); + try { + assertThat(stub.listOperationsCallable()).isNotNull(); + assertThat(stub.listOperationsPagedCallable()).isNotNull(); + assertThat(stub.getOperationCallable()).isNotNull(); + assertThat(stub.deleteOperationCallable()).isNotNull(); + assertThat(stub.cancelOperationCallable()).isNotNull(); + assertThat(stub.longRunningClient()).isNotNull(); + } finally { + stub.close(); + } + } } diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettingsTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettingsTest.java new file mode 100644 index 000000000000..1880ab03ca23 --- /dev/null +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettingsTest.java @@ -0,0 +1,243 @@ +/* + * Copyright 2026 Google LLC + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google LLC nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.google.api.gax.httpjson.longrunning.stub; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.google.api.client.http.LowLevelHttpRequest; +import com.google.api.client.http.LowLevelHttpResponse; +import com.google.api.client.testing.http.MockHttpTransport; +import com.google.api.client.testing.http.MockLowLevelHttpRequest; +import com.google.api.client.testing.http.MockLowLevelHttpResponse; +import com.google.api.gax.core.FixedCredentialsProvider; +import com.google.api.gax.httpjson.longrunning.OperationsClient; +import com.google.api.gax.httpjson.longrunning.OperationsSettings; +import com.google.api.gax.rpc.ClientContext; +import com.google.api.gax.rpc.StatusCode; +import com.google.api.gax.rpc.UnauthenticatedException; +import com.google.auth.Credentials; +import com.google.longrunning.Operation; +import java.io.IOException; +import java.net.URI; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class OperationsStubSettingsTest { + + private static final String CUSTOM_UNIVERSE_DOMAIN = "example.com"; + + @Test + void defaultEndpoint_usesDefaultUniverseDomain() throws IOException { + OperationsStubSettings stubSettings = OperationsStubSettings.newBuilder().build(); + assertThat(stubSettings.getServiceName()).isEqualTo("longrunning"); + assertThat(stubSettings.getUniverseDomain()).isEqualTo(Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertThat(stubSettings.getEndpoint()).isEqualTo("longrunning.googleapis.com:443"); + + OperationsSettings clientSettings = OperationsSettings.newBuilder().build(); + assertThat(clientSettings.getUniverseDomain()).isEqualTo(Credentials.GOOGLE_DEFAULT_UNIVERSE); + assertThat(clientSettings.getEndpoint()).isEqualTo("longrunning.googleapis.com:443"); + } + + @Test + void customUniverseDomain_resolvesEndpointDynamically() throws IOException { + OperationsStubSettings stubSettings = + OperationsStubSettings.newBuilder().setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN).build(); + assertThat(stubSettings.getUniverseDomain()).isEqualTo(CUSTOM_UNIVERSE_DOMAIN); + assertThat(stubSettings.getEndpoint()).isEqualTo("longrunning.example.com:443"); + + OperationsSettings clientSettings = + OperationsSettings.newBuilder().setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN).build(); + assertThat(clientSettings.getUniverseDomain()).isEqualTo(CUSTOM_UNIVERSE_DOMAIN); + assertThat(clientSettings.getEndpoint()).isEqualTo("longrunning.example.com:443"); + } + + @Test + void customUniverseDomainAndExplicitEndpoint_preservesExplicitEndpoint() throws IOException { + String explicitEndpoint = "myservice.example.com:443"; + OperationsStubSettings settings = + OperationsStubSettings.newBuilder() + .setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN) + .setEndpoint(explicitEndpoint) + .build(); + assertThat(settings.getUniverseDomain()).isEqualTo(CUSTOM_UNIVERSE_DOMAIN); + assertThat(settings.getEndpoint()).isEqualTo(explicitEndpoint); + } + + @Test + void toBuilder_recomputesDefaultEndpointWhenUniverseDomainChanges() throws IOException { + OperationsStubSettings defaultSettings = OperationsStubSettings.newBuilder().build(); + OperationsStubSettings customSettings = + defaultSettings.toBuilder().setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN).build(); + assertThat(customSettings.getEndpoint()).isEqualTo("longrunning.example.com:443"); + + String explicitEndpoint = "myservice.example.com:443"; + OperationsStubSettings explicitSettings = + OperationsStubSettings.newBuilder().setEndpoint(explicitEndpoint).build(); + OperationsStubSettings updatedExplicitSettings = + explicitSettings.toBuilder().setUniverseDomain("other.example.com").build(); + assertThat(updatedExplicitSettings.getEndpoint()).isEqualTo(explicitEndpoint); + } + + @Test + void standaloneOperationsClient_customUniverseDomain_routesRequestToCustomUniverse() + throws IOException { + AtomicReference capturedUrl = new AtomicReference<>(); + MockHttpTransport mockTransport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + capturedUrl.set(url); + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() { + MockLowLevelHttpResponse response = new MockLowLevelHttpResponse(); + response.setStatusCode(200); + response.setContentType("application/json; charset=UTF-8"); + response.setContent("{\"name\":\"operations/test-op\",\"done\":true}"); + return response; + } + }; + } + }; + + OperationsSettings settings = + OperationsSettings.newBuilder() + .setUniverseDomain(CUSTOM_UNIVERSE_DOMAIN) + .setCredentialsProvider( + FixedCredentialsProvider.create( + new UniverseDomainCredentials(CUSTOM_UNIVERSE_DOMAIN))) + .setTransportChannelProvider( + OperationsSettings.defaultHttpJsonTransportProviderBuilder() + .setHttpTransport(mockTransport) + .build()) + .build(); + + try (OperationsClient client = OperationsClient.create(settings)) { + Operation operation = client.getOperation("operations/test-op"); + assertThat(operation.getName()).isEqualTo("operations/test-op"); + assertThat(operation.getDone()).isTrue(); + } + + assertThat(capturedUrl.get()).startsWith("https://longrunning.example.com:443/"); + assertThat(capturedUrl.get()).doesNotContain("googleapis.com"); + } + + @Test + void standaloneOperationsClient_universeDomainMismatch_throwsBeforeSendingRequest() + throws IOException { + AtomicInteger requestCount = new AtomicInteger(); + MockHttpTransport mockTransport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + requestCount.incrementAndGet(); + return new MockLowLevelHttpRequest(); + } + }; + + OperationsSettings settings = + OperationsSettings.newBuilder() + .setCredentialsProvider( + FixedCredentialsProvider.create( + new UniverseDomainCredentials(CUSTOM_UNIVERSE_DOMAIN))) + .setTransportChannelProvider( + OperationsSettings.defaultHttpJsonTransportProviderBuilder() + .setHttpTransport(mockTransport) + .build()) + .build(); + + try (OperationsClient client = OperationsClient.create(settings)) { + assertThrows(UnauthenticatedException.class, () -> client.getOperation("operations/test-op")); + } + + assertThat(requestCount.get()).isEqualTo(0); + } + + @Test + void newBuilderWithNullClientContext_initializesRetryDefaultsWithoutMtlsEndpoint() + throws IOException { + OperationsStubSettings settings = + OperationsStubSettings.newBuilder((ClientContext) null).build(); + assertThat(settings.getMtlsEndpoint()).isNull(); + assertThat(settings.listOperationsSettings().getRetryableCodes()) + .containsExactly(StatusCode.Code.UNAVAILABLE); + assertThat(settings.getOperationSettings().getRetryableCodes()) + .containsExactly(StatusCode.Code.UNAVAILABLE); + assertThat(settings.deleteOperationSettings().getRetryableCodes()) + .containsExactly(StatusCode.Code.UNAVAILABLE); + assertThat(settings.cancelOperationSettings().getRetryableCodes()) + .containsExactly(StatusCode.Code.UNAVAILABLE); + assertThat(settings.getOperationSettings().getRetrySettings().getTotalTimeoutDuration()) + .isEqualTo(Duration.ofMillis(10000L)); + } + + private static final class UniverseDomainCredentials extends Credentials { + private final String universeDomain; + + private UniverseDomainCredentials(String universeDomain) { + this.universeDomain = universeDomain; + } + + @Override + public String getAuthenticationType() { + return "OAuth2"; + } + + @Override + public Map> getRequestMetadata(URI uri) { + return Collections.singletonMap( + "Authorization", Collections.singletonList("Bearer test-token-value")); + } + + @Override + public boolean hasRequestMetadata() { + return true; + } + + @Override + public boolean hasRequestMetadataOnly() { + return true; + } + + @Override + public void refresh() {} + + @Override + public String getUniverseDomain() { + return universeDomain; + } + } +} diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/core/GoogleCredentialsProvider.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/core/GoogleCredentialsProvider.java index c471b74e0d3f..7315c56f1c04 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/core/GoogleCredentialsProvider.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/core/GoogleCredentialsProvider.java @@ -46,8 +46,8 @@ * GoogleCredentialsProvider acquires credentials using Application Default Credentials. * *

    For more information on Application Default Credentials, see - * https://developers.google.com/identity/protocols/application-default-credentials. + * href="https://docs.cloud.google.com/docs/authentication/application-default-credentials"> + * Application Default Credentials. */ @NullMarked @AutoValue diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiStreamObserver.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiStreamObserver.java index 776be7412634..d5c72bc4a385 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiStreamObserver.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ApiStreamObserver.java @@ -42,12 +42,11 @@ * implements the {@code ApiStreamObserver} and passes it to GAX, which then calls the observer with * the messages for the application to receive them. * - *

    Implementations are expected to be thread-compatible. Separate - * {@code ApiStreamObserver}s do not need to be synchronized together; incoming and outgoing - * directions are independent. Since individual {@code ApiStreamObserver}s are not thread-safe, if - * multiple threads will be writing to a {@code ApiStreamObserver} concurrently, the application - * must synchronize calls. + *

    Implementations are expected to be thread-compatible (safe to use across threads only with + * external synchronization). Separate {@code ApiStreamObserver}s do not need to be synchronized + * together; incoming and outgoing directions are independent. Since individual {@code + * ApiStreamObserver}s are not thread-safe, if multiple threads will be writing to a {@code + * ApiStreamObserver} concurrently, the application must synchronize calls. * *

    This interface is a fork of io.grpc.stub.StreamObserver to enable shadowing of Guava, and also * to allow for a transport-agnostic interface that doesn't depend on gRPC. diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java index 79cea1dba7d9..b80a8292c4a7 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientContext.java @@ -193,7 +193,15 @@ public static ClientContext create(StubSettings settings) throws IOException { "GDC-H API audience can only be set when using GdchCredentials"); } - if (settings.getQuotaProjectId() != null && credentials != null) { + // ApiKeyCredentials never emits x-goog-user-project, so wrapping it in + // QuotaProjectIdHidingCredentials is unnecessary and would hide its type from downstream + // instanceof checks (EndpointContext universe domain validation and + // InstantiatingGrpcChannelProvider duplicate header removal). We also do not reject setting + // quotaProjectId alongside ApiKeyCredentials because resource-based APIs ignore + // x-goog-user-project rather than rejecting it. + if (settings.getQuotaProjectId() != null + && credentials != null + && !(credentials instanceof ApiKeyCredentials)) { // If the quotaProjectId is set, wrap original credentials with correct // quotaProjectId as // QuotaProjectIdHidingCredentials. diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java index 371749972ac1..5f60bcb45a5a 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/ClientSettings.java @@ -316,6 +316,13 @@ public B setGdchApiAudience(@Nullable String gdchApiAudience) { *

    API Key authorization is not supported for every product. Please check the documentation * for each product to confirm if it is supported. * + *

    WARNING: API keys do not carry universe domain metadata and are not + * validated against the client's configured universe domain or endpoint. If no universe + * domain is configured on the client (or via {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN}), requests + * default to {@code googleapis.com}. Callers are solely responsible for ensuring the API key + * matches the configured universe domain, as the client will not prevent sending an API key + * to an unintended universe domain. + * *

    Note: If you set an API key and {@link CredentialsProvider} in the same ClientSettings the * API key will override any credentials provided. */ diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/EndpointContext.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/EndpointContext.java index 725aba5c5314..f36dc527af96 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/EndpointContext.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/EndpointContext.java @@ -32,6 +32,7 @@ import com.google.api.core.InternalApi; import com.google.api.gax.rpc.internal.EnvironmentProvider; import com.google.api.gax.rpc.mtls.CertificateBasedAccess; +import com.google.auth.ApiKeyCredentials; import com.google.auth.Credentials; import com.google.auth.mtls.CertificateSourceUnavailableException; import com.google.auth.mtls.MtlsProvider; @@ -88,17 +89,17 @@ public static EndpointContext getDefaultInstance() { } /** - * ServiceName is host URI for Google Cloud Services. It follows the format of - * `{ServiceName}.googleapis.com`. For example, speech.googleapis.com would have a ServiceName of + * ServiceName is host URI for Google Cloud Services. It follows the format of {@code + * {ServiceName}.googleapis.com}. For example, speech.googleapis.com would have a ServiceName of * speech and cloudasset.googleapis.com would have a ServiceName of cloudasset. */ public abstract @Nullable String serviceName(); /** - * Universe Domain is the domain for Google Cloud Services. It follows the format of - * `{ServiceName}.{UniverseDomain}`. For example, speech.googleapis.com would have a Universe - * Domain value of `googleapis.com` and cloudasset.test.com would have a Universe Domain of - * `test.com`. If this value is not set, this will default to `googleapis.com`. + * Universe Domain is the domain for Google Cloud Services. It follows the format of {@code + * {ServiceName}.{UniverseDomain}}. For example, speech.googleapis.com would have a Universe + * Domain value of {@code googleapis.com} and cloudasset.test.com would have a Universe Domain of + * {@code test.com}. If this value is not set, this will default to {@code googleapis.com}. */ public abstract @Nullable String universeDomain(); @@ -163,6 +164,9 @@ EndpointContext withGDCH() throws IOException { * implementation of the StatusCode). This method is scoped to be internal and should be not be * accessed by users. * + *

    Universe domain validation is skipped for {@link ApiKeyCredentials} because API keys do not + * carry universe domain metadata and are expected to match the configured universe domain. + * * @param credentials Auth Library Credentials * @param invalidUniverseDomainStatusCode Transport-specific Status Code to be returned if the * Universe Domain is invalid. For both transports, this is defined to be Unauthorized. @@ -176,6 +180,12 @@ public void validateUniverseDomain( // GDC-H has no universe domain, return return; } + // Client-side universe domain configuration is already validated in Builder#build(). + // API keys carry no universe domain metadata, so callers are responsible for ensuring the + // API key belongs to the configured universe domain. + if (credentials instanceof ApiKeyCredentials) { + return; + } // (TODO: b/349488459) - Disable automatic requests to MDS until 01/2025 // If MDS is required for Universe Domain, do not do any validation if (credentials instanceof ComputeEngineCredentials) { @@ -201,17 +211,17 @@ public void validateUniverseDomain( @AutoValue.Builder public abstract static class Builder { /** - * ServiceName is host URI for Google Cloud Services. It follows the format of - * `{ServiceName}.googleapis.com`. For example, speech.googleapis.com would have a ServiceName - * of speech and cloudasset.googleapis.com would have a ServiceName of cloudasset. + * ServiceName is host URI for Google Cloud Services. It follows the format of {@code + * {ServiceName}.googleapis.com}. For example, speech.googleapis.com would have a ServiceName of + * speech and cloudasset.googleapis.com would have a ServiceName of cloudasset. */ public abstract Builder setServiceName(String serviceName); /** - * Universe Domain is the domain for Google Cloud Services. It follows the format of - * `{ServiceName}.{UniverseDomain}`. For example, speech.googleapis.com would have a Universe - * Domain value of `googleapis.com` and cloudasset.test.com would have a Universe Domain of - * `test.com`. If this value is not set, this will default to `googleapis.com`. + * Universe Domain is the domain for Google Cloud Services. It follows the format of {@code + * {ServiceName}.{UniverseDomain}}. For example, speech.googleapis.com would have a Universe + * Domain value of {@code googleapis.com} and cloudasset.test.com would have a Universe Domain + * of {@code test.com}. If this value is not set, this will default to {@code googleapis.com}. */ public abstract Builder setUniverseDomain(String universeDomain); diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StatusCode.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StatusCode.java index 7e946f6a08bb..83483237fc7a 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StatusCode.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StatusCode.java @@ -35,9 +35,8 @@ /** * Transport-specific status code. * - *

    The status codes are modeled after the status codes in grpc. For more information about grpc - * status codes, see - * https://github.com/grpc/grpc-java/blob/master/core/src/main/java/io/grpc/Status.java + *

    The status codes are modeled after the status codes in gRPC. For more information about gRPC + * status codes, see gRPC status codes. */ @NullMarked @InternalExtensionOnly diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java index 0c57740b86fd..5d177ebead5c 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/StubSettings.java @@ -607,6 +607,13 @@ public B setTracerFactory(ApiTracerFactory tracerFactory) { *

    API Key authorization is not supported for every product. Please check the documentation * for each product to confirm if it is supported. * + *

    WARNING: API keys do not carry universe domain metadata and are not + * validated against the client's configured universe domain or endpoint. If no universe + * domain is configured on the client (or via {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN}), requests + * default to {@code googleapis.com}. Callers are solely responsible for ensuring the API key + * matches the configured universe domain, as the client will not prevent sending an API key + * to an unintended universe domain. + * *

    Note: If you set an API key and {@link CredentialsProvider} in the same ClientSettings the * API key will override any credentials provided. */ @@ -664,11 +671,11 @@ public final String getApiKey() { } /** - * @return the resolved endpoint when the Builder was created. If invoked after - * `StubSettings.newBuilder()` is called, it will return the clientSettingsEndpoint value. - * If other parameters are then set in the builder, the resolved endpoint is not - * automatically updated. The resolved endpoint will only be recomputed when the - * StubSettings is built again. + * @return the resolved endpoint when the Builder was created. If invoked after {@code + * StubSettings.newBuilder()} is called, it will return the clientSettingsEndpoint value. If + * other parameters are then set in the builder, the resolved endpoint is not automatically + * updated. The resolved endpoint will only be recomputed when the StubSettings is built + * again. */ public String getEndpoint() { // For the `StubSettings.newBuilder()` case diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/mtls/MtlsProvider.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/mtls/MtlsProvider.java index 26afbc83ab80..d82d3037ad7c 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/mtls/MtlsProvider.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/mtls/MtlsProvider.java @@ -182,7 +182,7 @@ static int runCertificateProviderCommand(Process commandProcess, long timeoutMil // exitValue throws IllegalThreadStateException if process has not yet terminated. // Once the process is terminated, exitValue no longer throws exception. Therefore // in the while loop, we use exitValue to check if process is terminated. See - // https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#exitValue() + // https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#exitValue-- // for more details. } } diff --git a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryMetricsRecorder.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryMetricsRecorder.java index 3cd9ba53b523..aa878137bb7f 100644 --- a/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryMetricsRecorder.java +++ b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/tracing/OpenTelemetryMetricsRecorder.java @@ -44,13 +44,13 @@ import org.jspecify.annotations.NullMarked; /** - * OpenTelemetry implementation of recording metrics. This implementation collections the - * measurements related to the lifecyle of an RPC. + * OpenTelemetry implementation of recording metrics. This implementation collects the measurements + * related to the lifecycle of an RPC. * - *

    For the Otel implementation, an attempt is a single RPC invocation and an operation is the + *

    For the OTel implementation, an attempt is a single RPC invocation and an operation is the * collection of all the attempts made before a response is returned (either as a success or an - * error). A single call (i.e. `EchoClient.echo()`) should have an operation_count of 1 and may have - * an attempt_count of 1+ (depending on the retry configurations). + * error). A single call (e.g., {@code EchoClient.echo()}) should have an operation_count of 1 and + * may have an attempt_count of 1+ (depending on the retry configurations). */ @NullMarked @BetaApi diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java index 12d81f3675b5..a1ce29803c48 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/retrying/ScheduledRetryingExecutorTest.java @@ -182,6 +182,10 @@ void testSuccessWithFailuresGetAttempt() throws Exception { assertFalse(future.getAttemptResult().isDone()); assertFalse(future.getAttemptResult().isCancelled()); + // Capture the first attempt's future before submitting so the test deterministically + // observes at least one failed intermediate attempt even when RecordingScheduler runs all + // retries immediately with zero delay. + Future attemptResult = future.getAttemptResult(); future.setAttemptFuture(executor.submit(future)); CustomException exception; @@ -189,7 +193,9 @@ void testSuccessWithFailuresGetAttempt() throws Exception { do { exception = null; checks++; - Future attemptResult = future.getAttemptResult(); + if (checks > 1) { + attemptResult = future.getAttemptResult(); + } try { // testing that the gotten attempt result is non-cancelable assertFalse(attemptResult.cancel(false)); diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java index ffc380e39284..e97928d75fc6 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/ClientContextTest.java @@ -31,6 +31,7 @@ import static com.google.api.gax.util.TimeConversionTestUtils.testDurationMethod; import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -1306,6 +1307,115 @@ void testSetApiKey_withDefaultCredentials_overridesCredentials() throws IOExcept assertThat(fakeCallContext.getCredentials()).isInstanceOf(ApiKeyCredentials.class); } + @Test + void testSetApiKey_withCustomUniverseDomain_skipsUniverseDomainValidation() throws IOException { + FakeStubSettings.Builder builder = new FakeStubSettings.Builder(); + InterceptingExecutor executor = new InterceptingExecutor(1); + FakeTransportChannel transportChannel = FakeTransportChannel.create(new FakeChannel()); + FakeTransportProvider transportProvider = + new FakeTransportProvider( + transportChannel, + executor, + true, + ImmutableMap.of(), + null, + DEFAULT_ENDPOINT, + DEFAULT_MTLS_ENDPOINT); + builder.setTransportChannelProvider(transportProvider); + HeaderProvider headerProvider = + mock(HeaderProvider.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(headerProvider.getHeaders()).thenReturn(ImmutableMap.of()); + builder.setHeaderProvider(headerProvider); + builder.setApiKey("test-api-key"); + builder.setUniverseDomain("test.com"); + + ClientContext context = ClientContext.create(builder.build()); + + FakeCallContext fakeCallContext = (FakeCallContext) context.getDefaultCallContext(); + assertThat(fakeCallContext.getCredentials()).isInstanceOf(ApiKeyCredentials.class); + StatusCode statusCode = mock(StatusCode.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(statusCode.getCode()).thenReturn(StatusCode.Code.UNAUTHENTICATED); + assertDoesNotThrow( + () -> + context + .getEndpointContext() + .validateUniverseDomain(fakeCallContext.getCredentials(), statusCode)); + } + + @Test + void testSetApiKey_withQuotaProjectIdAndCustomUniverseDomain_doesNotWrapCredentials() + throws IOException { + FakeStubSettings.Builder builder = new FakeStubSettings.Builder(); + InterceptingExecutor executor = new InterceptingExecutor(1); + FakeTransportChannel transportChannel = FakeTransportChannel.create(new FakeChannel()); + FakeTransportProvider transportProvider = + new FakeTransportProvider( + transportChannel, executor, true, null, null, DEFAULT_ENDPOINT, DEFAULT_MTLS_ENDPOINT); + builder.setTransportChannelProvider(transportProvider); + HeaderProvider headerProvider = + mock(HeaderProvider.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(headerProvider.getHeaders()).thenReturn(ImmutableMap.of()); + builder.setHeaderProvider(headerProvider); + builder.setApiKey("test-api-key"); + builder.setQuotaProjectId("quota-project"); + builder.setUniverseDomain("test.com"); + + ClientContext context = ClientContext.create(builder.build()); + + FakeCallContext fakeCallContext = (FakeCallContext) context.getDefaultCallContext(); + assertThat(context.getCredentials()).isInstanceOf(ApiKeyCredentials.class); + assertThat(fakeCallContext.getCredentials()).isInstanceOf(ApiKeyCredentials.class); + assertThat(context.getQuotaProjectId()).isEqualTo("quota-project"); + assertThat(transportChannel.getHeaders()).containsEntry("x-goog-user-project", "quota-project"); + StatusCode statusCode = mock(StatusCode.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(statusCode.getCode()).thenReturn(StatusCode.Code.UNAUTHENTICATED); + assertDoesNotThrow( + () -> + context + .getEndpointContext() + .validateUniverseDomain(fakeCallContext.getCredentials(), statusCode)); + } + + @Test + void + testSetApiKeyCredentialsProvider_withQuotaProjectIdAndCustomUniverseDomain_doesNotWrapCredentials() + throws IOException { + FakeStubSettings.Builder builder = new FakeStubSettings.Builder(); + InterceptingExecutor executor = new InterceptingExecutor(1); + FakeTransportChannel transportChannel = FakeTransportChannel.create(new FakeChannel()); + FakeTransportProvider transportProvider = + new FakeTransportProvider( + transportChannel, + executor, + true, + ImmutableMap.of(), + null, + DEFAULT_ENDPOINT, + DEFAULT_MTLS_ENDPOINT); + builder.setTransportChannelProvider(transportProvider); + HeaderProvider headerProvider = + mock(HeaderProvider.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(headerProvider.getHeaders()).thenReturn(ImmutableMap.of()); + builder.setHeaderProvider(headerProvider); + builder.setCredentialsProvider( + FixedCredentialsProvider.create(ApiKeyCredentials.create("test-api-key"))); + builder.setQuotaProjectId("quota-project"); + builder.setUniverseDomain("test.com"); + + ClientContext context = ClientContext.create(builder.build()); + + FakeCallContext fakeCallContext = (FakeCallContext) context.getDefaultCallContext(); + assertThat(context.getCredentials()).isInstanceOf(ApiKeyCredentials.class); + assertThat(fakeCallContext.getCredentials()).isInstanceOf(ApiKeyCredentials.class); + StatusCode statusCode = mock(StatusCode.class, Mockito.withSettings().withoutAnnotations()); + Mockito.when(statusCode.getCode()).thenReturn(StatusCode.Code.UNAUTHENTICATED); + assertDoesNotThrow( + () -> + context + .getEndpointContext() + .validateUniverseDomain(fakeCallContext.getCredentials(), statusCode)); + } + // This test case is added to cover a special case with BigTable. BigTable's EnhancedStubSettings // wrappers do not directly inherit from the generated StubSettings. The wrappers must directly // set the endpoint values since they are set in the generated StubSettings. This test case mimics diff --git a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/EndpointContextTest.java b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/EndpointContextTest.java index 7abd207043ec..5b97213c7aa2 100644 --- a/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/EndpointContextTest.java +++ b/sdk-platform-java/gax-java/gax/src/test/java/com/google/api/gax/rpc/EndpointContextTest.java @@ -37,6 +37,7 @@ import com.google.api.gax.rpc.internal.EnvironmentProvider; import com.google.api.gax.rpc.mtls.CertificateBasedAccess; import com.google.api.gax.rpc.testing.FakeMtlsProvider; +import com.google.auth.ApiKeyCredentials; import com.google.auth.Credentials; import com.google.auth.mtls.CertificateSourceUnavailableException; import com.google.auth.mtls.MtlsProvider; @@ -492,6 +493,19 @@ void hasValidUniverseDomain_computeEngineCredentials_noValidationOnUniverseDomai assertDoesNotThrow(() -> endpointContext.validateUniverseDomain(credentials, statusCode)); } + @Test + void hasValidUniverseDomain_apiKeyCredentials_skipsValidation() throws IOException { + Credentials apiKeyCredentials = ApiKeyCredentials.create("test-api-key"); + EndpointContext defaultEndpointContext = defaultEndpointContextBuilder.build(); + EndpointContext customEndpointContext = + defaultEndpointContextBuilder.setUniverseDomain("test.com").build(); + + assertDoesNotThrow( + () -> defaultEndpointContext.validateUniverseDomain(apiKeyCredentials, statusCode)); + assertDoesNotThrow( + () -> customEndpointContext.validateUniverseDomain(apiKeyCredentials, statusCode)); + } + @Test void shouldUseS2A_envVarNotSet_returnsFalse() throws IOException { EnvironmentProvider envProvider = diff --git a/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java b/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java index d204381b1f87..34e5aacdd090 100644 --- a/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core-http/src/main/java/com/google/cloud/http/HttpTransportOptions.java @@ -32,6 +32,7 @@ import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.UnauthenticatedException; +import com.google.auth.ApiKeyCredentials; import com.google.auth.Credentials; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.http.HttpTransportFactory; @@ -177,19 +178,22 @@ private String determineUniverseDomain() { return universeDomain == null ? Credentials.GOOGLE_DEFAULT_UNIVERSE : universeDomain; } - @Override - public void initialize(HttpRequest httpRequest) throws IOException { - String configuredUniverseDomain = determineUniverseDomain(); + private void validateUniverseDomain() throws IOException { // Default to the GDU. Override with value in the Credentials if needed String credentialsUniverseDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE; // delegate is always HttpCredentialsAdapter or null (NoCredentials) if (delegate != null) { - HttpCredentialsAdapter httpCredentialsAdapter = (HttpCredentialsAdapter) delegate; - credentialsUniverseDomain = httpCredentialsAdapter.getCredentials().getUniverseDomain(); + Credentials credentials = ((HttpCredentialsAdapter) delegate).getCredentials(); + // API keys carry no universe domain metadata. Callers are responsible for ensuring the + // API key belongs to the configured universe domain. + if (credentials instanceof ApiKeyCredentials) { + return; + } + credentialsUniverseDomain = credentials.getUniverseDomain(); } - // Validate the universe domain before initializing the request + String configuredUniverseDomain = determineUniverseDomain(); if (!configuredUniverseDomain.equals(credentialsUniverseDomain)) { throw new UnauthenticatedException( new Throwable( @@ -200,6 +204,11 @@ public void initialize(HttpRequest httpRequest) throws IOException { HttpJsonStatusCode.of(StatusCode.Code.UNAUTHENTICATED), false); } + } + + @Override + public void initialize(HttpRequest httpRequest) throws IOException { + validateUniverseDomain(); if (delegate != null) { delegate.initialize(httpRequest); diff --git a/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java index 1697a0c43f41..2a2435610266 100644 --- a/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core-http/src/test/java/com/google/cloud/http/HttpTransportOptionsTest.java @@ -33,6 +33,7 @@ import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.UnauthenticatedException; +import com.google.auth.ApiKeyCredentials; import com.google.auth.Credentials; import com.google.auth.http.HttpTransportFactory; import com.google.cloud.BaseService; @@ -223,6 +224,21 @@ void testHttpRequestInitializer_customUniverseDomainSettings_noCredentials() { exception.getCause().getMessage()); } + @Test + void testHttpRequestInitializer_customUniverseDomainSettings_apiKeyCredentials() + throws IOException { + ApiKeyCredentials apiKeyCredentials = ApiKeyCredentials.create("test-api-key"); + TestServiceOptions testServiceOptions = + generateTestServiceOptions(CUSTOM_UNIVERSE_DOMAIN, apiKeyCredentials); + HttpRequestInitializer httpRequestInitializer = + DEFAULT_OPTIONS.getHttpRequestInitializer(testServiceOptions); + // Does not throw a validation exception + httpRequestInitializer.initialize(defaultHttpRequest); + assertEquals( + "test-api-key", + defaultHttpRequest.getHeaders().getFirstHeaderStringValue("x-goog-api-key")); + } + private TestServiceOptions generateTestServiceOptions( String universeDomain, Credentials credentials) { return TestServiceOptions.newBuilder() diff --git a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index 4ce8cdf275f3..9d59ca11a5bf 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -42,6 +42,7 @@ import com.google.api.gax.rpc.NoHeaderProvider; import com.google.api.gax.tracing.ApiTracer; import com.google.api.gax.tracing.ApiTracerFactory; +import com.google.auth.ApiKeyCredentials; import com.google.auth.Credentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.QuotaProjectIdProvider; @@ -909,12 +910,22 @@ public String getResolvedApiaryHost(String serviceName) { * this is only intended for BigQuery and Storage Apiary Wrapped Libraries. * *

    This validation call should be made prior to any RPC invocation. This call is used to gate - * the RPC invocation if there is no valid universe domain. + * the RPC invocation if there is no valid universe domain. Validation is skipped for {@link + * ApiKeyCredentials} because API keys do not carry universe domain metadata. */ @InternalApi public boolean hasValidUniverseDomain() throws IOException { + Credentials credentials = getCredentials(); + // API keys carry no universe domain metadata. Callers are responsible for ensuring the API key + // belongs to the configured universe domain. + if (credentials instanceof ApiKeyCredentials) { + return true; + } String resolvedUniverseDomain = universeDomain != null ? universeDomain : Credentials.GOOGLE_DEFAULT_UNIVERSE; - return resolvedUniverseDomain.equals(getCredentials().getUniverseDomain()); + // Fall back to GDU when credentials are null to match EndpointContext and HttpTransportOptions. + String credentialsUniverseDomain = + credentials != null ? credentials.getUniverseDomain() : Credentials.GOOGLE_DEFAULT_UNIVERSE; + return resolvedUniverseDomain.equals(credentialsUniverseDomain); } } diff --git a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index 3c11ba0eeefa..1f4b41f1a117 100644 --- a/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/sdk-platform-java/java-core/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -37,6 +37,7 @@ import com.google.api.client.testing.http.MockLowLevelHttpResponse; import com.google.api.core.ApiClock; import com.google.api.core.CurrentMillisClock; +import com.google.auth.ApiKeyCredentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.spi.ServiceRpcFactory; @@ -285,7 +286,7 @@ protected TestServiceOptions build() { } } - private TestServiceOptions(Builder builder) { + TestServiceOptions(Builder builder) { super( TestServiceFactory.class, TestServiceRpcFactory.class, @@ -630,6 +631,57 @@ void testIsValidUniverseDomain_userUniverseDomainConfig_nonGDUCredentials() thro assertThat(options.hasValidUniverseDomain()).isTrue(); } + @Test + void testIsValidUniverseDomain_apiKeyCredentials_skipsValidation() throws IOException { + ApiKeyCredentials apiKeyCredentials = ApiKeyCredentials.create("test-api-key"); + TestServiceOptions defaultOptions = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://test.googleapis.com") + .setCredentials(apiKeyCredentials) + .build(); + TestServiceOptions customOptions = + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://test.random.com") + .setUniverseDomain("random.com") + .setCredentials(apiKeyCredentials) + .build(); + + assertThat(defaultOptions.hasValidUniverseDomain()).isTrue(); + assertThat(customOptions.hasValidUniverseDomain()).isTrue(); + } + + @Test + void testIsValidUniverseDomain_nullCredentials_defaultsToGdu() throws IOException { + TestServiceOptions defaultOptions = + new TestServiceOptions( + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://test.googleapis.com") + .setCredentials(NoCredentials.getInstance())) { + @Override + public com.google.auth.Credentials getCredentials() { + return null; + } + }; + TestServiceOptions customOptions = + new TestServiceOptions( + TestServiceOptions.newBuilder() + .setProjectId("project-id") + .setHost("https://test.random.com") + .setUniverseDomain("random.com") + .setCredentials(NoCredentials.getInstance())) { + @Override + public com.google.auth.Credentials getCredentials() { + return null; + } + }; + + assertThat(defaultOptions.hasValidUniverseDomain()).isTrue(); + assertThat(customOptions.hasValidUniverseDomain()).isFalse(); + } + @Test void testGetScopedCredentials_useJwtAccessWithScope_enablesByDefault() { TestServiceOptions options = diff --git a/sdk-platform-java/java-shared-dependencies/upper-bound-check/pom.xml b/sdk-platform-java/java-shared-dependencies/upper-bound-check/pom.xml index bae591408606..3017299c06d6 100644 --- a/sdk-platform-java/java-shared-dependencies/upper-bound-check/pom.xml +++ b/sdk-platform-java/java-shared-dependencies/upper-bound-check/pom.xml @@ -22,6 +22,7 @@ UTF-8 ${project.artifactId} + true