From 36bb13237a5107a6dba5994ef32ec7289767e5fe Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 09:45:41 -0500 Subject: [PATCH 01/57] docs(logging): fix property key, copy-pasted Javadocs, and typos in LoggingHandler and LoggingLevel (#15156) Fixes factual Javadoc errors and typos in `LoggingHandler`, `LoggingLevel`, and `LoggingConfig` (documentation-only change with no behavioral or API signature changes): - `LoggingHandler.java`: - Fixes the wrong `logging.properties` key `com.google.cloud.logging.Synchronicity` to `com.google.cloud.logging.LoggingHandler.synchronicity` (matching the property actually read by `LoggingConfig`). - Fixes copy-pasted `getSynchronicity()` Javadoc (`"Get the flush log level."` -> returns write synchronicity). - Removes broken `{@link LoggingConfig}` reference to a package-private class and fixes missing spaces before `{@link LogEntry}`. - Converts the single-star `/*` deprecation comment on `getRedirectToStdout()` to Javadoc `/**` and documents `getLogTarget()`. - Clarifies `addHandler(Logger, LoggingHandler)` accurately as a convenience wrapper over `Logger#addHandler(Handler)`. - `LoggingLevel.java`: fixes broken `{@code ALL < DEBUG < FINES}T` and typo `levet`. - `LoggingConfig.java`: fixes wrong package name `com.google.cloud.logging.context.ContextHandler` to `com.google.cloud.logging.ContextHandler`. ### Verification - `fmt:check` (`google-java-format`): passed. - JDK 25 `mvn -f java-logging/google-cloud-logging/pom.xml -Dlint checkstyle:check@checkstyle test-compile javadoc:javadoc`: passed (0 Checkstyle violations, 0 Javadoc errors). --- .../google/cloud/logging/LoggingConfig.java | 4 +-- .../google/cloud/logging/LoggingHandler.java | 35 +++++++++++-------- .../google/cloud/logging/LoggingLevel.java | 4 +-- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java index b53f6ed84a43..f85ffc4f7c2a 100644 --- a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java +++ b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingConfig.java @@ -119,8 +119,8 @@ List getEnhancers() { /** * Returns boolean value of the property {@code - * com.google.cloud.logging.context.ContextHandler.useInheritedContext}. If no value is defined or - * the property does not represent a valid boolean value returns {@code false}. + * com.google.cloud.logging.ContextHandler.useInheritedContext}. If no value is defined or the + * property does not represent a valid boolean value returns {@code false}. * * @return {@code true} or {@code false} */ diff --git a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java index d1e56762ac10..278adbfbb138 100644 --- a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java +++ b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java @@ -108,8 +108,9 @@ *
  • {@code com.google.cloud.logging.LoggingHandler.resourceType} the type name to use when * creating the default {@link MonitoredResource} (defaults to auto-detected resource type, * else "global"). - *
  • {@code com.google.cloud.logging.Synchronicity} the synchronicity of the write method to use - * to write logs to the Cloud Logging service (defaults to {@link Synchronicity#ASYNC}). + *
  • {@code com.google.cloud.logging.LoggingHandler.synchronicity} the synchronicity of the + * write method to use to write logs to the Cloud Logging service (defaults to {@link + * Synchronicity#ASYNC}). *
  • {@code com.google.cloud.logging.LoggingHandler.autoPopulateMetadata} is a boolean flag that * opts-out the population of the log entries metadata before the logs are sent to Cloud * Logging (defaults to {@code true}). @@ -126,9 +127,9 @@ * agent. If set to CLOUD_LOGGING, logs will be sent directly to the Google Cloud Logging API. * * - *

    To add a {@code LoggingHandler} to an existing {@link Logger} and be sure to avoid infinite - * recursion when logging, use the {@link #addHandler(Logger, LoggingHandler)} method. Alternatively - * you can add the handler via {@code logging.properties}. For example using the following line: + *

    To add a {@code LoggingHandler} to an existing {@link Logger}, call {@link #addHandler(Logger, + * LoggingHandler)} or {@link Logger#addHandler(Handler)}. Alternatively you can add the handler via + * {@code logging.properties}. For example using the following line: * *

      * {@code com.example.mypackage.handlers=com.google.cloud.logging.LoggingHandler}
    @@ -214,7 +215,7 @@ public LoggingHandler(String log, LoggingOptions options, MonitoredResource moni
        * @param options options for the Cloud Logging service
        * @param monitoredResource the monitored resource to which log entries refer. If it is null then
        *     a default resource is created based on the project ID and deployment environment.
    -   * @param enhancers List of {@link LoggingEnhancer} instances used to enhance any{@link LogEntry}
    +   * @param enhancers List of {@link LoggingEnhancer} instances used to enhance any {@link LogEntry}
        *     instances built by this handler.
        */
       public LoggingHandler(
    @@ -227,15 +228,17 @@ public LoggingHandler(
     
       /**
        * Creates a handler that publishes messages to Cloud Logging. Auto-population of the logs
    -   * metadata can be opted-out in {@code options} argument or in the configuration file. At least
    -   * one flag {@link LoggingOptions} or {@link LoggingConfig} has to be explicitly set to {@code
    -   * false} in order to opt out the metadata auto-population.
    +   * metadata can be opted-out in the {@code options} argument or via the {@code
    +   * com.google.cloud.logging.LoggingHandler.autoPopulateMetadata} configuration property. At least
    +   * one of {@link LoggingOptions#getAutoPopulateMetadata()} or the {@code logging.properties}
    +   * property must be explicitly set to {@code false} in order to opt out of metadata
    +   * auto-population.
        *
        * @param log the name of the log to which log entries are written
        * @param options options for the Cloud Logging service
        * @param monitoredResource the monitored resource to which log entries refer. If it is null then
        *     a default resource is created based on the project ID and deployment environment.
    -   * @param enhancers List of {@link LoggingEnhancer} instances used to enhance any{@link LogEntry}
    +   * @param enhancers List of {@link LoggingEnhancer} instances used to enhance any {@link LogEntry}
        *     instances built by this handler.
        * @param destination the log destination {@link LogDestinationName} (see 'logName' parameter in
        *     https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
    @@ -433,7 +436,7 @@ public void setSynchronicity(Synchronicity synchronicity) {
         logging.setWriteSynchronicity(synchronicity);
       }
     
    -  /** Get the flush log level. */
    +  /** Returns the synchronicity of logging writes. */
       public Synchronicity getSynchronicity() {
         return logging.getWriteSynchronicity();
       }
    @@ -462,7 +465,9 @@ public void setRedirectToStdout(boolean value) {
         this.logTarget = value ? LogTarget.STDOUT : LogTarget.CLOUD_LOGGING;
       }
     
    -  /*
    +  /**
    +   * Returns {@code true} if log output is redirected to {@link LogTarget#STDOUT}.
    +   *
        * @deprecated Use {@link #getLogTarget()}.
        */
       @Deprecated
    @@ -481,14 +486,14 @@ public void setLogTarget(LogTarget value) {
         this.logTarget = value;
       }
     
    +  /** Returns the configured destination target for ingested logs. */
       public LogTarget getLogTarget() {
         return logTarget;
       }
     
       /**
    -   * Adds the provided {@code LoggingHandler} to {@code logger}. Use this method to register Cloud
    -   * Logging handlers instead of {@link Logger#addHandler(Handler)} to avoid infinite recursion when
    -   * logging.
    +   * Adds the provided {@code LoggingHandler} to {@code logger}. This convenience method delegates
    +   * to {@link Logger#addHandler(Handler)}.
        */
       public static void addHandler(Logger logger, LoggingHandler handler) {
         logger.addHandler(handler);
    diff --git a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java
    index f32a59b2026f..cb6bca508788 100644
    --- a/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java
    +++ b/java-logging/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java
    @@ -31,7 +31,7 @@
      *   
  • CRITICAL *
  • ERROR ({@code WARNING < ERROR < SEVERE}) *
  • NOTICE ({@code INFO < NOTICE < WARNING}) - *
  • DEBUG ({@code ALL < DEBUG < FINES}T + *
  • DEBUG ({@code ALL < DEBUG < FINEST}) * * *

    Notice that {@code ERROR} is lower than {@link java.util.logging.Level#SEVERE} but higher than @@ -73,7 +73,7 @@ public final class LoggingLevel extends Level { public static final LoggingLevel ALERT = new LoggingLevel("ALERT", 1100, Severity.ALERT); /** - * A levet to be used when one or more systems are unusable. This level is initialized to {@code + * A level to be used when one or more systems are unusable. This level is initialized to {@code * 1150}. */ public static final LoggingLevel EMERGENCY = From 9e8b3ae18bc3bf30cf2abe0e85e0751646f95a25 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 10:25:22 -0500 Subject: [PATCH 02/57] docs(bigquery): document BigQueryOptions and BigQueryRetryConfig retry and timeout settings (#15128) Documents the retry and timeout configuration entry points on `BigQueryOptions` and `BigQueryRetryConfig`: - Adds class Javadoc to `BigQueryOptions` distinguishing overall retry bounds (`Builder.setRetrySettings`) from per-attempt HTTP connect and read timeouts (`Builder.setTransportOptions(HttpTransportOptions)`, 60-second default read timeout via `getDefaultHttpTransportOptions()`). - Documents `Builder.setTransportOptions`, `Builder.setResultRetryAlgorithm` (including default retry behavior and linking `BigQueryException#isRetryable()`), and `getDefaultHttpTransportOptions()`. - Documents `BigQueryRetryConfig` and its builder methods, explaining why message-based retries exist (BigQuery returns transient failures like rate limits with non-5xx codes such as 403 or 400 or in job error payloads), clarifying its scope (job creation for all job types via `JobOption.bigQueryRetryConfig(...)` and query job status polling via `Job.waitFor(BigQueryRetryConfig, RetryOption...)`, ignored for non-query jobs in `waitFor`), and clarifying case-insensitive substring matching (`retryOnMessage`) vs. lowercased full-string regex matching (`retryOnRegEx`). Verified with `mvn fmt:check`, `checkstyle:check@checkstyle`, `test-compile`, and `javadoc -Xdoclint:syntax,html,reference` (zero new warnings). --- .../cloud/bigquery/BigQueryOptions.java | 28 ++++++++++++++ .../cloud/bigquery/BigQueryRetryConfig.java | 37 +++++++++++++++++++ 2 files changed, 65 insertions(+) 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)); From 0f1c8abab6f4d2e355d1194abdc8ad76dd64a86a Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 10:48:38 -0500 Subject: [PATCH 03/57] fix(auth): preserve serialization compatibility in JwtCredentials (#15190) --- .../google/auth/oauth2/JwtCredentials.java | 17 ++++++++++++- .../auth/oauth2/JwtCredentialsTest.java | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) 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/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 = From c09d09919dd042c73328e0f7d675658473f50213 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 12:48:25 -0500 Subject: [PATCH 04/57] fix(gax-httpjson): resolve OperationsStubSettings endpoint from universe domain (#15191) Overrides `getServiceName()` to return `"longrunning"` and removes `builder.setEndpoint(getDefaultEndpoint())` from `OperationsStubSettings.Builder.createDefault()` so `EndpointContext` resolves the endpoint from the configured universe domain when no explicit endpoint is set. Also annotates `getDefaultEndpoint()` with `@ObsoleteApi` and builds default retry settings in `HttpJsonOperationsStub.create(ClientContext, ...)` via `OperationsStubSettings.newBuilder((ClientContext) null)`. --- .../stub/HttpJsonOperationsStub.java | 12 +- .../stub/OperationsStubSettings.java | 11 +- .../stub/HttpJsonOperationsStubTest.java | 22 ++ .../stub/OperationsStubSettingsTest.java | 243 ++++++++++++++++++ 4 files changed, 282 insertions(+), 6 deletions(-) create mode 100644 sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/longrunning/stub/OperationsStubSettingsTest.java 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; + } + } +} From 5cd60253fb99e9953e19e329721a40dced8ed183 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 13:44:59 -0500 Subject: [PATCH 05/57] fix(bigquery): forward universe domain to BigQueryReadSettings in ConnectionImpl (#15200) Extracts `ConnectionImpl.createBigQueryReadSettings()` and forwards `bigQueryOptions.getUniverseDomain()` when non-null to `BigQueryReadSettings.newBuilder()`, matching `BigQueryImpl.configureReadSettings`. Also uses `NoCredentialsProvider.create()` when `bigQueryOptions.getCredentials()` is `null`, and adds unit tests in `ConnectionImplTest` covering custom universe domain, default universe domain, resolved endpoint, and null credentials. --- .../google/cloud/bigquery/ConnectionImpl.java | 32 ++++++++-- .../cloud/bigquery/ConnectionImplTest.java | 61 +++++++++++++++++++ 2 files changed, 87 insertions(+), 6 deletions(-) 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()); + } } From 19df4efb3f5760ba6d1621e4198b54d49997b477 Mon Sep 17 00:00:00 2001 From: Igor Bernstein Date: Tue, 24 Nov 2026 14:00:45 -0500 Subject: [PATCH 06/57] ci(bigtable): add bigtable-classic-it profile and use it in CFE/DirectPath presubmits (#15181) ## Summary - Adds a composable `bigtable-classic-it` Maven profile in `java-bigtable/google-cloud-bigtable/pom.xml` mirroring `bigtable-session-it`: - Sets `bigtable.internal.client-config-override-use-default=true` - Sets `bigtable.internal.client-config-override` to `session_configuration { session_diversion_configuration { global_diversion { session_load: 0.0 } } }` - Wires `bigtable-classic-it` into `.kokoro/presubmit/bigtable-integration-cfe.cfg` and `.kokoro/presubmit/bigtable-integration-dp.cfg`. ## Why Previously, the CFE and DirectPath presubmit jobs only ran the classic data path implicitly because the target prod instance has not ramped server-driven session diversion yet. Composing `bigtable-classic-it` ensures the `{CFE, DirectPath} x {Classic, Session}` matrix stays explicit and resilient once environments enable sessions by default, while `bigtable-integration.cfg` (`-P bigtable-prod-it`) continues testing the un-overridden server-driven default. Builds on #15171 (`AbstractTestEnv.isSessionsEnabled()`), so setting `bigtable.internal.client-config-override` with `session_load: 0.0` is properly recognized as classic (skipping `SessionIT` and running classic-only tests like `LargeRowIT` and `DirectPathFallbackIT`). ## Verification - Verified resolved Failsafe `systemPropertyVariables` via `mvn help:effective-pom` for: - `-P bigtable-cfe-it,bigtable-classic-it` (`session_load: 0.0`, `override-use-default=true`) - `-P bigtable-directpath-it,bigtable-classic-it` (`session_load: 0.0`, `override-use-default=true`) - `-P bigtable-prod-it` (override remains empty, `override-use-default=false`) - Ran `CloudEnvTest` and `ClientConfigurationManagerTest` (`23/23` passed). --- .kokoro/presubmit/bigtable-integration-cfe.cfg | 2 +- .kokoro/presubmit/bigtable-integration-dp.cfg | 2 +- java-bigtable/google-cloud-bigtable/pom.xml | 8 ++++++++ 3 files changed, 10 insertions(+), 2 deletions(-) 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/java-bigtable/google-cloud-bigtable/pom.xml b/java-bigtable/google-cloud-bigtable/pom.xml index 8dcd545ba78e..6f70c5383334 100644 --- a/java-bigtable/google-cloud-bigtable/pom.xml +++ b/java-bigtable/google-cloud-bigtable/pom.xml @@ -610,6 +610,14 @@ + + bigtable-classic-it + + true + session_configuration { session_diversion_configuration { global_diversion { session_load: 0.0 } } } + + + bigtable-session-it From c14aebb19292200edd1c35ecb9d8c4f96e06b911 Mon Sep 17 00:00:00 2001 From: Igor Bernstein Date: Tue, 24 Nov 2026 14:58:15 -0500 Subject: [PATCH 07/57] chore(bigtable): add bigtable-team to CODEOWNERS for Bigtable CI configs (#15208) Adds `@googleapis/bigtable-team` to `.github/CODEOWNERS` (alongside `@googleapis/cloud-sdk-java-team`) for Bigtable-specific CI configurations so the Bigtable client team can review and approve changes to our own Kokoro configs, Kokoro scripts, and GitHub Actions workflows: - `/.kokoro/bigtable-*` (`.kokoro/bigtable-cleanup.sh`, `.kokoro/bigtable-conformance.sh`) - `/.kokoro/presubmit/bigtable-*` (Bigtable integration and GraalVM native presubmit `.cfg` files) - `/.kokoro/nightly/bigtable-*` (`.kokoro/nightly/bigtable-cleanup.cfg`) - `/.github/workflows/java-bigtable-*` (`.github/workflows/java-bigtable-emulator.yaml`, `.github/workflows/java-bigtable-conformance.yaml`) `@googleapis/cloud-sdk-java-team` remains a co-owner on all matched paths, matching the existing `/java-bigtable/` rule. --- .github/CODEOWNERS | 6 ++++++ 1 file changed, 6 insertions(+) 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 From 32bd4df695f95d0e98be90a81f573c04a277b1e2 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Tue, 24 Nov 2026 15:16:03 -0500 Subject: [PATCH 08/57] chore(ci): configure Maven Resolver HTTP retry backoff for 429/5xx in .mvn/maven.config (#15207) Configure Maven Resolver HTTP transport retries and backoff for HTTP 429/5xx responses in `.mvn/maven.config` to mitigate transient Maven Central rate-limit failures in CI. b/590162583 --- .mvn/maven.config | 4 ++++ 1 file changed, 4 insertions(+) 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 From d8c934c7a8c0eed58cf53e80b45a891debd9d804 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Tue, 24 Nov 2026 15:29:01 -0500 Subject: [PATCH 09/57] chore(bigquery-jdbc): use universe domain terminology (#15210) Update the universeDomain connection property description, unit and integration test identifiers and literals, JUnit @Tag annotations (disable_universe_domain), and testing skill documentation to use universe domain terminology consistently and remove internal links. --- .../skills/bigquery-jdbc-testing/SKILL.md | 29 +++--- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 4 +- .../bigquery/jdbc/BigQueryConnectionTest.java | 23 ++--- .../jdbc/BigQueryDatabaseMetaDataTest.java | 2 +- .../bigquery/jdbc/BigQueryJdbcBaseTest.java | 2 +- .../jdbc/BigQueryJdbcOAuthUtilityTest.java | 2 +- .../jdbc/BigQueryJdbcUrlUtilityTest.java | 16 +-- .../cloud/bigquery/jdbc/it/ITAuthTests.java | 2 +- .../bigquery/jdbc/it/ITBigQueryJDBCTest.java | 46 ++++----- .../jdbc/it/ITConnectionPoolingTest.java | 4 +- .../jdbc/it/ITDatabaseMetadataTest.java | 16 +-- .../cloud/bigquery/jdbc/it/ITDriverTest.java | 2 +- .../jdbc/it/ITJdbcTimestampPicosTest.java | 2 +- .../jdbc/it/ITNightlyBigQueryTest.java | 18 ++-- .../bigquery/jdbc/it/ITOpenTelemetryTest.java | 2 +- .../cloud/bigquery/jdbc/it/ITPcntTest.java | 2 +- .../bigquery/jdbc/it/ITStatementTest.java | 2 +- ...java => ITUniverseDomainBigQueryTest.java} | 97 +++++++++---------- 18 files changed, 135 insertions(+), 136 deletions(-) rename java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/{ITTPCBigQueryTest.java => ITUniverseDomainBigQueryTest.java} (72%) 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/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..e5720baa52f9 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 @@ -377,8 +377,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() 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..7e7bad7b64e8 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 @@ -96,7 +96,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;" @@ -974,28 +974,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 +1065,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 +1074,7 @@ 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); } private static URI storageUri(String universeDomain, String service) { 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..c932a5e0f7b6 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 @@ -3567,7 +3567,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_お客様")); } 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/BigQueryJdbcOAuthUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtilityTest.java index 1a086782e341..917dcce261be 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 @@ -173,7 +173,7 @@ public void testGetCredentialsForPreGeneratedToken() { } @Test - public void testGetCredentialsForPreGeneratedTokenTPC() throws IOException { + public void testGetCredentialsForPreGeneratedTokenCustomUniverseDomain() throws IOException { Map authProperties = BigQueryJdbcOAuthUtility.parseOAuthProperties( DataSource.fromUrl( 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..71f2b7ffa3c5 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 @@ -318,20 +318,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 +346,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(" : ")); 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..25266c2611b2 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 @@ -267,7 +267,7 @@ public void testPooledConnectionListenerConnectionError() throws SQLException { } @Test - @Tag("disable_tpc") + @Tag("disable_universe_domain") public void testExecuteQueryWithConnectionPoolingEnabledDefaultPoolSize() throws SQLException { String connectionURL = ITBase.connectionUrl; @@ -275,7 +275,7 @@ 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 + ";"; 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..3bc9d5f2003c 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 @@ -387,7 +387,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"); } } } From 2b00c9e9f8f0e557f4ebdeaf0427b1cb322c66a8 Mon Sep 17 00:00:00 2001 From: Igor Bernstein Date: Tue, 24 Nov 2026 15:33:13 -0500 Subject: [PATCH 10/57] fix(bigtable): ignore blank client-config-override and enforce IT protocol (#15206) ## Summary Fixes a bug where Maven Failsafe's empty `-Dbigtable.internal.client-config-override=""` bypassed `GetClientConfiguration` polling on default integration test runs, and adds suite-wide protocol enforcement (`-Dbigtable.expected-protocol`) for Bigtable integration tests. ### Changes 1. **Ignore blank `bigtable.internal.client-config-override` (`ClientConfigurationManager`)**: - Filter out blank strings (`.filter(str -> !str.trim().isEmpty())`) so empty default `` in `pom.xml` are treated as unset and default IT runs genuinely poll `GetClientConfiguration`. - Added unit test `testBlankSysPropOverrideIsIgnoredAndPollsServer` in `ClientConfigurationManagerTest`. 2. **Skip `GetClientConfiguration` in DirectPath remote-address check (`CloudEnv`)**: - Under `REQUIRE_DIRECT_PATH` / `REQUIRE_DIRECT_PATH_IPV4`, skip the remote IP check for `GetClientConfiguration` since `ClientConfigurationManager` always polls over CloudPath regardless of data transport. - Keep checking `GetClientConfiguration` under `REQUIRE_CFE` so `ShimImpl`'s DirectAccess probe over DirectPath continues to be rejected and forces CFE. 3. **Suite-wide protocol enforcement (`AbstractTestEnv`, `CloudEnv`, `pom.xml`, `.kokoro/presubmit/bigtable-integration.cfg`)**: - Added `-Dbigtable.expected-protocol` (`ANY` | `CLASSIC` | `SESSION`), defaulting to `ANY` when unset/blank, set to `SESSION` in `bigtable-session-it`, and passed as `CLASSIC` in `.kokoro/presubmit/bigtable-integration.cfg` *(follow-up: add `CLASSIC` to `bigtable-classic-it` once #15181 merges)*. - Validate resolved session config in `CloudEnv.start()` via `verifyExpectedProtocol(...)`. - Attach a suite-wide protocol enforcement interceptor (including under `ConnectionMode.DEFAULT`): - `CLASSIC`: aborts any `Bigtable/Open*` RPC with `Status.FAILED_PRECONDITION`. - `SESSION`: aborts classic `MutateRow`, `CheckAndMutateRow`, `ReadModifyWriteRow`, and single-point `ReadRows` (`rows_limit == 1` with single key or equal closed-closed range) with `Status.FAILED_PRECONDITION`, leaving bulk/range `ReadRows` and `MutateRows` unblocked. - Added unit tests in `CloudEnvTest` covering protocol parsing, startup validation, remote-address skipping, and protocol enforcement. 4. **Gate `SessionIT` on `ExpectedProtocol.SESSION`**: - Switch `SessionIT`'s `assume()` from `isSessionsEnabled()` to `getExpectedProtocol() == ExpectedProtocol.SESSION` so environments mid-ramp (e.g. 50% diversion) don't flake once `GetClientConfiguration` polling is restored. ## Verification - Formatted with `mvn com.spotify.fmt:fmt-maven-plugin:format` - Verified `mvn help:effective-pom` for `bigtable-prod-it`, `bigtable-prod-it -Dbigtable.expected-protocol=CLASSIC`, and `bigtable-cfe-it,bigtable-session-it` - Ran `mvn test -Dtest=CloudEnvTest,ClientConfigurationManagerTest` (34/34 passed, 0 Checkstyle violations) --- .kokoro/presubmit/bigtable-integration.cfg | 2 +- java-bigtable/google-cloud-bigtable/pom.xml | 3 + .../util/ClientConfigurationManager.java | 1 + .../util/ClientConfigurationManagerTest.java | 29 ++ .../cloud/bigtable/data/v2/it/SessionIT.java | 16 +- .../test_helpers/env/AbstractTestEnv.java | 19 + .../bigtable/test_helpers/env/CloudEnv.java | 208 +++++++++- .../test_helpers/env/CloudEnvTest.java | 373 ++++++++++++++++++ 8 files changed, 624 insertions(+), 27 deletions(-) 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/java-bigtable/google-cloud-bigtable/pom.xml b/java-bigtable/google-cloud-bigtable/pom.xml index 6f70c5383334..67a2b65bf119 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/BuiltInMetricsProvider.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/BuiltInMetricsProvider.java index e43d848671af..2e42c7bcae7f 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 @@ -61,7 +61,7 @@ import java.util.logging.Logger; import javax.annotation.Nullable; -final class BuiltInMetricsProvider { +class BuiltInMetricsProvider { static BuiltInMetricsProvider INSTANCE = new BuiltInMetricsProvider(); @@ -78,7 +78,9 @@ final class BuiltInMetricsProvider { private boolean mismatchedProjectIdLogged; private Thread shutdownHook; - private BuiltInMetricsProvider() {} + // Package-private and non-final so tests can record the arguments passed by SpannerOptions. + @VisibleForTesting + BuiltInMetricsProvider() {} synchronized OpenTelemetry getOrCreateOpenTelemetry( String projectId, 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 495fd67a9d7c..7a8404e131bf 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; @@ -118,7 +120,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 +138,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 +326,10 @@ static GcpChannelPoolOptions mergeWithDefaultChannelPoolOptions( private final boolean trackTransactionStarter; private final boolean enableGrpcGcpOtelMetrics; private final boolean enableChannelPoolBuiltInMetrics; - private final BuiltInMetricsProvider builtInMetricsProvider = BuiltInMetricsProvider.INSTANCE; + + // Non-final so tests can observe the arguments passed to the process-wide metrics provider. + @VisibleForTesting + BuiltInMetricsProvider builtInMetricsProvider = BuiltInMetricsProvider.INSTANCE; /** * 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); } @@ -1013,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); @@ -1141,7 +1148,8 @@ protected SpannerOptions(Builder builder) { * 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; } @@ -1152,8 +1160,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; } @@ -1161,6 +1184,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; @@ -1252,6 +1298,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"; @@ -1381,6 +1435,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. */ @@ -3048,7 +3107,7 @@ public ApiTracerFactory getApiTracerFactory() { @InternalApi public OpenTelemetry getBuiltInOpenTelemetry() { return this.builtInMetricsProvider.getOrCreateOpenTelemetry( - this.getProjectId(), getCredentials(), this.monitoringHost, getUniverseDomain()); + this.getProjectId(), getCredentials(), this.monitoringHost, getResolvedUniverseDomain()); } /** @@ -3088,7 +3147,7 @@ public void enablegRPCMetrics( this.getProjectId(), getCredentials(), this.monitoringHost, - getUniverseDomain()); + getResolvedUniverseDomain()); } if (usesCustomMetricsProvider()) { OpenTelemetry customOpenTelemetry = @@ -3187,7 +3246,10 @@ private ApiTracerFactory createCustomMetricsTracerFactory() { 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( 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 0bc461465c4e..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 @@ -220,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"; @@ -846,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), @@ -1371,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); } @@ -1553,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 16150825ba0e..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 @@ -232,11 +232,13 @@ public class ConnectionProperties { BooleanConverter.INSTANCE, Context.STARTUP); public static final ConnectionProperty UNIVERSE_DOMAIN = - createNonNull( + 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); public static final ConnectionProperty USE_AUTO_SAVEPOINTS_FOR_EMULATOR = 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 b71cb9db1512..a0ca6cd60bae 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; @@ -80,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; @@ -91,6 +97,7 @@ import java.util.logging.Level; 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; @@ -2259,4 +2266,434 @@ 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", + 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(); + } + } + } + + /** Records the universe domain that {@link SpannerOptions} passes to the metrics provider. */ + private static final class RecordingBuiltInMetricsProvider extends BuiltInMetricsProvider { + private final List universeDomains = new ArrayList<>(); + + @Override + synchronized OpenTelemetry getOrCreateOpenTelemetry( + String projectId, Credentials credentials, String monitoringHost, String universeDomain) { + universeDomains.add(universeDomain); + return OpenTelemetry.noop(); + } + + @Override + void enableGrpcMetrics( + InstantiatingGrpcChannelProvider.Builder channelProviderBuilder, + String projectId, + Credentials credentials, + String monitoringHost, + String universeDomain) { + universeDomains.add(universeDomain); + } + } + + 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/connection/ConnectionOptionsTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/connection/ConnectionOptionsTest.java index 1c9787af1517..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; @@ -39,27 +40,38 @@ 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; @@ -2092,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(); @@ -2444,6 +2459,129 @@ public void testProgrammaticPropertiesAllowedAndTrusted() throws Throwable { }); } + @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 = @@ -3025,4 +3163,302 @@ public void testStartupPropertyPolicy() throws Throwable { 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 3c6cef5237ff..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 @@ -366,6 +366,7 @@ public void testCreateConnectionPropertyValue() { ConnectionProperties.STATEMENT_TIMEOUT, ConnectionProperties.AUTOCOMMIT_DML_MODE, ConnectionProperties.RPC_PRIORITY, + ConnectionProperties.UNIVERSE_DOMAIN, }) { assertTrue(nullableProperty.isNullAllowed()); assertNull(ConnectionPropertyValue.of(nullableProperty, null).getValue()); @@ -389,7 +390,6 @@ public void testCreateConnectionPropertyValue() { ConnectionProperties.SAVEPOINT_SUPPORT, ConnectionProperties.DDL_IN_TRANSACTION_MODE, ConnectionProperties.TRACING_PREFIX, - ConnectionProperties.UNIVERSE_DOMAIN, ConnectionProperties.OPTIMIZER_VERSION, ConnectionProperties.READ_ONLY_STALENESS, }) { 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 f459ef54bf5c..79a1bc2138e9 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 @@ -1319,4 +1319,42 @@ public void testSpannerPoolKeyReuseWithStartupPropertyPolicyReject() { 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); + } } From 420f49e4b784ec3425f4a5cca84660ae89a7b299 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:33:09 +0530 Subject: [PATCH 33/57] fix(spanner): reject point-at-infinity and non-canonical EC points in OPAQUE (#15146) ## Problem Statement - During Spanner Omni OPAQUE authentication, `OpaqueUtil.finalize`, `OpaqueUtil.diffieHellman`, and `OpaqueUtil.blind` accepted the elliptic-curve point at infinity (`{0x00}`) and non-canonical point encodings. - If a rogue login server returned `{0x00}` as `evaluated_message`, `OpaqueUtil.finalize` returned `{0x00}` regardless of the client's password or blind scalar, making all derived OPAQUE envelope and AKE keys password-independent and breaking mutual server authentication. ## Solution - Enforce canonical 33-byte compressed `secp256r1` point encoding (`0x02` or `0x03` prefix) and reject the point at infinity, non-canonical encodings, and off-curve points before and after scalar multiplication in `OpaqueUtil.finalize`, `OpaqueUtil.diffieHellman`, and `OpaqueUtil.blind` (per RFC 9497 Section 3.3.1 / RFC 9807). - Validate that scalar inputs (`blind`, `privateKey`, `blindScalar`) are non-null, non-empty, and non-zero modulo the curve order. - Behavior change: direct callers of `OpaqueUtil.finalize`, `OpaqueUtil.diffieHellman`, or `OpaqueUtil.blind` now receive a checked `GeneralSecurityException` on invalid points or zero/order-multiple scalars rather than `{0x00}` or unchecked `IllegalArgumentException`, `NullPointerException`, or `ArithmeticException`. --- .../google/cloud/spanner/omni/OpaqueUtil.java | 92 ++++++- .../cloud/spanner/omni/LoginClientTest.java | 258 ++++++++++++++++++ .../cloud/spanner/omni/OpaqueUtilTest.java | 155 +++++++++++ 3 files changed, 491 insertions(+), 14 deletions(-) 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/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)); + } } From 1c0a358f74be88c913e5ed1cbe59536e284686f3 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:34:01 +0530 Subject: [PATCH 34/57] fix(spanner): skip Cloud Monitoring built-in metrics for unauthenticated clients (#15259) ## Problem Statement - Creating a non-emulator Cloud Spanner client without Google credentials (such as with `NoCredentials`, `usePlainText()`, or no Application Default Credentials) before an authenticated client in the same JVM could initialize the shared Cloud Monitoring built-in metrics exporter without credentials. - Because the Cloud Monitoring exporter is shared across the process, subsequent authenticated Spanner clients in the same JVM could fail to export built-in metrics to Cloud Monitoring. ## Solution - Skip initializing the Cloud Monitoring built-in metrics exporter during gRPC and fallback metrics setup when a Spanner client is configured with `NoCredentials` or `null` credentials, matching existing behavior for application-layer and channel-pool built-in metrics. - Preserve caller-owned `CustomOpenTelemetryMetricsProvider` sinks so clients without Google credentials can still export metrics to custom OpenTelemetry destinations. --- .../google/cloud/spanner/SpannerOptions.java | 22 +- ...BuiltInMetricsCustomOpenTelemetryTest.java | 53 +++- .../cloud/spanner/SpannerOptionsTest.java | 235 +++++++++++++++++- .../spanner/spi/v1/GapicSpannerRpcTest.java | 15 ++ 4 files changed, 314 insertions(+), 11 deletions(-) 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 7a8404e131bf..5ac8c191df69 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 @@ -3046,7 +3046,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() { @@ -3103,9 +3104,16 @@ 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 or no credentials are configured. + */ @InternalApi + @Nullable public OpenTelemetry getBuiltInOpenTelemetry() { + if (!isEnableBuiltInMetrics() || usesNoCredentials()) { + return null; + } return this.builtInMetricsProvider.getOrCreateOpenTelemetry( this.getProjectId(), getCredentials(), this.monitoringHost, getResolvedUniverseDomain()); } @@ -3125,10 +3133,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( @@ -3141,7 +3149,7 @@ 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(), 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..fa217c70f947 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 @@ -47,9 +47,9 @@ public class BuiltInMetricsCustomOpenTelemetryTest extends AbstractMockServerTes @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. + SpannerOptions.useDefaultEnvironment(); + // Reset the process-wide Cloud Monitoring singleton so state cannot leak across tests sharing + // the JVM fork. BuiltInMetricsProvider.INSTANCE.reset(); } @@ -165,4 +165,51 @@ public void gcmSingletonIsNotInitializedByCustomOnlyClient() { } assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); } + + @Test + public void noCredentialsClientDoesNotInitializeGcmSingletonWithGrpcMetricsEnabled() { + SpannerOptions.useEnvironment( + new SpannerOptions.SpannerEnvironment() { + @Override + public boolean isEnableGRPCBuiltInMetrics() { + return true; + } + }); + BuiltInMetricsProvider.INSTANCE.reset(); + + // Default provider with NoCredentials and built-in metrics enabled must not initialize GCM. + try (Spanner defaultSpanner = + spannerBuilder(DefaultMetricsProvider.INSTANCE) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build() + .getService()) { + executeSelect1(defaultSpanner); + } + assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + + // Custom provider with NoCredentials and built-in metrics enabled still records custom metrics + // while leaving the GCM singleton uninitialized. + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); + try { + try (Spanner customSpanner = + spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build() + .getService()) { + executeSelect1(customSpanner); + } + assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + assertNotNull( + getMetric( + metricReader, + BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + + "/" + + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); + } finally { + customOpenTelemetry.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 a0ca6cd60bae..7d7a09bf8390 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 @@ -2665,14 +2665,238 @@ public boolean isEnableGRPCBuiltInMetrics() { } } - /** Records the universe domain that {@link SpannerOptions} passes to the metrics provider. */ + @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; + } + }); + } + + /** + * Records the universe domain, credentials, and custom OpenTelemetry instances 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<>(); @Override synchronized OpenTelemetry getOrCreateOpenTelemetry( String projectId, Credentials credentials, String monitoringHost, String universeDomain) { universeDomains.add(universeDomain); + this.credentials.add(credentials); return OpenTelemetry.noop(); } @@ -2684,6 +2908,15 @@ void enableGrpcMetrics( 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); } } 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..5e5496897d89 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 @@ -2809,6 +2809,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 = From d61b6d32b69004e3d21dd2c145d449dd8b2c1a87 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Fri, 27 Nov 2026 17:07:33 +0000 Subject: [PATCH 35/57] fix(bigquery-jdbc): use loopback binding, PKCE, and state verification in user account OAuth flow (#15241) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit b/584840384 ### Summary Aligns interactive user-account authentication (`OAuthType=1`) in `BigQueryJdbcOAuthUtility` with RFC 8252 and RFC 7636, extracts the local loopback HTTP callback listener into `BigQueryJdbcOAuthCallbackServer`, and ensures `RequestGoogleDriveScope` and explicit `universeDomain` settings apply to user-account credentials. ### What Changed & Why - **Desktop pre-check & deterministic socket cleanup:** `getGoogleUserAccountCredentials` checks `isDesktopBrowseSupported()` (`GraphicsEnvironment.isHeadless()`, `Desktop.isDesktopSupported()`, and `Desktop.Action.BROWSE`) before opening a local socket, and wraps `BigQueryJdbcOAuthCallbackServer` and accepted `Socket` instances in `try-with-resources` so the listener closes prior to token exchange and on any error or timeout. - **RFC 8252 loopback redirect URI (`BigQueryJdbcOAuthCallbackServer`):** `openLoopbackServerSocket()` binds `127.0.0.1` (falling back to `::1` on IPv6-only hosts, `backlog = 8`) using `java.net.ServerSocket` (`java.base`, avoiding a `jdk.httpserver` module dependency in custom `jlink` / OSGi runtimes) and `buildLoopbackCallbackUri()` formats `http://127.0.0.1:` or `http://[::1]:` for `getUserAuthorizer`. Matching the bound IP family avoids `Connection Refused` errors when the browser and JVM resolve `localhost` to different address families. (The 9-argument `getGoogleUserAccountCredentials` and 1-argument `openLoopbackServerSocket` package-private overloads are deterministic test seams to which the production entry points delegate.) - **RFC 7636 `S256` PKCE, OAuth `state`, & `RequestGoogleDriveScope`:** Configured `UserAuthorizer` with `Rfc7636PkceProvider` (used instead of `DefaultPKCEProvider`, which in `google-auth-library-oauth2-http` `1.58.0` emits a 172-character `=`-padded `code_verifier` outside RFC 7636 Section 4.1's 43–128 unreserved-character range), added `state` generation and callback verification, and wired `RequestGoogleDriveScope` (`BIGQUERY_WITH_DRIVE_SCOPES` vs. `DEFAULT_BIGQUERY_SCOPES`) at authorization consent time. - **Explicit `universeDomain` propagation:** `getCredentialsFromCode` propagates `UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME` from `overrideProperties` onto `UserCredentials.Builder`, matching non-JSON credential handling for custom universe domains. - **Reliable HTTP/1.1 callback parsing & responses:** - Enforces a `1000 ms` per-socket read timeout within the `120 s` callback window, skipping empty browser TCP preconnects, returning `404 Not Found` for secondary requests such as `/favicon.ico`, and continuing to listen after malformed or unverified HTTP requests (responding `400 Bad Request` and recording the last rejected request reason in case the callback window times out). - Parses the callback request target via `URI`, UTF-8 URL-decodes query parameters while preserving literal `+` characters per RFC 3986 (`code`, `state`, `error`), and immediately aborts when a `state`-verified callback reports an OAuth `error=` or omits `code`. - Drains up to `64 KiB` of request headers (accommodating `127.0.0.1` cookies) and calls `socket.shutdownOutput()` after flushing `\r\n`-formatted HTTP/1.1 responses (`200 OK`, `400 Bad Request`, `404 Not Found`) with `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src 'none'`, `Connection: close`, and exact UTF-8 byte `Content-Length`. - **Documentation (`docs/USER_GUIDE.md`):** Documented that custom `OAuthClientId` values used with `OAuthType=1` must be configured as a **Desktop app** OAuth 2.0 client. ### Compatibility Notes - Existing `OAuthType=1` flows already used ephemeral ports (`ServerSocket(0)`), which require a Google **Desktop app** OAuth 2.0 client (default or custom `OAuthClientId`). Google Desktop OAuth clients natively support `http://127.0.0.1:` and `http://[::1]:` redirect URIs and `S256` PKCE without Cloud Console changes. ### Testing - `BigQueryJdbcOAuthUtilityTest` covers `S256` PKCE challenge/verifier exchange, `RequestGoogleDriveScope` consent scope selection, default vs. explicit `universeDomain` propagation (including ignoring `GOOGLE_CLOUD_UNIVERSE_DOMAIN` for non-JSON credentials), IPv4/IPv6 loopback binding without mocking JDK networking classes, RFC 3986 `+` and `%2B` query decoding and malformed `%` handling, `state` and `error=` callback validation, `> 16 KiB` and `> 64 KiB` header draining, resilience to browser TCP preconnects / `/favicon.ico` / unverified local HTTP probes, timeout diagnostics and socket cleanup paths, and non-desktop environment fast-fail. - Live interactive browser consent was not run in automated CI as `OAuthType=1` requires desktop user interaction. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 4 +- .../jdbc/BigQueryJdbcOAuthCallbackServer.java | 431 +++++++ .../jdbc/BigQueryJdbcOAuthUtility.java | 202 ++- .../jdbc/BigQueryJdbcOAuthUtilityTest.java | 1104 ++++++++++++++++- 4 files changed, 1650 insertions(+), 91 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 9ec81ced44c7..017191ee9075 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. | 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 0682acc81508..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,9 @@ 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()); @@ -280,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 = @@ -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,55 +499,78 @@ 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( Map authProperties, Map overrideProperties, 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 f8df1f90e31a..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,10 +20,17 @@ 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; @@ -33,30 +40,49 @@ 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() { @@ -247,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 @@ -288,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) { @@ -573,6 +678,939 @@ public void testGetPreGeneratedRefreshTokenCredentialsPropagatesHttpTransportFac .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 { @@ -660,6 +1698,23 @@ public void testNonJsonCredentialsIgnoreEnvUniverseDomainAndUseExplicitOnly() th 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( @@ -669,6 +1724,11 @@ public void testNonJsonCredentialsIgnoreEnvUniverseDomainAndUseExplicitOnly() th "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()); } } From cff532d546f2ab53aa216227df08e5352317d676 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Fri, 27 Nov 2026 17:37:57 +0000 Subject: [PATCH 36/57] fix(bigquery-jdbc): enforce JDBC connection pooling lifecycle, state reset, and physical isolation (#15202) ### Summary Consolidates the 3-PR JDBC connection pooling stack (#15202, #15203, #15204) onto a single branch targeting `main` so all CI checks run against the complete change and the stack lands atomically. Fixes physical connection isolation, JDBC 4.3 `PooledConnection` / logical `Connection` lifecycle contracts, and mutable connection/transaction/session state reset on pool return: - **Connection state reset hook (`BigQueryConnection.resetForReuse()`):** Closes remaining open `Statement` instances tracked in `openStatements`, resets `autoCommit` to `true`, rolls back any active transaction without starting a follow-up `BEGIN TRANSACTION;` (`rollbackImpl(false)` in both `resetForReuse()` and `closeImpl()`), aborts driver-created BigQuery sessions (`CALL BQ.ABORT_SESSION();` when `EnableSession=1`) even when the calling thread is interrupted while preserving caller-configured `QueryProperties=session_id=...` properties, surfaces `BigQueryException` on pooled session abort while preserving un-aborted transaction/session state for fallback physical `close()`, clears `clientInfo` and `sqlWarnings` (backed by `CopyOnWriteArrayList` for concurrent snapshot reads), and restores `holdability`. - **Lifecycle serialization, rejection-safe `abort(Executor)` & MDC preservation:** Serializes `resetForReuse()` and `closeImpl()` via `lifecycleLock`; coordinates `abort(Executor)` and `close()` via `closeStateLock` so `isClosed` remains `false` until `executor.execute` accepts/starts while gating `checkClosed()` on `closeInitiated`; honors configured `Timeout` and inspects `JobStatus` on transaction commit/rollback job waits; and saves/restores outer thread MDC `connectionId` in `BigQueryJdbcMdc.registerInstance`, `close()`, and `abort(Executor)`. - **JDBC 4.3 `BigQueryPooledConnection` & dynamic handle/child proxies:** Replaces `BigQueryPooledConnectionWrapper` with `PooledConnectionInvocationHandler` backed by a per-handle `ReentrantReadWriteLock` shared with pooled `Statement` and `DatabaseMetaData` proxies so operational calls hold the read lock during RPCs while `close()`, handle reclaim, and physical teardown await quiescence. Wraps child `Statement` / `PreparedStatement` / `CallableStatement` and `DatabaseMetaData` objects (and attaches pooled proxies on `BigQueryStatement` for `ResultSet.getStatement()`) so `getConnection()` enforces `parentHandler.checkClosed()` and returns the logical `Connection` handle. Fires `connectionErrorOccurred` and physically closes `BigQueryConnection` on reset failures or out-of-band physical closes, dispatches `abort(Executor)` teardown asynchronously, isolates listener `RuntimeException`s, and scopes MDC inside `physicalLock`. - **Dedicated physical connections & concurrent LIFO checkout (`PooledConnectionDataSource` / `PooledConnectionListener`):** Removes the cached shared `bqConnection` field from `PooledConnectionDataSource` so cache misses open a dedicated `BigQueryConnection`, recycles idle physical connections into fresh `BigQueryPooledConnection` holders while retiring prior holders (`State.RETIRED`), separates the internal pool listener from public `ListenerPoolSize` slots with sticky external ownership on `addConnectionEventListener`, uses atomic LIFO (`addFirst`/`pollFirst`) checkout under `poolLock`, closes excess driver-owned idle connections at `ConnectionPoolSize` (`0` = unbounded), and clarifies `ConnectionPoolSize` and `ListenerPoolSize` in `docs/USER_GUIDE.md`. ### Behavior Changes - Every cache miss on `PooledConnectionDataSource.getPooledConnection()` opens a dedicated physical `BigQueryConnection`, and idle-pool hits wrap the recycled physical connection in a new `PooledConnection` while retiring the previous holder. - `Connection.close()` on a pooled handle synchronously runs state/transaction/session reset RPCs when needed and propagates any reset `SQLException` after firing `connectionErrorOccurred`. - `BigQueryPooledConnection.close()` physically closes `BigQueryConnection` and removes the holder from `PooledConnectionListener` without firing `connectionClosed`. - `BigQueryPooledConnection.getConnection()` while a handle is open invalidates the prior handle and resets connection state without firing `connectionClosed` (`PooledConnection#getConnection()`, JDBC 4.3 section 11.1). - Returning a connection when the built-in idle pool is at `ConnectionPoolSize` closes the excess physical connection inline on the caller thread (`ConnectionPoolSize=0` retains all idle connections). - Operational calls on a closed logical handle or retained child `Statement` / `DatabaseMetaData` throw `BigQueryJdbcException` (`SQLClientInfoException` with `ClientInfoStatus.REASON_UNKNOWN` for `setClientInfo`). ### Testing - Added/updated unit tests in `BigQueryConnectionTest`, `BigQueryJdbcMdcTest`, `BigQueryPooledConnectionTest`, `PooledConnectionDataSourceTest`, and `PooledConnectionListenerTest` (`1,384` unit tests passing). - Added integration tests in `ITConnectionPoolingTest` verifying independent concurrent checkouts and end-to-end session and uncommitted-transaction reset on pool return. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 4 +- .../bigquery/jdbc/BigQueryBaseResultSet.java | 6 +- .../bigquery/jdbc/BigQueryConnection.java | 425 +++-- .../cloud/bigquery/jdbc/BigQueryJdbcMdc.java | 16 +- .../jdbc/BigQueryPooledConnection.java | 1186 ++++++++++---- .../bigquery/jdbc/BigQueryStatement.java | 19 +- .../jdbc/PooledConnectionDataSource.java | 56 +- .../jdbc/PooledConnectionListener.java | 184 ++- .../bigquery/jdbc/BigQueryConnectionTest.java | 655 ++++++++ .../bigquery/jdbc/BigQueryJdbcMdcTest.java | 17 +- .../jdbc/BigQueryPooledConnectionTest.java | 1391 ++++++++++++++++- .../jdbc/PooledConnectionDataSourceTest.java | 397 ++++- .../jdbc/PooledConnectionListenerTest.java | 225 ++- .../jdbc/it/ITConnectionPoolingTest.java | 336 ++-- 14 files changed, 4157 insertions(+), 760 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 017191ee9075..518110948b9b 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -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 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..2235166c9d0d 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 @@ -290,7 +290,11 @@ public int getConcurrency() throws SQLException { @Override public Statement getStatement() throws SQLException { checkClosed(); - return this.statement; + if (this.statement == null) { + 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 c495045c456c..b2fea3a38654 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,12 +76,14 @@ 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; @@ -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; @@ -255,6 +262,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { 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. @@ -291,7 +299,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { } this.openStatements = ConcurrentHashMap.newKeySet(); this.autoCommit = true; - this.sqlWarnings = new ArrayList<>(); + this.sqlWarnings = new CopyOnWriteArrayList<>(); this.transactionStarted = false; this.isClosed = false; @@ -386,11 +394,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(); @@ -907,7 +916,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 @@ -950,7 +992,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 @@ -1012,10 +1055,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;") @@ -1023,9 +1066,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) { @@ -1036,6 +1079,108 @@ 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) { @@ -1084,152 +1229,144 @@ 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(); } + BigQueryJdbcMdc.clear(); + BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); + BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); + BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); + this.openTelemetry = null; } - if (interrupted) { - Thread.currentThread().interrupt(); + if (exceptionToThrow != null) { + throw exceptionToThrow; } - if (terminationInterruptedException != null) { - BigQueryJdbcException interruptedException = - new BigQueryJdbcException("Interrupted during close", terminationInterruptedException); - if (exceptionToThrow == null) { - exceptionToThrow = interruptedException; - } else { - exceptionToThrow.addSuppressed(interruptedException); - } - } - } 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; } } @@ -1247,7 +1384,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"); } } @@ -1593,32 +1730,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/BigQueryJdbcMdc.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java index 254cdc5cc2fa..09e25b4f673f 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 @@ -36,12 +36,24 @@ class BigQueryJdbcMdc { private static final InheritableThreadLocal currentConnectionId = 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) { + String previousConnectionId = currentConnectionId.get(); if (connectionId != null) { currentConnectionId.set(connectionId); + } else { + clear(); } - return () -> clear(); + return () -> { + if (previousConnectionId != null) { + currentConnectionId.set(previousConnectionId); + } else { + clear(); + } + }; } /** 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/BigQueryStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java index 13181dfc4806..5c813e71b797 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; @@ -122,7 +123,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; @@ -415,6 +418,8 @@ public void close() throws SQLException { closeStatementResources(); } this.connection = null; + this.logicalConnection = null; + this.logicalStatementProxy = null; } } @@ -1833,9 +1838,19 @@ private int[] executeBatchImpl(String combinedQueries) throws SQLException { 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/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/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java index 19e9ae9bfa02..18f3bb40baf1 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 @@ -30,6 +30,9 @@ 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; @@ -45,17 +48,21 @@ 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.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.TableResult; import com.google.cloud.bigquery.exception.BigQueryJdbcException; +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; @@ -72,13 +79,29 @@ import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +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.List; import java.util.Map; import java.util.Optional; import java.util.Properties; +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; @@ -1280,4 +1303,636 @@ private static JsonObject extractBearerJwtPayload(Credentials credentials, URI u new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); return JsonParser.parseString(payloadJson).getAsJsonObject(); } + + 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/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/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/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/ITConnectionPoolingTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITConnectionPoolingTest.java index 25266c2611b2..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,33 +261,36 @@ 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 @@ -282,52 +309,165 @@ public void testExecuteQueryWithConnectionPoolingEnabledCustomPoolSize() throws 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(); + } } } From 1d01c6ce545a3f50d70e0565498af18bc63a33e9 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:22:43 +0530 Subject: [PATCH 37/57] chore(spanner): bound streaming server retry delays and fall back on non-positive values (#15074) Sanitize server-supplied `RetryInfo` delays when resuming interrupted Cloud Spanner streaming reads and queries so zero, negative, or oversized retry trailers cannot trigger zero-delay retry spin loops or stall consumer threads for hours. - Fall back to exponential backoff (`>= 1 ms`) when a server retry delay is zero, sub-millisecond, or negative instead of retrying immediately without sleeping. - Cap positive server retry delays at the configured maximum retry delay on streaming retry settings (defaulting to `32s` when unset or non-positive) before evaluating the remaining total timeout budget. - Use the same `32s` ceiling for client-side exponential backoff when maximum retry delay is unset on streaming retry settings. --- .../spanner/ResumableStreamIterator.java | 79 +++- .../cloud/spanner/spi/v1/GapicSpannerRpc.java | 5 +- .../spanner/ResumableStreamIteratorTest.java | 412 ++++++++++++++++-- .../StreamingRetryBudgetMockServerTest.java | 2 +- 4 files changed, 447 insertions(+), 51 deletions(-) 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..9ad1f3621a01 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 @@ -37,6 +37,7 @@ 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; @@ -62,7 +63,9 @@ * 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 + * missing or non-positive server retry delays fall back to exponential backoff. * *

    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,6 +92,7 @@ abstract class ResumableStreamIterator extends AbstractIterator retryableCodes; + private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 32_000L; private static final Logger logger = Logger.getLogger(ResumableStreamIterator.class.getName()); @Nullable private BackOff backOff; private final ArrayDeque buffer = new ArrayDeque<>(); @@ -200,8 +204,9 @@ private boolean maxAttemptsExhausted() { * 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(); + @VisibleForTesting + boolean totalTimeoutExceeded(long proposedDelayMillis) { + long totalTimeoutMillis = streamingRetrySettings.getTotalTimeoutDuration().toMillis(); if (totalTimeoutMillis <= 0L) { return false; } @@ -215,23 +220,45 @@ private boolean totalTimeoutExceeded(long proposedDelayMillis) { return Math.max(proposedDelayMillis, 0L) >= totalTimeoutMillis - elapsedMillis; } - private ExponentialBackOff newBackOff() { + /** + * 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 zero or negative. + */ + private static long saturatedDurationMillis( + Duration duration, long nonPositiveDefaultMillis, long maxMillis) { + if (duration.isZero() || duration.isNegative()) { + return nonPositiveDefaultMillis; + } + try { + return Math.max(1L, Math.min(duration.toMillis(), maxMillis)); + } catch (ArithmeticException overflow) { + return maxMillis; + } + } + + private long effectiveMaxRetryDelayMillis() { + return saturatedDurationMillis( + streamingRetrySettings.getMaxRetryDelayDuration(), + DEFAULT_MAX_RETRY_DELAY_MILLIS, + Long.MAX_VALUE); + } + + @VisibleForTesting + BackOff newBackOff() { + int initialIntervalMillis = + (int) + saturatedDurationMillis( + streamingRetrySettings.getInitialRetryDelayDuration(), 1L, Integer.MAX_VALUE); + int maxIntervalMillis = + Math.max( + initialIntervalMillis, + (int) Math.min(effectiveMaxRetryDelayMillis(), Integer.MAX_VALUE)); 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))) + .setInitialIntervalMillis(initialIntervalMillis) + .setMaxIntervalMillis(maxIntervalMillis) // 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 @@ -248,7 +275,8 @@ private static long nextBackOffMillis(BackOff backoff) throws SpannerException { } } - 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 = @@ -261,7 +289,7 @@ private void backoffSleep(Context context, long backoffMillis) throws SpannerExc try { if (backoffMillis == BackOff.STOP) { // Highly unlikely but we handle it just in case. - backoffMillis = streamingRetrySettings.getMaxRetryDelay().toMillis(); + backoffMillis = effectiveMaxRetryDelayMillis(); } if (latch.await(backoffMillis, TimeUnit.MILLISECONDS)) { // Woken by context cancellation. @@ -478,14 +506,19 @@ long checkRetryBudgetAndGetDelay(SpannerException spannerException) { 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. + // Determine the retry delay: use a positive server-supplied retry delay (clamped to the + // effective max retry delay), or fall back to exponential backoff when absent or non-positive. long delayMillis = spannerException.getRetryDelayInMillis(); - if (delayMillis == -1L) { + long maxRetryDelayMillis = effectiveMaxRetryDelayMillis(); + if (delayMillis <= 0L) { if (this.backOff == null) { this.backOff = newBackOff(); } - delayMillis = nextBackOffMillis(this.backOff); + long backOffMillis = nextBackOffMillis(this.backOff); + delayMillis = + backOffMillis == BackOff.STOP ? maxRetryDelayMillis : Math.max(1L, backOffMillis); + } else { + delayMillis = Math.min(delayMillis, maxRetryDelayMillis); } // The total timeout budget applies regardless of whether the delay came from the server // or from the backoff. 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/ResumableStreamIteratorTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ResumableStreamIteratorTest.java index 12a00a990c05..7e3d449a4077 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 @@ -26,6 +26,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.google.api.client.util.BackOff; import com.google.api.core.ApiFuture; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.retrying.RetrySettings; @@ -105,19 +106,33 @@ 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); } + private static BackOff fixedBackOff(long delayMillis) { + return new BackOff() { + @Override + public void reset() {} + + @Override + public long nextBackOffMillis() { + return delayMillis; + } + }; + } + static class RetryableException extends SpannerException { RetryableException(ErrorCode code, @Nullable String message) { // OK to instantiate SpannerException directly for this unit test. @@ -190,13 +205,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 +223,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 +261,15 @@ long nanoTime() { return nanoTime.getAsLong(); } + @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 +570,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(delayMillis); } @Test @@ -565,11 +599,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 +617,304 @@ 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 truncates to 0L in Durations.toMillis and must also use + // exponential backoff rather than spinning at zero delay. + initWithLimit(Integer.MAX_VALUE); + SpannerException subMillisecondException = + new RetryableException( + errorCodeParameter, + "sub-millisecond delay", + statusWithRetryInfo(errorCodeParameter, 0L, 500_000)); + assertEquals(0L, subMillisecondException.getRetryDelayInMillis()); + long subMsBackoff = + resumableStreamIterator.checkRetryBudgetAndGetDelay(subMillisecondException); + assertThat(subMsBackoff).isAtLeast(5L); + assertThat(subMsBackoff).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(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_floorsZeroBackoffToOneMsAndMapsBackOffStopToEffectiveMax() { + SpannerException zeroDelayException = + new RetryableException( + errorCodeParameter, "zero delay", statusWithRetryInfo(errorCodeParameter, 0L, 0)); + SpannerException absentDelayException = + new RetryableException( + errorCodeParameter, + "absent delay", + errorCodeParameter.getGrpcStatus().asRuntimeException()); + + ResumableStreamIterator zeroBackoffIterator = + new FixedBackOffTestIterator(RetrySettings.newBuilder().build(), 0L); + assertEquals(1L, zeroBackoffIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); + assertEquals(1L, zeroBackoffIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + + ResumableStreamIterator stopBackoffUnsetMaxIterator = + new FixedBackOffTestIterator(RetrySettings.newBuilder().build(), BackOff.STOP); + assertEquals( + 32_000L, stopBackoffUnsetMaxIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); + assertEquals( + 32_000L, stopBackoffUnsetMaxIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + + RetrySettings customMaxSettings = + RetrySettings.newBuilder() + .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) + .setMaxRetryDelayDuration(java.time.Duration.ofMillis(250L)) + .build(); + ResumableStreamIterator stopBackoffCustomMaxIterator = + new FixedBackOffTestIterator(customMaxSettings, BackOff.STOP); + assertEquals( + 250L, stopBackoffCustomMaxIterator.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 effectiveMaxRetryDelayAndNewBackOff_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(15L); + + 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 newBackOff_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(48_000L); + maxObserved = Math.max(maxObserved, delayMillis); + } + // Intervals 1, 10, 100, 1000, 10000, 32000 (+/-50% jitter): the 32s ceiling is reached. + assertThat(maxObserved).isAtLeast(16_000L); + } + @Test(timeout = 60000L) public void customTotalTimeoutSmallerThanRetryDelay_doesNotRetry() { // Retrying is only allowed if the retry delay still fits in the remaining total timeout @@ -2977,6 +3315,30 @@ private abstract static class TestResumableStreamIterator extends ResumableStrea } } + private static final class FixedBackOffTestIterator extends TestResumableStreamIterator { + private final long delayMillis; + + FixedBackOffTestIterator(RetrySettings retrySettings, long delayMillis) { + super( + new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false), + retrySettings); + this.delayMillis = delayMillis; + } + + @Override + BackOff newBackOff() { + return fixedBackOff(delayMillis); + } + + @Override + CloseableIterator startStream( + @Nullable ByteString resumeToken, + @Nullable StreamMessageListener streamMessageListener, + XGoogSpannerRequestId requestId) { + throw new AssertionError("unexpected startStream"); + } + } + private static TraceWrapper mockTracerWithSpan(ISpan span) { TraceWrapper tracer = mock(TraceWrapper.class); when(tracer.spanBuilderWithExplicitParent(Mockito.any(), Mockito.any(), Mockito.any())) 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()); From 2c52d5ea1e69b86ca957885f8295fcb6378795d2 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:09:10 +0530 Subject: [PATCH 38/57] fix(spanner): disable built-in Cloud Monitoring metrics for custom non-default hosts without an explicit target (#15252) ## Problem Statement - When configuring a custom non-`*.googleapis.com` Spanner host via `SpannerOptions.Builder.setHost(...)` or a JDBC/Connection URL host or `endpoint` property without setting `universeDomain`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or `SPANNER_MONITORING_HOST`, default-on built-in Cloud Monitoring metrics remained enabled and exported telemetry and credentials to `monitoring.googleapis.com:443`. ## Solution - Automatically disable built-in Cloud Monitoring metrics when a custom non-`*.googleapis.com` host (including malformed or scheme-less hosts) is configured without an explicit `universeDomain`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or `SPANNER_MONITORING_HOST`, logging a warning for non-plaintext, non-emulator clients. - Preserve `toBuilder()` re-evaluation when a caller later sets a universe domain, sets a monitoring host, or clears the custom host, and leave caller-owned `CustomOpenTelemetryMetricsProvider` sinks unaffected. --- java-spanner/.readme-partials.yaml | 2 + java-spanner/README.md | 2 + .../google/cloud/spanner/SpannerOptions.java | 62 ++- .../spanner/BuiltInMetricsBothSinksTest.java | 2 + ...BuiltInMetricsCustomOpenTelemetryTest.java | 97 ++++- .../ChannelPoolBuiltInMetricsTest.java | 4 + .../cloud/spanner/MetricsProviderTest.java | 1 + .../cloud/spanner/SpannerOptionsTest.java | 380 +++++++++++++++++- .../spanner/connection/SpannerPoolTest.java | 72 ++++ 9 files changed, 599 insertions(+), 23 deletions(-) diff --git a/java-spanner/.readme-partials.yaml b/java-spanner/.readme-partials.yaml index c0fe9ba9617c..4fb80df068fb 100644 --- a/java-spanner/.readme-partials.yaml +++ b/java-spanner/.readme-partials.yaml @@ -67,6 +67,8 @@ custom_content: | You can also disable the default Cloud Monitoring export by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. These controls affect only the Cloud Monitoring export. They do not affect a caller-owned client-metrics export configured with `CustomOpenTelemetryMetricsProvider`. + When a custom non-`*.googleapis.com` host is configured via `SpannerOptions.Builder.setHost(...)` (or a JDBC/Connection URL host or `endpoint` property) without setting `setUniverseDomain(...)`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `setMonitoringHost(...)`, or `SPANNER_MONITORING_HOST`, the default Cloud Monitoring export is automatically disabled so telemetry and credentials are not sent to `monitoring.googleapis.com`. + > Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data to Cloud Monitoring. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project. #### Exporting client metrics to OpenTelemetry diff --git a/java-spanner/README.md b/java-spanner/README.md index 98884d88a1be..514f4baf4832 100644 --- a/java-spanner/README.md +++ b/java-spanner/README.md @@ -165,6 +165,8 @@ SpannerOptions options = SpannerOptions.newBuilder() You can also disable the default Cloud Monitoring export by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. These controls affect only the Cloud Monitoring export. They do not affect a caller-owned client-metrics export configured with `CustomOpenTelemetryMetricsProvider`. +When a custom non-`*.googleapis.com` host is configured via `SpannerOptions.Builder.setHost(...)` (or a JDBC/Connection URL host or `endpoint` property) without setting `setUniverseDomain(...)`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `setMonitoringHost(...)`, or `SPANNER_MONITORING_HOST`, the default Cloud Monitoring export is automatically disabled so telemetry and credentials are not sent to `monitoring.googleapis.com`. + > Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data to Cloud Monitoring. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project. #### Exporting client metrics to OpenTelemetry 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 5ac8c191df69..e02de5a9c352 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 @@ -65,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; @@ -1118,6 +1119,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; } @@ -1143,6 +1164,34 @@ 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 @@ -3106,7 +3155,8 @@ public ApiTracerFactory getApiTracerFactory() { /** * Returns the internal OpenTelemetry instance used for built-in metrics, or {@code null} when - * Cloud Monitoring built-in metrics are disabled or no credentials are configured. + * Cloud Monitoring built-in metrics are disabled, no credentials are configured, or it could not + * be initialized. */ @InternalApi @Nullable @@ -3289,9 +3339,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/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..46b0f47fdec8 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; @@ -88,6 +89,7 @@ private Spanner createSpanner(OpenTelemetry customSink) { return 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()) 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 fa217c70f947..dd4cb4b6e27c 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 @@ -177,31 +177,87 @@ public boolean isEnableGRPCBuiltInMetrics() { }); BuiltInMetricsProvider.INSTANCE.reset(); - // Default provider with NoCredentials and built-in metrics enabled must not initialize GCM. - try (Spanner defaultSpanner = - spannerBuilder(DefaultMetricsProvider.INSTANCE) - .setEmulatorHost(null) - .setBuiltInMetricsEnabled(true) - .build() - .getService()) { - executeSelect1(defaultSpanner); + try { + // Default provider with NoCredentials and built-in metrics enabled must not initialize GCM. + try (Spanner defaultSpanner = + spannerBuilder(DefaultMetricsProvider.INSTANCE) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build() + .getService()) { + executeSelect1(defaultSpanner); + } + assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + + // Custom provider with NoCredentials and built-in metrics enabled still records custom + // metrics while leaving the GCM singleton uninitialized. + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); + try { + try (Spanner customSpanner = + spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + .setEmulatorHost(null) + .setBuiltInMetricsEnabled(true) + .build() + .getService()) { + executeSelect1(customSpanner); + } + assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + assertNotNull( + getMetric( + metricReader, + BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME + + "/" + + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); + } finally { + customOpenTelemetry.close(); + } + } finally { + BuiltInMetricsProvider.INSTANCE.reset(); + SpannerOptions.useDefaultEnvironment(); } - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + } - // Custom provider with NoCredentials and built-in metrics enabled still records custom metrics - // while leaving the GCM singleton uninitialized. + @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; + } + }); + BuiltInMetricsProvider.INSTANCE.reset(); InMemoryMetricReader metricReader = InMemoryMetricReader.create(); OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); try { - try (Spanner customSpanner = - spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) + SpannerOptions options = + SpannerOptions.newBuilder() + .setProjectId("my-project") .setEmulatorHost(null) - .setBuiltInMetricsEnabled(true) - .build() - .getService()) { - executeSelect1(customSpanner); + .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 singleton. assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); + assertNull(BuiltInMetricsProvider.INSTANCE.getProjectId()); + + // Caller-owned CustomOpenTelemetryMetricsProvider still records metrics end-to-end. assertNotNull( getMetric( metricReader, @@ -210,6 +266,13 @@ public boolean isEnableGRPCBuiltInMetrics() { + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); } finally { customOpenTelemetry.close(); + BuiltInMetricsProvider.INSTANCE.reset(); + SpannerOptions.useDefaultEnvironment(); + if (previousJmhEnabled == null) { + System.clearProperty("jmh.enabled"); + } else { + System.setProperty("jmh.enabled", previousJmhEnabled); + } } } } 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..88784a17e4a9 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; @@ -349,6 +350,7 @@ public void dynamicPoolReportsDynamicPoolModeAndChannelLoad() { SpannerOptions.newBuilder() .setProjectId("my-project") .setHost(String.format("http://localhost:%d", getPort())) + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) .setChannelConfigurator(ManagedChannelBuilder::usePlaintext) .setCredentials(NoCredentials.getInstance()) .enableGrpcGcpExtension() @@ -420,6 +422,7 @@ 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() @@ -432,6 +435,7 @@ private SpannerOptions createDirectPathFallbackOptions() { .setProjectId("my-project") .setEnableDirectAccess(true) .setHost("http://localhost:1") + .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) .setCredentials(NoCredentials.getInstance()) .enableGrpcGcpExtension() .disableDynamicChannelPool() 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..23573e57f167 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 @@ -67,6 +67,7 @@ public void reset() { private static SpannerOptions.Builder cloudBuilder() { return SpannerOptions.newBuilder() .setProjectId("test-project") + .setEmulatorHost(null) .setCredentials(NoCredentials.getInstance()); } 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 7d7a09bf8390..b2381cf52abf 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 @@ -94,7 +94,9 @@ 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; @@ -1581,6 +1583,7 @@ public void testCustomProviderKeepsCloudMonitoringSinkOnNonOmni() { SpannerOptions options = SpannerOptions.newBuilder() .setProjectId("some-project") + .setEmulatorHost(null) .setCredentials(NoCredentials.getInstance()) .setClientMetricsProvider(provider) .build(); @@ -2883,14 +2886,382 @@ public boolean isEnableGRPCBuiltInMetrics() { }); } + @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, and custom OpenTelemetry instances that {@link - * SpannerOptions} passes to the metrics provider. + * 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( @@ -2918,6 +3289,11 @@ void enableGrpcMetrics( customOpenTelemetries.add(openTelemetry); super.enableGrpcMetrics(channelProviderBuilder, openTelemetry); } + + @Override + synchronized void setProjectIdIfAbsent(String projectId) { + fallbackProjects.add(projectId); + } } private static void useUniverseDomainEnvironment(@Nullable String universeDomain) { 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 79a1bc2138e9..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; @@ -1357,4 +1360,73 @@ public void testSpannerPoolKeyUniverseDomain() { 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(); + } + } } From 9b7ef2bb9a78369872a088c825f27f152e4d1ce7 Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 19:35:09 -0500 Subject: [PATCH 39/57] fix(bigquery-jdbc): record adoption features once per object (#15044) ### What & Why - **Exclude driver-internal calls from usage telemetry:** Route `BigQueryDriver.connect` startup logging, `BigQueryConnection.isValid` health checks, and `BigQueryDatabaseMetaData` internal queries through internal helpers (`getMetaDataInternal`, `createStatementInternal`, `prepareStatementInternal`) so driver housekeeping is not counted as user activity. Synchronize `getMetaDataInternal` so threads sharing a connection initialize and see a single `DatabaseMetaData` instance. - **Deduplicate feature counts and fix batch error status:** Record metadata retrieval and parameter binding once per `Connection`, `ResultSet`, or `PreparedStatement` rather than on every repeated call. In `BigQueryPreparedStatement.executeBatch`, record batch usage on success only and mark Storage Write failures (`SQLException` / `RuntimeException`) as `STATUS_ERROR` instead of `STATUS_UNSPECIFIED`. - **Bound integration test memory:** Cap `maven-failsafe-plugin` Java Virtual Machine (JVM) memory (`-Xmx1536m -XX:MaxDirectMemorySize=1g -XX:+ExitOnOutOfMemoryError`) and reduce `ITStatementTest.testScript` row counts from 500k/700k/900k to 30k/40k/50k (still above the 30k Arrow Read activation threshold) so direct-memory (memory allocated outside the Java heap) spikes fail the offending test with `OutOfMemoryError` instead of killing the build container (exit 137). ### How It Was Tested - **Unit tests (`make unittest`):** Added tests in `BigQueryConnectionTest`, `BigQueryDatabaseMetaDataTest`, `BigQueryDriverTest`, `BigQueryJsonResultSetTest`, `BigQueryPreparedStatementSettersTest`, and `BigQueryStatementTest` covering internal-call exclusion, once-per-object feature counts, concurrent `getMetaData()`, and batch error reporting. - **Integration tests:** `ITStatementTest#testScript` requires Google Cloud credentials and is verified in presubmit. ### Risks / Follow-ups - Presubmit integration tests run in a single forked JVM; if another test exceeds the new 1.5 GB heap or 1 GB direct-memory limit, it will terminate the fork with `OutOfMemoryError` and should be right-sized similarly. --- java-bigquery-jdbc/pom.xml | 17 +- .../bigquery/jdbc/BigQueryBaseResultSet.java | 36 +++-- .../bigquery/jdbc/BigQueryConnection.java | 72 ++++++++- .../jdbc/BigQueryDatabaseMetaData.java | 11 +- .../cloud/bigquery/jdbc/BigQueryDriver.java | 2 +- .../jdbc/BigQueryParameterHandler.java | 40 ++++- .../jdbc/BigQueryPreparedStatement.java | 72 ++++++--- .../bigquery/jdbc/BigQueryStatement.java | 47 +++++- .../jdbc/telemetry/v1/TelemetryManager.java | 10 ++ .../bigquery/jdbc/BigQueryConnectionTest.java | 141 +++++++++++++++++ .../jdbc/BigQueryDatabaseMetaDataTest.java | 64 ++++++-- .../bigquery/jdbc/BigQueryDriverTest.java | 27 +++- .../jdbc/BigQueryJsonResultSetTest.java | 40 +++++ .../BigQueryPreparedStatementSettersTest.java | 145 +++++++++++++++++- .../bigquery/jdbc/BigQueryStatementTest.java | 49 +++++- .../bigquery/jdbc/it/ITStatementTest.java | 18 ++- .../jdbc/telemetry/v1/TelemetryTestUtils.java | 25 +++ 17 files changed, 727 insertions(+), 89 deletions(-) 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 2235166c9d0d..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,7 @@ public int getConcurrency() throws SQLException { @Override public Statement getStatement() throws SQLException { checkClosed(); - if (this.statement == null) { + if (this.statement == null || this.statement.isInternal()) { return null; } Statement proxy = this.statement.getLogicalStatementProxy(); 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 b2fea3a38654..1254b282da1d 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 @@ -87,6 +87,7 @@ 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; @@ -256,7 +257,13 @@ 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; @@ -523,6 +530,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 @@ -899,7 +938,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()) { @@ -1183,13 +1223,31 @@ private static SQLException accumulateException(SQLException current, SQLExcepti @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 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..b34900b1aa63 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 @@ -202,7 +202,7 @@ public Connection connect(String url, Properties info) throws SQLException { ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj); } BigQueryConnection connection = new BigQueryConnection(connectionUri, ds); - DatabaseMetaData metaData = connection.getMetaData(); + DatabaseMetaData metaData = connection.getMetaDataInternal(); LOG.info( "Driver info : { {Database Product Name : %s}, " + "{Database Product Version : %s}, " 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/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 5c813e71b797..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 @@ -92,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; /** @@ -164,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, @@ -174,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(); @@ -473,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); + } } /** @@ -721,7 +762,7 @@ void runQuery(String query, QueryJobConfiguration jobConfiguration) throws SQLEx .setErrorCode(errorCode); } - TelemetryManager.recordStatementExecution(this.currentExecutionBuilder, durationMs); + recordExecution(this.currentExecutionBuilder, durationMs); } } @@ -1833,7 +1874,7 @@ private int[] executeBatchImpl(String combinedQueries) throws SQLException { clearBatch(); - TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); + recordFeature(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS); return result; } 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 18f3bb40baf1..254c7a5e0920 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,6 +25,7 @@ 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; @@ -55,13 +56,20 @@ 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; @@ -80,6 +88,7 @@ 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; @@ -89,10 +98,13 @@ 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; @@ -1304,6 +1316,135 @@ private static JsonObject extractBearerJwtPayload(Credentials credentials, URI u 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); } 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 c932a5e0f7b6..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)); @@ -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..c7202cc103aa 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; @@ -241,15 +242,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 +263,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 +283,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 +294,13 @@ 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))); } } } 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/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/it/ITStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java index 3bc9d5f2003c..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()); } 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(); From c4fe8296135882e353b610e5b4a85b53bc75a90a Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 19:56:19 -0500 Subject: [PATCH 40/57] fix(bigquery-jdbc): harden log file creation with 0600/0700 permissions and symlink checks (#15112) Stack: PR 1 of 6 (base: `main`) Bug: b/584840147 ### Summary Replaces `java.util.logging.FileHandler` in `PerConnectionFileHandler` with a Java New I/O (NIO) `FileChannel` writer (`ChannelLogWriter`) enforcing owner-only POSIX (`0700` directory / `0600` file) permissions, component-by-component symbolic-link and hard-link checks, and graceful error handling. ### Design Decisions - **NIO `FileChannel` (`ChannelLogWriter`) over `java.util.logging.FileHandler`:** Applies `0600` (`rw-------`) atomically via `StandardOpenOption.CREATE_NEW`, avoids `.lck` sidecar files and `%` pattern expansion, and keeps `flush()` as a no-op over unbuffered OS channel writes. - **Path traversal, symlink, UID & hard-link (`nlink == 1`) checks:** Walks every path segment from root with `LinkOption.NOFOLLOW_LINKS`, rejecting target symlinks, non-regular files, hard-linked files (`unix:nlink > 1`), and foreign-owned paths (while allowing root-owned OS ancestor symlinks), and re-verifies attributes post-open. - **Graceful JDBC degradation:** Inaccessible `LogPath` targets report via `java.util.logging` `ErrorManager` without throwing `SQLException` from `DriverManager.getConnection(...)`. --- .../jdbc/BigQueryJdbcCustomLogger.java | 1 + .../jdbc/PerConnectionFileHandler.java | 374 +++++++++++++++--- .../jdbc/PerConnectionFileHandlerTest.java | 163 ++++++++ 3 files changed, 489 insertions(+), 49 deletions(-) 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..2fac95132b28 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 @@ -116,6 +116,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/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index 0b5279cf6bf0..b16bc4f9eec9 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,75 +17,289 @@ package com.google.cloud.bigquery.jdbc; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.SeekableByteChannel; +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.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.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 { + private static final String DEFAULT_HANDLER_ID = "Jdbc-default"; + private static final String GLOBAL_LOG_FILE_NAME = "BQ-JDBC-GLOBAL.log"; + private static final int MAX_CREATE_ATTEMPTS = 16; + 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 final Path baseLogPath; private final Level level; - private final ConcurrentHashMap handlers = new ConcurrentHashMap<>(); - private FileHandler defaultHandler; + private final Formatter logFormatter; + private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); + private final ChannelLogWriter defaultWriter; PerConnectionFileHandler(String baseLogPath, Level level) { - this.baseLogPath = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); this.level = level; + this.logFormatter = BigQueryJdbcRootLogger.getFormatter(); + setLevel(level); + setFormatter(this.logFormatter); + Path initializedDir = null; + ChannelLogWriter initializedDefault = null; try { - if (!Files.exists(this.baseLogPath)) { - Files.createDirectories(this.baseLogPath); + Path candidate = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); + initializedDir = ensureSecureDirectory(candidate); + initializedDefault = createLogWriter(DEFAULT_HANDLER_ID, initializedDir, level); + } catch (Exception e) { + reportError("Failed to initialize default log file", e, ErrorManager.OPEN_FAILURE); + } + this.baseLogPath = initializedDir; + this.defaultWriter = initializedDefault; + } + + 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; + } - this.defaultHandler = createFileHandler("Jdbc-default"); + 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; + } + } + + 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 String getLogFilePath(String id) { - if ("Jdbc-default".equals(id)) { - return baseLogPath.resolve("BQ-JDBC-GLOBAL.log").toString(); + private static int effectiveProcessUid() { + return PROCESS_UID; + } + + 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(); + if (root == null) { + throw new IOException("Cannot resolve root for log path: " + dir); } + boolean isPosix = supportsPosix(root); + 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); + if (isPosix) { + return FileChannel.open(path, opts, FILE_ATTR_0600); + } + return FileChannel.open(path, opts); } - private FileHandler createFileHandler(String id) { + private static FileChannel openSecureGlobalChannel(Path globalPath, boolean isPosix) + 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 openExclusiveNewChannel(globalPath, isPosix); + } catch (FileAlreadyExistsException existing) { + BasicFileAttributes attrs = + Files.readAttributes(globalPath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attrs.isSymbolicLink() || !attrs.isRegularFile() || attrs.isOther()) { + throw new IOException("Refusing non-regular global log file: " + globalPath); + } + if (isPosix) { + verifyPosixOwner(globalPath, false); + Files.setPosixFilePermissions(globalPath, FILE_PERMS_0600); + } + return FileChannel.open( + globalPath, + StandardOpenOption.WRITE, + StandardOpenOption.APPEND, + LinkOption.NOFOLLOW_LINKS); + } + } + + private static FileChannel 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"; + try { + return openExclusiveNewChannel(logDir.resolve(fileName), isPosix); + } 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); + } + + ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { + if (logDir == null) { + return null; + } + try { + Path verifiedDir = ensureSecureDirectory(logDir); + boolean isPosix = supportsPosix(verifiedDir); + SeekableByteChannel channel = + DEFAULT_HANDLER_ID.equals(id) + ? openSecureGlobalChannel(verifiedDir.resolve(GLOBAL_LOG_FILE_NAME), isPosix) + : openConnectionChannel(verifiedDir, id, isPosix); + return new ChannelLogWriter(channel, writerLevel, logFormatter, this); + } catch (Exception e) { + reportError("Failed to create log file for connection " + id, e, ErrorManager.OPEN_FAILURE); return null; } } @Override public void publish(LogRecord record) { - if (!isLoggable(record)) { + if (record == null || !isLoggable(record)) { return; } @@ -96,50 +310,112 @@ public void publish(LogRecord record) { connectionId = (String) params[0]; } } - FileHandler handler = defaultHandler; + ChannelLogWriter target = defaultWriter; - if (connectionId != null && !connectionId.isEmpty()) { - handler = handlers.computeIfAbsent(connectionId, this::createFileHandler); - if (handler == null) { - handler = defaultHandler; + if (connectionId != null && !connectionId.isEmpty() && baseLogPath != null) { + target = + writers.computeIfAbsent(connectionId, id -> createLogWriter(id, baseLogPath, this.level)); + if (target == null) { + target = defaultWriter; } } - if (handler != null) { - handler.publish(record); + if (target != null) { + target.publish(record); } } @Override public void flush() { - if (defaultHandler != null) { - defaultHandler.flush(); - } - for (FileHandler h : handlers.values()) { - h.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()) { + for (ChannelLogWriter writer : writers.values()) { try { - h.close(); - } catch (Exception e) { + writer.close(); + } catch (Exception ignored) { } } try { - if (defaultHandler != null) defaultHandler.close(); + if (defaultWriter != null) { + defaultWriter.close(); + } } finally { - handlers.clear(); + writers.clear(); } } - public void closeHandler(String connectionId) { + void closeHandler(String connectionId) { if (connectionId != null) { - FileHandler handler = handlers.remove(connectionId); - if (handler != null) { - handler.close(); + ChannelLogWriter writer = writers.remove(connectionId); + if (writer != null) { + writer.close(); + } + } + } + + static final class ChannelLogWriter { + private final Object lock = new Object(); + private final Level writerLevel; + private final Formatter formatter; + private final PerConnectionFileHandler owner; + private SeekableByteChannel channel; + private boolean closed; + + ChannelLogWriter( + SeekableByteChannel channel, + Level writerLevel, + Formatter formatter, + PerConnectionFileHandler owner) { + this.channel = channel; + this.writerLevel = writerLevel; + this.formatter = formatter; + this.owner = owner; + } + + void publish(LogRecord record) { + if (record.getLevel().intValue() < writerLevel.intValue()) { + return; + } + String formatted; + try { + formatted = formatter.format(record); + } catch (Exception e) { + owner.reportError("Failed to format log record", e, ErrorManager.FORMAT_FAILURE); + return; + } + byte[] bytes = formatted.getBytes(StandardCharsets.UTF_8); + synchronized (lock) { + if (closed || channel == null) { + return; + } + try { + ByteBuffer buf = ByteBuffer.wrap(bytes); + while (buf.hasRemaining()) { + channel.write(buf); + } + } catch (IOException e) { + owner.reportError("Failed to write log record", e, ErrorManager.WRITE_FAILURE); + } + } + } + + void close() { + synchronized (lock) { + if (closed) { + return; + } + closed = true; + if (channel != null) { + try { + channel.close(); + } catch (IOException e) { + owner.reportError("Failed to close log file", e, ErrorManager.CLOSE_FAILURE); + } + channel = null; + } } } } 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..55d4cf54a265 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,37 @@ 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.StandardSQLTypeName; 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.SQLException; import java.sql.Statement; +import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.Future; +import java.util.logging.ErrorManager; 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; @@ -221,4 +234,154 @@ 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 { + 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 { + 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)); + } 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(); + } + } } From 5ae95587b55ad356d52828bcfe8bf8b7e59ce583 Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 20:17:25 -0500 Subject: [PATCH 41/57] fix(bigquery-jdbc): add cross-process global log lock fallback and interrupt recovery (#15253) Stack: PR 2 of 6 (base: `fix/bq-jdbc-log-file-hardening`) Bug: b/584840147 ### Summary Adds in-JVM and cross-process sentinel locking on `BQ-JDBC-GLOBAL.log` with collision-free fallback file allocation and `ClosedByInterruptException` channel recovery in `PerConnectionFileHandler`. ### Design Decisions - **In-JVM + cross-process global log coordination:** Tracks active canonical global paths in `ACTIVE_GLOBAL_PATHS` and acquires a non-blocking 1-byte sentinel lock (`FileChannel.tryLock(Long.MAX_VALUE - 1, 1L, false)`), falling back to an exclusive `BQ-JDBC-GLOBAL--<4hex>.log` file on contention. - **Interrupt-safe channel writes & recovery:** Preserves the calling thread's interrupt status in `finally` around NIO channel opens and writes and reopens validated channels after `ClosedByInterruptException`. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 5 +- .../jdbc/PerConnectionFileHandler.java | 284 +++++++++++++++--- .../jdbc/PerConnectionFileHandlerTest.java | 117 +++++++- 3 files changed, 361 insertions(+), 45 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 518110948b9b..21a7fc1f426b 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -699,7 +699,10 @@ 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` when another process or handler already holds the global log lock, or when `BQ-JDBC-GLOBAL.log` is owned by a different OS user). +- **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. **Standard Log Record Format**: ```text 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 b16bc4f9eec9..5647f38c0ce7 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 @@ -18,7 +18,10 @@ 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.channels.SeekableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.FileAlreadyExistsException; @@ -40,6 +43,7 @@ import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; import java.util.logging.ErrorManager; import java.util.logging.Formatter; import java.util.logging.Handler; @@ -54,7 +58,10 @@ class PerConnectionFileHandler extends Handler { 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 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_-]"); @@ -68,12 +75,15 @@ class PerConnectionFileHandler extends Handler { PosixFilePermissions.asFileAttribute(FILE_PERMS_0600); private static final int PROCESS_UID = resolveProcessUid(); private static final UserPrincipal PROCESS_PRINCIPAL = resolveProcessPrincipal(); + static volatile Integer overrideUidForTesting; private final Path baseLogPath; private final Level level; private final Formatter logFormatter; private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); - private final ChannelLogWriter defaultWriter; + private final Object defaultWriterLock = new Object(); + private ChannelLogWriter defaultWriter; + private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { this.level = level; @@ -82,16 +92,13 @@ class PerConnectionFileHandler extends Handler { setFormatter(this.logFormatter); Path initializedDir = null; - ChannelLogWriter initializedDefault = null; try { Path candidate = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); initializedDir = ensureSecureDirectory(candidate); - initializedDefault = createLogWriter(DEFAULT_HANDLER_ID, initializedDir, level); } catch (Exception e) { reportError("Failed to initialize default log file", e, ErrorManager.OPEN_FAILURE); } this.baseLogPath = initializedDir; - this.defaultWriter = initializedDefault; } private static int resolveProcessUid() { @@ -137,7 +144,19 @@ private static boolean supportsPosix(Path path) { } private static int effectiveProcessUid() { - return PROCESS_UID; + 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 static void verifyPosixOwner(Path path, boolean allowRootOwner) throws IOException { @@ -239,29 +258,108 @@ private static FileChannel openExclusiveNewChannel(Path path, boolean isPosix) return FileChannel.open(path, opts); } - private static FileChannel openSecureGlobalChannel(Path globalPath, boolean isPosix) - throws IOException { + 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 { - return openExclusiveNewChannel(globalPath, isPosix); - } catch (FileAlreadyExistsException existing) { - BasicFileAttributes attrs = - Files.readAttributes(globalPath, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (attrs.isSymbolicLink() || !attrs.isRegularFile() || attrs.isOther()) { - throw new IOException("Refusing non-regular global log file: " + globalPath); + 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(globalPath, false); - Files.setPosixFilePermissions(globalPath, FILE_PERMS_0600); + verifyPosixOwner(path, false); + verifySingleLinkCount(path); } - return FileChannel.open( - globalPath, - StandardOpenOption.WRITE, - StandardOpenOption.APPEND, - LinkOption.NOFOLLOW_LINKS); + return fc; + } catch (IOException | RuntimeException e) { + try { + fc.close(); + } catch (IOException suppressed) { + e.addSuppressed(suppressed); + } + throw e; } } - private static FileChannel openConnectionChannel(Path logDir, String id, boolean isPosix) + private static FileLock tryAcquireSentinelLock(FileChannel fc) throws IOException { + try { + 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); @@ -270,8 +368,10 @@ private static FileChannel openConnectionChannel(Path logDir, String id, boolean attempt == 0 ? "BQ-JDBC-" + timestamp + "-" + shortUuid + ".log" : "BQ-JDBC-" + timestamp + "-" + attempt + "-" + shortUuid + ".log"; + Path candidate = logDir.resolve(fileName); try { - return openExclusiveNewChannel(logDir.resolve(fileName), isPosix); + 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. } @@ -286,20 +386,32 @@ ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { try { Path verifiedDir = ensureSecureDirectory(logDir); boolean isPosix = supportsPosix(verifiedDir); - SeekableByteChannel channel = + OpenedLogFile opened = DEFAULT_HANDLER_ID.equals(id) - ? openSecureGlobalChannel(verifiedDir.resolve(GLOBAL_LOG_FILE_NAME), isPosix) + ? openGlobalChannel(verifiedDir, isPosix) : openConnectionChannel(verifiedDir, id, isPosix); - return new ChannelLogWriter(channel, writerLevel, logFormatter, this); + return new ChannelLogWriter(opened, isPosix, writerLevel, logFormatter, this); } catch (Exception e) { reportError("Failed to create log file for connection " + id, e, ErrorManager.OPEN_FAILURE); return null; } } + private ChannelLogWriter getOrCreateDefaultWriter() { + synchronized (defaultWriterLock) { + if (handlerClosed || baseLogPath == null) { + return null; + } + if (defaultWriter == null) { + defaultWriter = createLogWriter(DEFAULT_HANDLER_ID, baseLogPath, level); + } + return defaultWriter; + } + } + @Override public void publish(LogRecord record) { - if (record == null || !isLoggable(record)) { + if (handlerClosed || record == null || !isLoggable(record)) { return; } @@ -310,17 +422,17 @@ public void publish(LogRecord record) { connectionId = (String) params[0]; } } - ChannelLogWriter target = defaultWriter; + ChannelLogWriter target = null; if (connectionId != null && !connectionId.isEmpty() && baseLogPath != null) { target = writers.computeIfAbsent(connectionId, id -> createLogWriter(id, baseLogPath, this.level)); - if (target == null) { - target = defaultWriter; - } + } + if (target == null) { + target = getOrCreateDefaultWriter(); } - if (target != null) { + if (!handlerClosed && target != null) { target.publish(record); } } @@ -332,6 +444,7 @@ public void flush() { @Override public void close() throws SecurityException { + handlerClosed = true; for (ChannelLogWriter writer : writers.values()) { try { writer.close(); @@ -339,8 +452,11 @@ public void close() throws SecurityException { } } try { - if (defaultWriter != null) { - defaultWriter.close(); + synchronized (defaultWriterLock) { + if (defaultWriter != null) { + defaultWriter.close(); + defaultWriter = null; + } } } finally { writers.clear(); @@ -356,25 +472,72 @@ void closeHandler(String connectionId) { } } + 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 Object lock = new Object(); + private final Path filePath; + private final boolean isPosix; + private final Path globalClaimKey; private final Level writerLevel; private final Formatter formatter; private final PerConnectionFileHandler owner; private SeekableByteChannel channel; + private FileLock fileLock; private boolean closed; ChannelLogWriter( - SeekableByteChannel channel, + OpenedLogFile opened, + boolean isPosix, Level writerLevel, Formatter formatter, PerConnectionFileHandler owner) { - this.channel = channel; + this.filePath = opened.path; + this.channel = opened.channel; + this.fileLock = opened.lock; + this.globalClaimKey = opened.globalClaimKey; + this.isPosix = isPosix; this.writerLevel = writerLevel; this.formatter = formatter; this.owner = owner; } + 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; + } + void publish(LogRecord record) { if (record.getLevel().intValue() < writerLevel.intValue()) { return; @@ -391,13 +554,35 @@ void publish(LogRecord record) { if (closed || channel == null) { return; } + boolean interrupted = false; try { - ByteBuffer buf = ByteBuffer.wrap(bytes); - while (buf.hasRemaining()) { - channel.write(buf); + for (int attempt = 0; attempt < MAX_REOPEN_ATTEMPTS; attempt++) { + interrupted |= Thread.interrupted(); + try { + if (!channel.isOpen()) { + reopenAfterInterrupt(); + } + ByteBuffer buf = ByteBuffer.wrap(bytes); + while (buf.hasRemaining()) { + channel.write(buf); + } + return; + } 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; + } + } } } catch (IOException e) { owner.reportError("Failed to write log record", e, ErrorManager.WRITE_FAILURE); + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } } } @@ -408,13 +593,26 @@ void close() { return; } closed = true; - if (channel != null) { - try { - channel.close(); - } catch (IOException e) { - owner.reportError("Failed to close log file", e, ErrorManager.CLOSE_FAILURE); + 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); + } } } } 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 55d4cf54a265..f60f5618f27c 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 @@ -91,7 +91,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 @@ -253,6 +253,7 @@ public void testPosixOwnerOnlyPermissionsOnCreatedDirsAndFiles() throws IOExcept 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")); @@ -293,6 +294,7 @@ public void testCreateDirectoryUnderSharedNonSymlinkAncestor() throws IOExceptio 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)); @@ -354,6 +356,11 @@ public void testSymbolicLinksAndNonRegularPathsAreRejected() throws IOException 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(); } @@ -384,4 +391,112 @@ public void testPercentTokensCollisionSuffixesAndNoLockFiles() throws IOExceptio 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")); + } } From a756d9232b98b221dce4f072482b2cf7c81b45ec Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 20:55:11 -0500 Subject: [PATCH 42/57] fix(bigquery-jdbc): add 1 GiB log file rotation and truncation fallback (#15165) Stack: PR 3 of 6 (base: `fix/bq-jdbc-log-lock-and-interrupt`) Bug: b/584840147 ### Summary Adds bounded 1 GiB log file size rotation onto a single `.1.log` (`0600`) backup file with in-place truncation fallback in `PerConnectionFileHandler`. ### Environment Variables & System Properties - **Added System Property:** `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=` (default: `1073741824` / 1 GiB). Documented in `docs/USER_GUIDE.md`. ### Design Decisions - **1 GiB cap + single `.1.log` (`0600`) backup rotation:** Validates `.1.log` with `NOFOLLOW_LINKS` (deleting any symlink without following it), atomically rotates active logs to `.1.log`, and opens a fresh `0600` active channel while preserving global sentinel locks. - **In-place truncation fallback:** Falls back to `channel.truncate(0)` when backup rotation is blocked. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 1 + .../jdbc/PerConnectionFileHandler.java | 213 ++++++++++++++++-- .../jdbc/PerConnectionFileHandlerTest.java | 161 +++++++++++++ 3 files changed, 355 insertions(+), 20 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 21a7fc1f426b..966ce4897e03 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -703,6 +703,7 @@ Log files are generated inside the specified `LogPath` directory with per-connec - **Global log file**: `BQ-JDBC-GLOBAL.log` (or `BQ-JDBC-GLOBAL--.log` when another process or handler already holds the global log lock, or when `BQ-JDBC-GLOBAL.log` is owned by a different OS user). - **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). **Standard Log Record Format**: ```text 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 5647f38c0ce7..a6aa537c06fa 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 @@ -22,7 +22,6 @@ import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; -import java.nio.channels.SeekableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystems; @@ -30,6 +29,7 @@ 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; @@ -56,6 +56,9 @@ * 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; @@ -79,6 +82,7 @@ class PerConnectionFileHandler extends Handler { private final Path baseLogPath; private final Level level; + private final long maxFileBytes; private final Formatter logFormatter; private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); private final Object defaultWriterLock = new Object(); @@ -86,7 +90,12 @@ class PerConnectionFileHandler extends Handler { private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { + this(baseLogPath, level, resolveMaxLogFileBytes()); + } + + PerConnectionFileHandler(String baseLogPath, Level level, long maxFileBytes) { this.level = level; + this.maxFileBytes = maxFileBytes <= 0L ? DEFAULT_MAX_LOG_FILE_BYTES : maxFileBytes; this.logFormatter = BigQueryJdbcRootLogger.getFormatter(); setLevel(level); setFormatter(this.logFormatter); @@ -101,6 +110,21 @@ class PerConnectionFileHandler extends Handler { this.baseLogPath = initializedDir; } + static long resolveMaxLogFileBytes() { + String raw = System.getProperty(MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY); + if (raw != null && !raw.trim().isEmpty()) { + try { + long parsed = Long.parseLong(raw.trim()); + if (parsed > 0L) { + return parsed; + } + } catch (NumberFormatException ignored) { + // Fall back to 1 GiB default on invalid property value. + } + } + return DEFAULT_MAX_LOG_FILE_BYTES; + } + private static int resolveProcessUid() { Path procSelfStatus = Paths.get("/proc/self/status"); if (Files.isReadable(procSelfStatus)) { @@ -379,10 +403,44 @@ private static OpenedLogFile openConnectionChannel(Path logDir, String id, boole throw new IOException("Unable to allocate unique log file for connection " + id); } - ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { + 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 { Path verifiedDir = ensureSecureDirectory(logDir); boolean isPosix = supportsPosix(verifiedDir); @@ -390,10 +448,15 @@ ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { DEFAULT_HANDLER_ID.equals(id) ? openGlobalChannel(verifiedDir, isPosix) : openConnectionChannel(verifiedDir, id, isPosix); - return new ChannelLogWriter(opened, isPosix, writerLevel, logFormatter, this); + 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(); + } } } @@ -403,7 +466,7 @@ private ChannelLogWriter getOrCreateDefaultWriter() { return null; } if (defaultWriter == null) { - defaultWriter = createLogWriter(DEFAULT_HANDLER_ID, baseLogPath, level); + defaultWriter = createLogWriter(DEFAULT_HANDLER_ID, baseLogPath, level, this.maxFileBytes); } return defaultWriter; } @@ -422,18 +485,29 @@ public void publish(LogRecord record) { connectionId = (String) params[0]; } } + boolean usedConnectionWriter = false; ChannelLogWriter target = null; if (connectionId != null && !connectionId.isEmpty() && baseLogPath != null) { target = - writers.computeIfAbsent(connectionId, id -> createLogWriter(id, baseLogPath, this.level)); + writers.computeIfAbsent( + connectionId, id -> createLogWriter(id, baseLogPath, this.level, this.maxFileBytes)); + usedConnectionWriter = (target != null); } if (target == null) { target = getOrCreateDefaultWriter(); } - if (!handlerClosed && target != null) { - target.publish(record); + if (!handlerClosed && target != null && !target.publish(record)) { + if (usedConnectionWriter) { + writers.remove(connectionId, target); + } else { + synchronized (defaultWriterLock) { + if (defaultWriter == target) { + defaultWriter = null; + } + } + } } } @@ -488,30 +562,42 @@ static final class OpenedLogFile { static final class ChannelLogWriter { private final Object lock = new Object(); - private final Path filePath; + private final String id; + private final Path logDir; private final boolean isPosix; - private final Path globalClaimKey; private final Level writerLevel; + private final long maxBytes; private final Formatter formatter; private final PerConnectionFileHandler owner; - private SeekableByteChannel channel; + 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) { + 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 { @@ -536,54 +622,140 @@ private void reopenAfterInterrupt() throws IOException { } 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 (isPosix) { + verifyPosixOwner(backupPath, false); + verifySingleLinkCount(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(); } - void publish(LogRecord record) { + private void truncateInPlace() throws IOException { + if (channel == null || !channel.isOpen()) { + reopenAfterInterrupt(); + } + channel.truncate(0L); + channel.position(0L); + writtenBytes = 0L; + } + + boolean publish(LogRecord record) { if (record.getLevel().intValue() < writerLevel.intValue()) { - return; + return true; } String formatted; try { formatted = formatter.format(record); } catch (Exception e) { owner.reportError("Failed to format log record", e, ErrorManager.FORMAT_FAILURE); - return; + return true; } byte[] bytes = formatted.getBytes(StandardCharsets.UTF_8); synchronized (lock) { - if (closed || channel == null) { - return; + if (closed) { + return false; } boolean interrupted = false; try { for (int attempt = 0; attempt < MAX_REOPEN_ATTEMPTS; attempt++) { interrupted |= Thread.interrupted(); try { - if (!channel.isOpen()) { + 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(); + } + } ByteBuffer buf = ByteBuffer.wrap(bytes); while (buf.hasRemaining()) { - channel.write(buf); + writtenBytes += channel.write(buf); } - return; + 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; + 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; } } @@ -612,6 +784,7 @@ void close() { channel = null; if (globalClaimKey != null) { ACTIVE_GLOBAL_PATHS.remove(globalClaimKey); + globalClaimKey = null; } } } 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 f60f5618f27c..80b003c2f1a1 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 @@ -499,4 +499,165 @@ public void testInterruptedPublishPreservesInterruptFlagAndKeepsChannelAlive() 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 testOneGibDefaultAndBackupFileRotation() throws IOException { + 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()); + } finally { + if (prev == null) { + System.clearProperty(prop); + } else { + System.setProperty(prop, prev); + } + } + + Path boundedDir = tempDir.resolve("bounded"); + long maxBytes = 1024L; + PerConnectionFileHandler defaultMaxHandler = + new PerConnectionFileHandler(tempDir.resolve("def_max").toString(), Level.INFO, 0L); + defaultMaxHandler.close(); + + 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.registerInstance("BQ-JDBC-rotc1234"); + for (int i = 0; i < 15; i++) { + boundedHandler.publish(new LogRecord(Level.INFO, "Per-conn rotation line #" + i)); + } + BigQueryJdbcMdc.clear(); + boundedHandler.publish(new LogRecord(Level.FINEST, "Tail global record")); + } 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()); + + 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)); + + // Symlink at .1.log is deleted safely without modifying target; foreign UID falls back + 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"))); + + PerConnectionFileHandler.overrideUidForTesting = 888_888_888; + try { + for (int i = 0; i < 12; i++) { + symRotHandler.publish(new LogRecord(Level.INFO, "Foreign backup fallback line #" + i)); + } + } finally { + PerConnectionFileHandler.overrideUidForTesting = null; + } + assertTrue( + new String( + Files.readAllBytes(symDir.resolve("BQ-JDBC-GLOBAL.log")), + StandardCharsets.UTF_8) + .contains("fallback line #11")); + } finally { + symRotHandler.close(); + } + } + + // Non-regular directory blocking .1.log falls back gracefully to in-place truncation + 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); + assertTrue( + new String(Files.readAllBytes(fallbackGlobal), StandardCharsets.UTF_8).contains("cap #19")); + } + + @Test + public void testClosedWriterOnRotationFailureEvictsAndRecovers() throws IOException { + Path recoverDir = tempDir.resolve("recover_rot"); + PerConnectionFileHandler recoverHandler = + new PerConnectionFileHandler(recoverDir.toString(), Level.INFO, 512L); + recoverHandler.setErrorManager(silentErrorManager()); + try { + BigQueryJdbcMdc.registerInstance("BQ-JDBC-rcvr1234"); + 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(); + } + } } From 718e941d7ff1f1778dc7ee4da42a46f1da59b8e5 Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 21:27:12 -0500 Subject: [PATCH 43/57] fix(bigquery-jdbc): replace String log parameter routing with typed ConnectionLogContext (#15254) Stack: PR 4 of 6 (base: `fix/bq-jdbc-log-rotation-and-context`) Bug: b/584840147 ### Summary Replaces raw `String` `LogRecord.getParameters()[0]` connection-ID stamping with a package-private typed `ConnectionLogContext` carrier across `BigQueryJdbcResultSetLogger`, `BigQueryJdbcRootLogger`, `PerConnectionFileHandler`, and `OpenTelemetryJulHandler`. ### Design Decisions - **Collision-free parameter routing:** Arbitrary `String` parameters at `params[0]` can no longer be misinterpreted as connection IDs or spawn unintended `BQ-JDBC-*-.log` files when MDC is empty. - **OpenTelemetry `MessageFormat` compatibility:** `OpenTelemetryJulHandler` strips `ConnectionLogContext` at `params[0]` before positional message formatting. --- .../jdbc/BigQueryJdbcResultSetLogger.java | 47 ++++++++----- .../bigquery/jdbc/BigQueryJdbcRootLogger.java | 6 +- .../bigquery/jdbc/ConnectionLogContext.java | 66 +++++++++++++++++++ .../jdbc/OpenTelemetryJulHandler.java | 47 ++++++++++--- .../jdbc/PerConnectionFileHandler.java | 6 +- .../jdbc/BigQueryJdbcCustomLoggerTest.java | 15 +++-- .../jdbc/OpenTelemetryJulHandlerTest.java | 57 +++++++++++++++- .../jdbc/PerConnectionFileHandlerTest.java | 23 +++++-- 8 files changed, 226 insertions(+), 41 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java 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..30a236d03476 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, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE)); + } + + 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() { @@ -92,46 +104,49 @@ public boolean isLoggable(Level level) { 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) { + 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); } 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..0f1c7ab269e4 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 @@ -104,9 +104,9 @@ public String format(LogRecord record) { String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis())); 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) { + connectionId = context.connectionId(); } } String connStr = 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..073b2333a72b --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java @@ -0,0 +1,66 @@ +/* + * 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.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 volatile int levelValue; + + ConnectionLogContext(String connectionId, int levelValue) { + this.connectionId = Objects.requireNonNull(connectionId, "connectionId cannot be null"); + this.levelValue = levelValue; + } + + String connectionId() { + return connectionId; + } + + int levelValue() { + return levelValue; + } + + void setLevelValue(int levelValue) { + this.levelValue = 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; + } +} 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..def2569efd0f 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; @@ -63,6 +65,13 @@ public void publish(LogRecord record) { connectionId = BigQueryJdbcMdc.getConnectionId(); } + if (connectionId == null || connectionId.isEmpty()) { + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context != null) { + connectionId = context.connectionId(); + } + } + if (connectionId == null || connectionId.isEmpty()) { return; } @@ -97,8 +106,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 +145,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 +178,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 a6aa537c06fa..bcc63418f542 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 @@ -480,9 +480,9 @@ public void publish(LogRecord record) { 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) { + connectionId = context.connectionId(); } } boolean usedConnectionWriter = false; 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..3e7233fa4eb6 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 @@ -335,7 +335,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,14 +363,16 @@ 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); @@ -394,7 +399,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); 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..5896cf81be72 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; @@ -120,15 +123,63 @@ 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()); } } 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 80b003c2f1a1..d102a71149cc 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 @@ -537,6 +537,14 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { 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 { @@ -544,12 +552,18 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { boundedHandler.publish( new LogRecord(Level.INFO, "Padding log line to exceed 1 KiB limit #" + i)); } - BigQueryJdbcMdc.registerInstance("BQ-JDBC-rotc1234"); + // Route via ConnectionLogContext in params[0] with empty MDC and trigger per-conn .1.log + BigQueryJdbcMdc.clear(); for (int i = 0; i < 15; i++) { - boundedHandler.publish(new LogRecord(Level.INFO, "Per-conn rotation line #" + i)); + LogRecord ctxRec = new LogRecord(Level.INFO, "Per-conn rotation line #" + i); + ctxRec.setParameters(new Object[] {connCtx}); + boundedHandler.publish(ctxRec); } - BigQueryJdbcMdc.clear(); - boundedHandler.publish(new LogRecord(Level.FINEST, "Tail global record")); + // Plain String in params[0] with empty MDC routes to global log instead of "-BigQ.log" + 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(); } @@ -561,6 +575,7 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { 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-------"); From 35ae16b859ee995aaaa314dcb5d29a9621e36447 Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 22:47:02 -0500 Subject: [PATCH 44/57] fix(bigquery-jdbc): isolate per-connection log levels, directories, and pre-connect routing (#15168) Stack: PR 5 of 6 (base: `fix/bq-jdbc-connection-log-context`) Bug: b/584840083 ### Summary Isolates per-connection `LogLevel` and `LogPath` configurations using reference-counted per-directory `ManagedFileHandler` instances, pre-connect global log scoping (`openPreConnectScope`), and `ConnectionLogContext` propagation through `BigQueryJdbcMdc` and `OpenTelemetryJulHandler`. ### Design Decisions - **Reference-counted per-directory `ManagedFileHandler`s:** Concurrent connections maintain independent thresholds and directories without closing sibling handlers or detaching `OpenTelemetryJulHandler`. - **Scoped pre-connect routing (`openPreConnectScope`):** Routes pre-UUID connection diagnostics to the target `LogPath`s `BQ-JDBC-GLOBAL.log` and releases handlers deterministically. - **Thread-pool & OTel per-connection level isolation:** Propagates `ConnectionLogContext` across `BigQueryJdbcMdc` executors and enforces per-connection level thresholds in `OpenTelemetryJulHandler`. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 2 +- .../bigquery/jdbc/BigQueryConnection.java | 18 ++ .../cloud/bigquery/jdbc/BigQueryDriver.java | 59 ++-- .../jdbc/BigQueryJdbcCustomLogger.java | 15 + .../cloud/bigquery/jdbc/BigQueryJdbcMdc.java | 56 ++-- .../jdbc/BigQueryJdbcResultSetLogger.java | 27 +- .../bigquery/jdbc/BigQueryJdbcRootLogger.java | 264 +++++++++++++++--- .../bigquery/jdbc/ConnectionLogContext.java | 48 +++- .../jdbc/OpenTelemetryJulHandler.java | 22 +- .../jdbc/PerConnectionFileHandler.java | 90 +++++- .../jdbc/BigQueryJdbcLoggingBaseTest.java | 8 +- .../jdbc/BigQueryJdbcRootLoggerTest.java | 180 ++++++++++++ .../jdbc/OpenTelemetryJulHandlerTest.java | 25 ++ 13 files changed, 701 insertions(+), 113 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 966ce4897e03..9cbc6b9a330b 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -700,7 +700,7 @@ 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: -- **Global log file**: `BQ-JDBC-GLOBAL.log` (or `BQ-JDBC-GLOBAL--.log` when another process or handler already holds the global log lock, or when `BQ-JDBC-GLOBAL.log` is owned by a different OS user). +- **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). 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 1254b282da1d..1d9f846c7600 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 @@ -290,6 +290,19 @@ 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 = ds.getLogPath(); + if (connLogPath == null) { + connLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); + } + if (connLogPath == null && rawLogLevel != null && !ds.getEnableGcpLogExporter()) { + connLogPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH; + } + BigQueryJdbcRootLogger.registerConnection(this.connectionId, rawLogLevel, connLogPath); + boolean initialized = false; try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { this.connectionUrl = url; if (LOG.isLoggable(Level.CONFIG)) { @@ -437,6 +450,11 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { this.metadataExecutor = BigQueryJdbcMdc.newFixedThreadPool( String.format("BQ-Metadata-%s", connectionId), this.metadataFetchThreadCount); + initialized = true; + } finally { + if (!initialized) { + BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); + } } } 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 b34900b1aa63..ec787b377253 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 @@ -190,34 +190,41 @@ 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)) { + 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.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()); Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class); 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 2fac95132b28..bca84a28c02a 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 @@ -32,6 +32,21 @@ public BigQueryJdbcCustomLogger(String name) { this(name, null); } + @Override + public boolean isLoggable(Level level) { + if (level == null || level == Level.OFF) { + return false; + } + if (this.getLevel() != null) { + return super.isLoggable(level); + } + ConnectionLogContext context = BigQueryJdbcMdc.getConnectionContext(); + if (context != null && context.hasExplicitLevel()) { + return context.isLoggable(level); + } + return super.isLoggable(level); + } + private void logWithCaller(Level level, Supplier msgSupplier) { logWithCaller(level, null, msgSupplier); } 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 09e25b4f673f..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,7 +33,7 @@ class BigQueryJdbcMdc { private static final BigQueryJdbcCustomLogger LOG = new BigQueryJdbcCustomLogger(BigQueryJdbcMdc.class.getName()); - private static final InheritableThreadLocal currentConnectionId = + private static final InheritableThreadLocal currentContext = new InheritableThreadLocal<>(); /** @@ -41,30 +41,46 @@ class BigQueryJdbcMdc { * context when closed. */ static MdcCloseable registerInstance(String connectionId) { - String previousConnectionId = currentConnectionId.get(); - 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 { - clear(); + currentContext.remove(); } return () -> { - if (previousConnectionId != null) { - currentConnectionId.set(previousConnectionId); + if (previous != null) { + currentContext.set(previous); } else { - clear(); + 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(); } /** @@ -191,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(); } }; @@ -210,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/BigQueryJdbcResultSetLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java index 30a236d03476..fa1831c01576 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 @@ -74,7 +74,11 @@ public static BigQueryJdbcResultSetLogger getLogger(Class clazz, String conne if (connectionId == null || connectionId.isEmpty()) { return getLogger(clazz, (ConnectionLogContext) null); } - return getLogger(clazz, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE)); + ConnectionLogContext context = BigQueryJdbcRootLogger.getConnectionContext(connectionId); + if (context == null) { + context = ConnectionLogContext.unregistered(connectionId); + } + return getLogger(clazz, context); } static BigQueryJdbcResultSetLogger getLogger( @@ -99,6 +103,15 @@ BigQueryJdbcCustomLogger delegate() { } public boolean isLoggable(Level level) { + if (level == null || level == Level.OFF) { + return false; + } + if (delegate.getLevel() != null) { + return delegate.isLoggable(level); + } + if (connectionContext != null && connectionContext.hasExplicitLevel()) { + return connectionContext.isLoggable(level); + } return delegate.isLoggable(level); } @@ -137,7 +150,7 @@ public BigQueryJdbcResultSetLogger getJsonArrayLogger() { * BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily. */ public void log(LogRecord record) { - if (record == null) { + if (record == null || !isLoggable(record.getLevel())) { return; } if (connectionContext != null) { @@ -150,12 +163,16 @@ public void log(LogRecord record) { System.arraycopy(existingParams, 0, newParams, 1, existingParams.length); record.setParameters(newParams); } + 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); @@ -165,7 +182,7 @@ 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()); @@ -173,7 +190,7 @@ private void logTrace(Level level, String methodName, Supplier msgSuppli /** 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); 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 0f1c7ab269e4..65968510b987 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,13 +21,20 @@ 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.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.logging.ConsoleHandler; import java.util.logging.Formatter; -import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; @@ -44,7 +51,13 @@ class BigQueryJdbcRootLogger { 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 Object HANDLER_LOCK = new Object(); + private static final ConcurrentHashMap activeConnections = + new ConcurrentHashMap<>(); + private static final Map handlersByPath = new HashMap<>(); + 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]; @@ -102,12 +115,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()) { - ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); - if (context != null) { - connectionId = context.connectionId(); - } + connectionId = BigQueryJdbcMdc.getConnectionId(); } String connStr = (connectionId != null && !connectionId.isEmpty()) ? connectionId : "NO_CONN"; @@ -148,8 +159,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 +173,231 @@ 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; + } + public static void setLevel(Level level, String logPath) throws IOException { - if (level != Level.OFF) { - if (logPath != null) { - setPath(logPath, level); + synchronized (HANDLER_LOCK) { + externalRootLevel = null; + updateEffectiveRootLevelLocked(); + } + } + + static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logPath) { + Level effectiveLevel = level != null ? level : Level.OFF; + ManagedFileHandler tempHandler = null; + boolean countedScope = false; + synchronized (HANDLER_LOCK) { + if (effectiveLevel != Level.OFF) { + activePreConnectScopes++; + countedScope = true; + if (logPath != null) { + try { + tempHandler = acquireHandlerLocked(logPath); + } catch (Exception ex) { + logger.warning("Log File warning : " + ex); + } + } + } + updateEffectiveRootLevelLocked(); + } + 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) { + synchronized (HANDLER_LOCK) { + if (decrementScope && activePreConnectScopes > 0) { + activePreConnectScopes--; + } + releaseHandlerLocked(acquired); + updateEffectiveRootLevelLocked(); + } + } } - } 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; + } + synchronized (HANDLER_LOCK) { + captureExternalRootLevelLocked(); + Level connLevel = + rawLogLevel != null + ? BigQueryJdbcUrlUtility.parseLogLevel(rawLogLevel) + : (externalRootLevel != null ? externalRootLevel : Level.OFF); + if (connLevel == null) { + connLevel = Level.OFF; + } + ManagedFileHandler managed = null; + if (connLevel != Level.OFF && logPath != null) { + try { + managed = acquireHandlerLocked(logPath); + managed.handler.registerConnection(connectionId, connLevel); + } catch (Exception ex) { + logger.warning("Log File warning : " + ex); + } + } + ConnectionLogConfig previous = + activeConnections.put( + connectionId, + new ConnectionLogConfig( + new ConnectionLogContext(connectionId, connLevel.intValue()), + connLevel, + managed)); + if (previous != null && previous.managedHandler != null) { + previous.managedHandler.handler.closeHandler(connectionId); + releaseHandlerLocked(previous.managedHandler); } - fileHandler = null; + updateEffectiveRootLevelLocked(); } - logger.setLevel(level); } - static void setPath(String logPath, Level level) { - try { - if (logPath == null) { - logPath = ""; + public static void closeConnectionHandler(String connectionId) { + if (connectionId == null) { + return; + } + synchronized (HANDLER_LOCK) { + captureExternalRootLevelLocked(); + ConnectionLogConfig removed = activeConnections.remove(connectionId); + if (removed != null && removed.managedHandler != null) { + try { + removed.managedHandler.handler.closeHandler(connectionId); + } finally { + releaseHandlerLocked(removed.managedHandler); + } } - if (!logPath.isEmpty() && !logPath.endsWith("/")) { - logPath = logPath + "/"; + updateEffectiveRootLevelLocked(); + } + } + + static void resetForTest() { + synchronized (HANDLER_LOCK) { + 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.setLevel(Level.OFF); + } + } + + private static void captureExternalRootLevelLocked() { + Level current = logger.getLevel(); + if (current != lastManagedRootLevel) { + externalRootLevel = current; + } + } - if (fileHandler != null) { - fileHandler.close(); - logger.removeHandler(fileHandler); + 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 (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; + } + } - fileHandler = new PerConnectionFileHandler(logPath, level); - fileHandler.setLevel(level); - logger.addHandler(fileHandler); + 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); logger.setUseParentHandlers(false); + managed = new ManagedFileHandler(key, created); + handlersByPath.put(key, managed); + } + managed.refCount++; + return managed; + } - } catch (Exception ex) { - logger.warning("Log File warning : " + ex); + 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); + } } } - public static void closeConnectionHandler(String connectionId) { - if (fileHandler instanceof PerConnectionFileHandler) { - ((PerConnectionFileHandler) fileHandler).closeHandler(connectionId); + 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; + + ConnectionLogConfig( + ConnectionLogContext context, Level level, ManagedFileHandler managedHandler) { + this.context = context; + this.level = level; + this.managedHandler = managedHandler; } } } 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 index 073b2333a72b..75410fec19d6 100644 --- 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 @@ -16,6 +16,7 @@ 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; @@ -29,17 +30,50 @@ final class ConnectionLogContext { 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.connectionId = Objects.requireNonNull(connectionId, "connectionId cannot be null"); + 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; } @@ -48,6 +82,16 @@ 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; @@ -61,6 +105,6 @@ static ConnectionLogContext extractFromParameters(LogRecord record) { @Override public String toString() { - return connectionId; + return connectionId != null ? connectionId : "NO_CONN"; } } 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 def2569efd0f..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 @@ -56,23 +56,29 @@ 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()) { - ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); - if (context != null) { - connectionId = context.connectionId(); - } + return; } - if (connectionId == null || connectionId.isEmpty()) { + if (logContext == null || !connectionId.equals(logContext.connectionId())) { + logContext = BigQueryJdbcRootLogger.getConnectionContext(connectionId); + } + if (logContext != null + && logContext.hasExplicitLevel() + && !logContext.isLoggable(record.getLevel())) { return; } 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 bcc63418f542..0573244750b3 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 @@ -85,18 +85,24 @@ class PerConnectionFileHandler extends Handler { private final long maxFileBytes; private final Formatter logFormatter; private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); + private final ConcurrentHashMap connectionLevels; private final Object defaultWriterLock = new Object(); private ChannelLogWriter defaultWriter; private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { - this(baseLogPath, level, resolveMaxLogFileBytes()); + 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.logFormatter = BigQueryJdbcRootLogger.getFormatter(); + this.connectionLevels = managed ? new ConcurrentHashMap<>() : null; setLevel(level); setFormatter(this.logFormatter); @@ -110,6 +116,16 @@ class PerConnectionFileHandler extends Handler { this.baseLogPath = initializedDir; } + Path getBaseLogPath() { + return baseLogPath; + } + + void registerConnection(String connectionId, Level connLevel) { + if (connectionLevels != null && connectionId != null && connLevel != null) { + connectionLevels.put(connectionId, connLevel); + } + } + static long resolveMaxLogFileBytes() { String raw = System.getProperty(MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY); if (raw != null && !raw.trim().isEmpty()) { @@ -478,13 +494,55 @@ public void publish(LogRecord record) { return; } - String connectionId = BigQueryJdbcMdc.getConnectionId(); - if (connectionId == null || connectionId.isEmpty()) { - ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); - if (context != null) { - connectionId = context.connectionId(); + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context == null) { + context = BigQueryJdbcMdc.getConnectionContext(); + } + String connectionId = context != null ? context.connectionId() : null; + + if (connectionLevels != null) { + if (connectionId != null && !connectionId.isEmpty()) { + Level allowedLevel = connectionLevels.get(connectionId); + if (allowedLevel == null + || allowedLevel == Level.OFF + || record.getLevel().intValue() < allowedLevel.intValue()) { + return; + } + if (baseLogPath != null) { + boolean usedConnWriter = false; + ChannelLogWriter target = + writers.computeIfAbsent( + connectionId, + id -> createLogWriter(id, baseLogPath, allowedLevel, this.maxFileBytes)); + if (target != null) { + usedConnWriter = true; + } else { + target = getOrCreateDefaultWriter(); + } + if (!handlerClosed && target != null && !target.publish(record)) { + if (usedConnWriter) { + writers.remove(connectionId, target); + } else { + clearDefaultWriter(target); + } + } + } + return; + } + if (context == null + || !context.isLoggable(record.getLevel()) + || context.preConnectDir() == null + || baseLogPath == null + || !baseLogPath.equals(context.preConnectDir())) { + return; } + ChannelLogWriter globalTarget = getOrCreateDefaultWriter(); + if (!handlerClosed && globalTarget != null && !globalTarget.publish(record)) { + clearDefaultWriter(globalTarget); + } + return; } + boolean usedConnectionWriter = false; ChannelLogWriter target = null; @@ -502,11 +560,15 @@ public void publish(LogRecord record) { if (usedConnectionWriter) { writers.remove(connectionId, target); } else { - synchronized (defaultWriterLock) { - if (defaultWriter == target) { - defaultWriter = null; - } - } + clearDefaultWriter(target); + } + } + } + + private void clearDefaultWriter(ChannelLogWriter expected) { + synchronized (defaultWriterLock) { + if (defaultWriter == expected) { + defaultWriter = null; } } } @@ -534,11 +596,17 @@ public void close() throws SecurityException { } } finally { writers.clear(); + if (connectionLevels != null) { + connectionLevels.clear(); + } } } void closeHandler(String connectionId) { if (connectionId != null) { + if (connectionLevels != null) { + connectionLevels.remove(connectionId); + } ChannelLogWriter writer = writers.remove(connectionId); if (writer != null) { writer.close(); 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..7ace1801704a 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 @@ -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/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/OpenTelemetryJulHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java index 5896cf81be72..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 @@ -61,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); } @@ -182,4 +185,26 @@ public void testResultSetLoggerRoutingAndMessageFormatting() { 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()); + } } From 312e4aaea9679b4afc2af7fb8833cda33bba535e Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Fri, 27 Nov 2026 23:18:56 -0500 Subject: [PATCH 45/57] fix(bigquery-jdbc): gate log writer lifecycle, mask URL secrets, and short-circuit Gate 1 (#15255) Stack: PR 6 of 6 (base: `fix/bq-jdbc-per-conn-log-isolation`; consolidates #15166, #15167, and #15169) Bug: b/584840147, b/584840083 ### Summary Consolidates the final three diagnostic logging layers and incorporates review feedback across the stack: synchronizes per-connection writer slot close-vs-publish lifecycle and constructor failure rollback, masks non-allowlisted URL/connection secrets with ASCII control-character sanitization and fail-closed `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath`, and adds Gate-1 `isLoggable` short-circuiting with external JUL `Handler` preservation. ### Environment Variables & System Properties - **Added System Property:** `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=` (default: `true`; fail-closed allowing unset/blank, `true`, or `1`). When disabled, URL/Properties `LogPath` values are ignored with both a log `WARNING` and a JDBC `SQLWarning` on `Connection`. Documented in `docs/USER_GUIDE.md`. ### Design Decisions & Review Feedback Addressed - **Race-free `ConnectionWriterSlot` & `ReentrantLock` I/O locking:** Guards writer lifecycle and handler coordination with `ReentrantLock` (avoiding virtual-thread pinning across file I/O), disarms closed `ConnectionLogContext`s to `OFF_VALUE`, and cleans up executors/OTel resources on failed construction. - **Secret masking & log-injection sanitization:** Removes `BYOID_CredentialSource` from case-insensitive `SAFE_TO_LOG_PROPERTIES` and replaces ASCII control characters (`< 0x20`, `0x7F`) with `?` in logged property keys and allowlisted values. - **Fast-path Gate-1 filtering:** Checks `super.isLoggable(level)` ahead of thread-local MDC lookup (`~0.6 ns` disabled path) and preserves externally attached JUL handlers via `RootDriverLogger`. - **Channel & rotation refinements:** Opens exclusive channels with `APPEND`, writes `ByteBuffer`s in 8 KiB slices, emits `[LOG TRUNCATED: ...]` markers on fallback truncation, removes redundant backup UID checks before atomic `Files.move`, reports invalid `maxLogFileBytes` once, and installs a bounded `DeduplicatingErrorManager`. --- java-bigquery-jdbc/docs/USER_GUIDE.md | 1 + .../bigquery/jdbc/BigQueryConnection.java | 80 +++- .../cloud/bigquery/jdbc/BigQueryDriver.java | 21 +- .../jdbc/BigQueryJdbcContextProxy.java | 6 +- .../jdbc/BigQueryJdbcCustomLogger.java | 33 +- .../jdbc/BigQueryJdbcResultSetLogger.java | 34 +- .../bigquery/jdbc/BigQueryJdbcRootLogger.java | 361 +++++++++++++++-- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 60 ++- .../jdbc/PerConnectionFileHandler.java | 352 ++++++++++++----- .../bigquery/jdbc/BigQueryConnectionTest.java | 13 +- .../bigquery/jdbc/BigQueryDriverTest.java | 111 ++++++ .../jdbc/BigQueryJdbcCustomLoggerTest.java | 360 +++++++++++++++++ .../jdbc/BigQueryJdbcLoggingBaseTest.java | 2 +- .../jdbc/BigQueryJdbcUrlUtilityTest.java | 90 +++++ .../jdbc/PerConnectionFileHandlerTest.java | 362 ++++++++++++++++-- 15 files changed, 1662 insertions(+), 224 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 9cbc6b9a330b..cb2f7cc28e92 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -704,6 +704,7 @@ Log files are generated inside the specified `LogPath` directory with per-connec - **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/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 1d9f846c7600..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 @@ -160,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, @@ -279,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)); } @@ -294,32 +322,37 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { if (rawLogLevel == null) { rawLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); } - String connLogPath = ds.getLogPath(); - if (connLogPath == null) { - connLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); - } - if (connLogPath == null && rawLogLevel != null && !ds.getEnableGcpLogExporter()) { - connLogPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH; - } + 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 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; @@ -445,15 +478,27 @@ 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; } } } @@ -1433,7 +1478,9 @@ private void closeImpl() throws SQLException { if (callerInterrupted) { Thread.currentThread().interrupt(); } - BigQueryJdbcMdc.clear(); + if (this.connectionId.equals(BigQueryJdbcMdc.getConnectionId())) { + BigQueryJdbcMdc.clear(); + } BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId); BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId); BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry); @@ -1549,6 +1596,7 @@ private OpenTelemetry getOpenTelemetryInstance() { effectiveProjectId, this.credentials, this.proxyProperties); + this.openTelemetry = openTelemetry; boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry; Logging localLoggingClient = null; 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 ec787b377253..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) { @@ -193,6 +192,12 @@ public Connection connect(String url, Properties info) throws SQLException { 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); 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 bca84a28c02a..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,19 +34,40 @@ 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 (level == null || level == Level.OFF) { + if (!isSuperLoggable(level)) { return false; } - if (this.getLevel() != null) { - return super.isLoggable(level); + 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; } - ConnectionLogContext context = BigQueryJdbcMdc.getConnectionContext(); if (context != null && context.hasExplicitLevel()) { return context.isLoggable(level); } - return super.isLoggable(level); + return true; } private void logWithCaller(Level level, Supplier msgSupplier) { 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 fa1831c01576..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 @@ -74,11 +74,7 @@ public static BigQueryJdbcResultSetLogger getLogger(Class clazz, String conne if (connectionId == null || connectionId.isEmpty()) { return getLogger(clazz, (ConnectionLogContext) null); } - ConnectionLogContext context = BigQueryJdbcRootLogger.getConnectionContext(connectionId); - if (context == null) { - context = ConnectionLogContext.unregistered(connectionId); - } - return getLogger(clazz, context); + return getLogger(clazz, BigQueryJdbcRootLogger.resolveContext(connectionId)); } static BigQueryJdbcResultSetLogger getLogger( @@ -103,16 +99,12 @@ BigQueryJdbcCustomLogger delegate() { } public boolean isLoggable(Level level) { - if (level == null || level == Level.OFF) { + if (!delegate.isSuperLoggable(level)) { return false; } - if (delegate.getLevel() != null) { - return delegate.isLoggable(level); - } - if (connectionContext != null && connectionContext.hasExplicitLevel()) { - return connectionContext.isLoggable(level); - } - return delegate.isLoggable(level); + ConnectionLogContext ctx = + connectionContext != null ? connectionContext : BigQueryJdbcMdc.getConnectionContext(); + return delegate.isLoggableAfterSuper(level, ctx); } public BigQueryJdbcResultSetLogger getArrowStructLogger() { @@ -163,10 +155,13 @@ public void log(LogRecord record) { System.arraycopy(existingParams, 0, newParams, 1, existingParams.length); record.setParameters(newParams); } - try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.withContext(connectionContext)) { - delegate.log(record); + if (BigQueryJdbcMdc.getConnectionContext() != connectionContext) { + try (BigQueryJdbcMdc.MdcCloseable ignored = + BigQueryJdbcMdc.withContext(connectionContext)) { + delegate.log(record); + } + return; } - return; } delegate.log(record); } @@ -185,7 +180,10 @@ private void logTrace(Level level, String methodName, Supplier msgSuppli 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. */ @@ -258,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 65968510b987..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 @@ -24,6 +24,9 @@ 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; @@ -33,28 +36,37 @@ 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 final Object HANDLER_LOCK = new Object(); + 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(); @@ -88,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() { @@ -181,10 +279,29 @@ static ConnectionLogContext getConnectionContext(String 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 { - synchronized (HANDLER_LOCK) { - externalRootLevel = null; + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); } } @@ -192,7 +309,9 @@ static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logP Level effectiveLevel = level != null ? level : Level.OFF; ManagedFileHandler tempHandler = null; boolean countedScope = false; - synchronized (HANDLER_LOCK) { + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); if (effectiveLevel != Level.OFF) { activePreConnectScopes++; countedScope = true; @@ -200,11 +319,13 @@ static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logP try { tempHandler = acquireHandlerLocked(logPath); } catch (Exception ex) { - logger.warning("Log File warning : " + 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 = @@ -217,12 +338,16 @@ static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logP mdcScope.close(); } finally { if (decrementScope || acquired != null) { - synchronized (HANDLER_LOCK) { + HANDLER_LOCK.lock(); + try { + captureExternalRootLevelLocked(); if (decrementScope && activePreConnectScopes > 0) { activePreConnectScopes--; } releaseHandlerLocked(acquired); updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); } } } @@ -233,8 +358,10 @@ static void registerConnection(String connectionId, String rawLogLevel, String l if (connectionId == null || connectionId.isEmpty()) { return; } - synchronized (HANDLER_LOCK) { + HANDLER_LOCK.lock(); + try { captureExternalRootLevelLocked(); + drainCleanupQueueLocked(); Level connLevel = rawLogLevel != null ? BigQueryJdbcUrlUtility.parseLogLevel(rawLogLevel) @@ -248,7 +375,7 @@ static void registerConnection(String connectionId, String rawLogLevel, String l managed = acquireHandlerLocked(logPath); managed.handler.registerConnection(connectionId, connLevel); } catch (Exception ex) { - logger.warning("Log File warning : " + ex); + logger.log(Level.WARNING, "Log File warning", ex); } } ConnectionLogConfig previous = @@ -258,11 +385,126 @@ static void registerConnection(String connectionId, String rawLogLevel, String l new ConnectionLogContext(connectionId, connLevel.intValue()), connLevel, managed)); - if (previous != null && previous.managedHandler != null) { - previous.managedHandler.handler.closeHandler(connectionId); - releaseHandlerLocked(previous.managedHandler); + if (previous != null) { + closeConfigLocked(connectionId, previous); } updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); + } + } + + static void trackConnectionLifecycle(BigQueryConnection connection, String connectionId) { + if (connection == null || connectionId == null) { + return; + } + HANDLER_LOCK.lock(); + try { + boolean reaped = drainCleanupQueueLocked(); + ConnectionLogConfig config = activeConnections.get(connectionId); + if (config != null) { + detachCleanableLocked(config); + config.cleanable = new ConnectionCleanable(connection, connectionId, CLEANUP_QUEUE); + trackedConnectionCount++; + ensureCleanerRunningLocked(); + } + if (reaped) { + updateEffectiveRootLevelLocked(); + } + } finally { + HANDLER_LOCK.unlock(); + } + } + + 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; + } + + 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; + } + + 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. + } } } @@ -270,22 +512,28 @@ public static void closeConnectionHandler(String connectionId) { if (connectionId == null) { return; } - synchronized (HANDLER_LOCK) { + HANDLER_LOCK.lock(); + try { captureExternalRootLevelLocked(); + drainCleanupQueueLocked(); ConnectionLogConfig removed = activeConnections.remove(connectionId); - if (removed != null && removed.managedHandler != null) { - try { - removed.managedHandler.handler.closeHandler(connectionId); - } finally { - releaseHandlerLocked(removed.managedHandler); - } + if (removed != null) { + closeConfigLocked(connectionId, removed); } updateEffectiveRootLevelLocked(); + } finally { + HANDLER_LOCK.unlock(); } } static void resetForTest() { - synchronized (HANDLER_LOCK) { + 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 { @@ -299,17 +547,62 @@ static void resetForTest() { 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; @@ -325,6 +618,14 @@ private static void updateEffectiveRootLevelLocked() { 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; } @@ -353,7 +654,6 @@ private static ManagedFileHandler acquireHandlerLocked(String logPath) { new PerConnectionFileHandler( pathArg, Level.ALL, PerConnectionFileHandler.resolveMaxLogFileBytes(), true); logger.addHandler(created); - logger.setUseParentHandlers(false); managed = new ManagedFileHandler(key, created); handlersByPath.put(key, managed); } @@ -392,6 +692,7 @@ private static final class ConnectionLogConfig { final ConnectionLogContext context; final Level level; final ManagedFileHandler managedHandler; + ConnectionCleanable cleanable; ConnectionLogConfig( ConnectionLogContext context, Level level, ManagedFileHandler managedHandler) { @@ -400,4 +701,16 @@ private static final class ConnectionLogConfig { 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 60ca2319448b..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 @@ -125,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; @@ -836,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; } } @@ -847,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. * @@ -855,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(); 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 0573244750b3..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 @@ -44,6 +44,8 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; 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; @@ -64,6 +66,9 @@ class PerConnectionFileHandler extends Handler { 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"); @@ -78,16 +83,20 @@ class PerConnectionFileHandler extends Handler { 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 long maxFileBytes; + private final boolean managed; private final Formatter logFormatter; - private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); - private final ConcurrentHashMap connectionLevels; - private final Object defaultWriterLock = new Object(); + 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) { @@ -101,19 +110,25 @@ class PerConnectionFileHandler extends Handler { 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(); - this.connectionLevels = managed ? new ConcurrentHashMap<>() : null; setLevel(level); setFormatter(this.logFormatter); + setErrorManager(new DeduplicatingErrorManager()); Path initializedDir = null; + boolean detectedPosix = false; try { - Path candidate = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); - initializedDir = ensureSecureDirectory(candidate); + 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() { @@ -121,22 +136,44 @@ Path getBaseLogPath() { } void registerConnection(String connectionId, Level connLevel) { - if (connectionLevels != null && connectionId != null && connLevel != null) { - connectionLevels.put(connectionId, 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 = System.getProperty(MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY); + String raw; + try { + 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(raw.trim()); + 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; } @@ -224,12 +261,17 @@ private static void verifyPosixOwner(Path path, boolean allowRootOwner) throws I } 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); } - boolean isPosix = supportsPosix(root); Path current = root; int nameCount = normalized.getNameCount(); for (int i = 0; i < nameCount; i++) { @@ -291,7 +333,8 @@ private static String sanitizeIdSegment(String id) { private static FileChannel openExclusiveNewChannel(Path path, boolean isPosix) throws IOException { EnumSet opts = - EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); + EnumSet.of( + StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.APPEND); if (isPosix) { return FileChannel.open(path, opts, FILE_ATTR_0600); } @@ -458,8 +501,8 @@ ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel, long } boolean interrupted = Thread.interrupted(); try { - Path verifiedDir = ensureSecureDirectory(logDir); - boolean isPosix = supportsPosix(verifiedDir); + boolean isPosix = (logDir == baseLogPath) ? basePathPosix : supportsPosix(logDir); + Path verifiedDir = ensureSecureDirectory(logDir, isPosix); OpenedLogFile opened = DEFAULT_HANDLER_ID.equals(id) ? openGlobalChannel(verifiedDir, isPosix) @@ -476,18 +519,6 @@ ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel, long } } - private ChannelLogWriter getOrCreateDefaultWriter() { - synchronized (defaultWriterLock) { - if (handlerClosed || baseLogPath == null) { - return null; - } - if (defaultWriter == null) { - defaultWriter = createLogWriter(DEFAULT_HANDLER_ID, baseLogPath, level, this.maxFileBytes); - } - return defaultWriter; - } - } - @Override public void publish(LogRecord record) { if (handlerClosed || record == null || !isLoggable(record)) { @@ -500,32 +531,14 @@ public void publish(LogRecord record) { } String connectionId = context != null ? context.connectionId() : null; - if (connectionLevels != null) { + if (managed) { if (connectionId != null && !connectionId.isEmpty()) { - Level allowedLevel = connectionLevels.get(connectionId); - if (allowedLevel == null - || allowedLevel == Level.OFF - || record.getLevel().intValue() < allowedLevel.intValue()) { + ConnectionWriterSlot slot = slots.get(connectionId); + if (slot == null || !slot.allows(record.getLevel())) { return; } if (baseLogPath != null) { - boolean usedConnWriter = false; - ChannelLogWriter target = - writers.computeIfAbsent( - connectionId, - id -> createLogWriter(id, baseLogPath, allowedLevel, this.maxFileBytes)); - if (target != null) { - usedConnWriter = true; - } else { - target = getOrCreateDefaultWriter(); - } - if (!handlerClosed && target != null && !target.publish(record)) { - if (usedConnWriter) { - writers.remove(connectionId, target); - } else { - clearDefaultWriter(target); - } - } + publishToSlot(slot, connectionId, record); } return; } @@ -536,39 +549,96 @@ public void publish(LogRecord record) { || !baseLogPath.equals(context.preConnectDir())) { return; } - ChannelLogWriter globalTarget = getOrCreateDefaultWriter(); - if (!handlerClosed && globalTarget != null && !globalTarget.publish(record)) { - clearDefaultWriter(globalTarget); - } + publishToDefault(record); return; } - boolean usedConnectionWriter = false; - ChannelLogWriter target = null; - if (connectionId != null && !connectionId.isEmpty() && baseLogPath != null) { - target = - writers.computeIfAbsent( - connectionId, id -> createLogWriter(id, baseLogPath, this.level, this.maxFileBytes)); - usedConnectionWriter = (target != null); - } - if (target == null) { - target = getOrCreateDefaultWriter(); + 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; } + 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)) { - if (usedConnectionWriter) { - writers.remove(connectionId, target); - } else { - clearDefaultWriter(target); + defaultWriterLock.lock(); + try { + if (defaultWriter == target) { + defaultWriter = null; + } + } finally { + defaultWriterLock.unlock(); } } } - private void clearDefaultWriter(ChannelLogWriter expected) { - synchronized (defaultWriterLock) { - if (defaultWriter == expected) { - defaultWriter = null; + 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(); + } + 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(); } } } @@ -581,35 +651,97 @@ public void flush() { @Override public void close() throws SecurityException { handlerClosed = true; - for (ChannelLogWriter writer : writers.values()) { - try { - writer.close(); - } catch (Exception ignored) { + 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 { - synchronized (defaultWriterLock) { - if (defaultWriter != null) { - defaultWriter.close(); - defaultWriter = null; - } + if (defaultWriter != null) { + defaultWriter.close(); + defaultWriter = null; } } finally { - writers.clear(); - if (connectionLevels != null) { - connectionLevels.clear(); - } + defaultWriterLock.unlock(); } } void closeHandler(String connectionId) { if (connectionId != null) { - if (connectionLevels != null) { - connectionLevels.remove(connectionId); + 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; } - ChannelLogWriter writer = writers.remove(connectionId); - if (writer != null) { - writer.close(); + String text = "java.util.logging.ErrorManager: " + code + (msg != null ? ": " + msg : ""); + System.err.println(text); + if (ex != null) { + ex.printStackTrace(System.err); } } } @@ -629,7 +761,7 @@ static final class OpenedLogFile { } static final class ChannelLogWriter { - private final Object lock = new Object(); + private final ReentrantLock lock = new ReentrantLock(); private final String id; private final Path logDir; private final boolean isPosix; @@ -700,14 +832,8 @@ private void rotate() throws IOException { 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 (isPosix) { - verifyPosixOwner(backupPath, false); - verifySingleLinkCount(backupPath); - } + } else if (!backupAttrs.isRegularFile() || backupAttrs.isOther()) { + throw new IOException("Refusing to rotate onto non-regular backup path: " + backupPath); } } if (fileLock != null && fileLock.isValid()) { @@ -750,13 +876,23 @@ private void rotate() throws IOException { this.writtenBytes = reopened.channel.size(); } - private void truncateInPlace() throws IOException { + 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) { @@ -771,7 +907,8 @@ boolean publish(LogRecord record) { return true; } byte[] bytes = formatted.getBytes(StandardCharsets.UTF_8); - synchronized (lock) { + lock.lock(); + try { if (closed) { return false; } @@ -790,12 +927,16 @@ boolean publish(LogRecord record) { rotate(); } catch (Exception rotEx) { owner.reportError("Failed to rotate log file", rotEx, ErrorManager.WRITE_FAILURE); - truncateInPlace(); + truncateInPlace(rotEx, bytes.length); } } ByteBuffer buf = ByteBuffer.wrap(bytes); - while (buf.hasRemaining()) { - writtenBytes += channel.write(buf); + 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) { @@ -824,11 +965,14 @@ boolean publish(LogRecord record) { } } return true; + } finally { + lock.unlock(); } } void close() { - synchronized (lock) { + lock.lock(); + try { if (closed) { return; } @@ -855,6 +999,8 @@ void close() { globalClaimKey = null; } } + } finally { + lock.unlock(); } } } 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 254c7a5e0920..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 @@ -600,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 } @@ -616,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); } 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 c7202cc103aa..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 @@ -34,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 { @@ -303,4 +308,110 @@ public void testConnect_ioExceptionThrowsInsteadOfReturningNull() { 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/BigQueryJdbcCustomLoggerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java index 3e7233fa4eb6..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); } } @@ -376,6 +396,7 @@ public void testResultSetLoggerParameterPreservation() { assertEquals("job-999", params[1]); } finally { rsLogger.delegate().removeHandler(rsHandler); + rsLogger.delegate().setLevel(null); } } @@ -737,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 7ace1801704a..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; 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 71f2b7ffa3c5..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 { @@ -415,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/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index d102a71149cc..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 @@ -27,7 +27,10 @@ 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; @@ -36,13 +39,23 @@ 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; @@ -512,7 +525,7 @@ private static Optional findLogFileInDir(Path dir, String suffix) throws I } @Test - public void testOneGibDefaultAndBackupFileRotation() throws IOException { + 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); @@ -523,6 +536,14 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { 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); @@ -530,7 +551,10 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { System.setProperty(prop, prev); } } + } + @Test + public void testBackupFileRotationAndParameterContextRouting() throws IOException { Path boundedDir = tempDir.resolve("bounded"); long maxBytes = 1024L; PerConnectionFileHandler defaultMaxHandler = @@ -552,14 +576,12 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { boundedHandler.publish( new LogRecord(Level.INFO, "Padding log line to exceed 1 KiB limit #" + i)); } - // Route via ConnectionLogContext in params[0] with empty MDC and trigger per-conn .1.log 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); } - // Plain String in params[0] with empty MDC routes to global log instead of "-BigQ.log" LogRecord retryRecord = new LogRecord(Level.FINEST, "Retrying RPC"); retryRecord.setParameters(new Object[] {"BigQuery retried method: getQueryResults"}); boundedHandler.publish(retryRecord); @@ -587,43 +609,51 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { expected0600, Files.getPosixFilePermissions( findLogFileInDir(boundedDir, "-rotc.1.log").get(), LinkOption.NOFOLLOW_LINKS)); + } + } - // Symlink at .1.log is deleted safely without modifying target; foreign UID falls back - 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()); + @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, "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"))); - - PerConnectionFileHandler.overrideUidForTesting = 888_888_888; - try { - for (int i = 0; i < 12; i++) { - symRotHandler.publish(new LogRecord(Level.INFO, "Foreign backup fallback line #" + i)); - } - } finally { - PerConnectionFileHandler.overrideUidForTesting = null; + symRotHandler.publish(new LogRecord(Level.INFO, "Foreign backup rotation line #" + i)); } - assertTrue( - new String( - Files.readAllBytes(symDir.resolve("BQ-JDBC-GLOBAL.log")), - StandardCharsets.UTF_8) - .contains("fallback line #11")); } finally { - symRotHandler.close(); + 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(); } + } - // Non-regular directory blocking .1.log falls back gracefully to in-place truncation + @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 = @@ -639,18 +669,226 @@ public void testOneGibDefaultAndBackupFileRotation() throws IOException { } Path fallbackGlobal = fallbackDir.resolve("BQ-JDBC-GLOBAL.log"); assertTrue(Files.size(fallbackGlobal) > 0 && Files.size(fallbackGlobal) <= maxBytes); - assertTrue( - new String(Files.readAllBytes(fallbackGlobal), StandardCharsets.UTF_8).contains("cap #19")); + 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); + new PerConnectionFileHandler(recoverDir.toString(), Level.INFO, 512L, true); recoverHandler.setErrorManager(silentErrorManager()); - try { - BigQueryJdbcMdc.registerInstance("BQ-JDBC-rcvr1234"); + 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()); @@ -675,4 +913,54 @@ public void testClosedWriterOnRotationFailureEvictsAndRecovers() throws IOExcept 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; + } } From 1413eeb2a54f19a224423be6234369284ee98256 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Mon, 30 Nov 2026 10:47:50 +0100 Subject: [PATCH 46/57] perf(spanner): make async query execution event-driven (#14933) Asynchronous queries share a bounded background thread pool to read rows from query streams and dispatch them to application callbacks. Previously, each active query held onto a background thread for its entire lifetime, parking that thread whenever the query was waiting for more data from the server, waiting for a full row buffer to be drained, or paused by the application callback. Running many concurrent or paused queries could exhaust the shared thread pool and stall other queries waiting for an available worker thread. This change switches asynchronous query execution to an event-driven model so background threads are only used while actively moving buffered rows: - Event-driven row production: Background tasks read rows only while stream data is already buffered locally and space remains in the row queue, releasing the worker thread immediately whenever a query is waiting on the network, the row buffer is full, or consumption is paused. Incoming stream data, buffer consumption, and resume calls re-schedule row production as needed. - Serialized stream startup and consumption: Completes stream initialization before row production begins so underlying query iterators are never accessed concurrently across threads, while preserving startup error translation for queries that inline transaction creation. - Prompt cancellation and clean lifecycle termination: Delivers cancellation directly to paused or in-flight callbacks without requiring a separate resume call, closes underlying streams outside internal locks, and waits for all active tasks to finish before completing the result future and releasing executor resources. - Strict callback thread scoping and interrupt handling: Restricts cursor advancement and row reads in asynchronous mode to the active callback invocation thread, and cancels the query while preserving the thread interrupt status if a blocking list conversion is interrupted. --- .../cloud/spanner/AsyncResultSetImpl.java | 1020 ++++++++---- .../cloud/spanner/ForwardingStructReader.java | 10 +- ...ultSetImplLifecycleAndConcurrencyTest.java | 1322 ++++++++++++++++ .../AsyncResultSetImplStreamingTest.java | 1363 +++++++++++++++++ .../cloud/spanner/AsyncResultSetImplTest.java | 707 ++++++++- .../spanner/AsyncResultSetImplTestUtil.java | 298 ++++ .../google/cloud/spanner/ReadAsyncTest.java | 288 ++++ 7 files changed, 4597 insertions(+), 411 deletions(-) create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplLifecycleAndConcurrencyTest.java create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplStreamingTest.java create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/AsyncResultSetImplTestUtil.java 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/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/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/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; From 1e3d32e384a7de917665b1de4f803df0c178b2e0 Mon Sep 17 00:00:00 2001 From: Igor Bernstein Date: Mon, 30 Nov 2026 11:15:54 -0500 Subject: [PATCH 47/57] test(bigtable): add shared Data IT resource setup and lazy CloudEnv admin clients (#15246) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **PR Stack (Reduce Admin API usage in Bigtable Data ITs):** 1. **#15246 (This PR)** — Shared Data IT resource setup (`scripts/setup-test-table.sh`) and lazy `CloudEnv` admin clients 2. #15247 — Mechanical swap to shared `AuthorizedView` across 7 Data ITs 3. #15248 — Shared `MaterializedView`, `ExecuteQueryIT` (`cf_history` + `SchemaBundle`), and `LargeRowIT` bounded scans --- Lay the non-behavioral foundation for moving Data integration tests (`com.google.cloud.bigtable.data.v2.it.*`) onto pre-provisioned shared resources: - **`scripts/setup-test-table.sh`**: Document and idempotently provision all shared Data IT resources for `projects//instances//tables/`: - Column families `cf` (`maxversions=1 || maxage=1h`) and `cf_history` (`maxversions=10 || maxage=1h`, for multi-version SQL `with_history` queries). - `AuthorizedView` `test-authorized-view` (`SubsetView` over row prefix `row#` and `cf` qualifier prefix `qualifier`). - `MaterializedView` `
    -mv` (`SELECT _key, MAX(cf['column']) AS column FROM
    GROUP BY _key`). - `SchemaBundle` `test-schema-bundle` (protobuf `FileDescriptorSet` compiled from `singer.proto` and `album.proto`). - **`AbstractTestEnv` / `EmulatorEnv` / `CloudEnvTest`**: Expose `getHistoryFamilyId()`, `getAuthorizedViewId()`, `getMaterializedViewId()`, and `getSchemaBundleId()` matching `scripts/setup-test-table.sh`. - **`CloudEnv`**: Lazily initialize `tableAdminClient` and `instanceAdminClient` so pure-data IT forks do not open unused Admin gRPC channels. - **`SampleRowsIT#testOnAuthorizedView`**: Use `PrefixGenerator` for the temporary `AuthorizedView` ID and wrap resource cleanup in `try / finally`. --- .../bigtable/data/v2/it/SampleRowsIT.java | 55 +++-- .../test_helpers/env/AbstractTestEnv.java | 37 +++ .../bigtable/test_helpers/env/CloudEnv.java | 46 +++- .../test_helpers/env/CloudEnvTest.java | 15 ++ .../test_helpers/env/EmulatorEnv.java | 4 +- java-bigtable/scripts/setup-test-table.sh | 227 ++++++++++++++++-- 6 files changed, 325 insertions(+), 59 deletions(-) diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/SampleRowsIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/SampleRowsIT.java index 063d0d1f5095..78b7dbe9a557 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/SampleRowsIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/SampleRowsIT.java @@ -80,37 +80,40 @@ public void testOnAuthorizedView() .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); AuthorizedView testAuthorizedView = createPreSplitTableAndAuthorizedView(); - - BigtableDataClient client = testEnvRule.env().getDataClient(); - - ApiFuture> future = - client.sampleRowKeysAsync( - AuthorizedViewId.of(testAuthorizedView.getTableId(), testAuthorizedView.getId())); - - List results = future.get(1, TimeUnit.MINUTES); - - List resultKeys = new ArrayList<>(); - for (KeyOffset keyOffset : results) { - resultKeys.add(keyOffset.getKey()); + try { + BigtableDataClient client = testEnvRule.env().getDataClient(); + + ApiFuture> future = + client.sampleRowKeysAsync( + AuthorizedViewId.of(testAuthorizedView.getTableId(), testAuthorizedView.getId())); + + List results = future.get(1, TimeUnit.MINUTES); + + List resultKeys = new ArrayList<>(); + for (KeyOffset keyOffset : results) { + resultKeys.add(keyOffset.getKey()); + } + + assertThat(resultKeys) + .containsExactly( + ByteString.copyFromUtf8("food"), + ByteString.copyFromUtf8("fool"), + ByteString.copyFromUtf8("fop")); + } finally { + try { + testEnvRule + .env() + .getTableAdminClient() + .deleteAuthorizedView(testAuthorizedView.getTableId(), testAuthorizedView.getId()); + } finally { + testEnvRule.env().getTableAdminClient().deleteTable(testAuthorizedView.getTableId()); + } } - - assertThat(resultKeys) - .containsExactly( - ByteString.copyFromUtf8("food"), - ByteString.copyFromUtf8("fool"), - ByteString.copyFromUtf8("fop")); - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView(testAuthorizedView.getTableId(), testAuthorizedView.getId()); - - testEnvRule.env().getTableAdminClient().deleteTable(testAuthorizedView.getTableId()); } private static AuthorizedView createPreSplitTableAndAuthorizedView() { String tableId = PrefixGenerator.newPrefix("SampleRowsIT#AuthorizedView"); - String authorizedViewId = UUID.randomUUID().toString(); + String authorizedViewId = PrefixGenerator.newPrefix("SampleRowsIT#AuthorizedView"); testEnvRule .env() diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/AbstractTestEnv.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/AbstractTestEnv.java index 6b92802e8b40..f2785c2eec68 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/AbstractTestEnv.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/AbstractTestEnv.java @@ -22,6 +22,8 @@ import com.google.cloud.bigtable.admin.v2.models.Cluster; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.BigtableDataSettings; +import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; +import com.google.cloud.bigtable.data.v2.models.MaterializedViewId; import com.google.cloud.bigtable.data.v2.models.TableId; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; @@ -112,10 +114,45 @@ public synchronized String getPrimaryClusterId() { public abstract String getKmsKeyName(); + public static final String SHARED_AUTHORIZED_VIEW_ID = "test-authorized-view"; + public static final String SHARED_SCHEMA_BUNDLE_ID = "test-schema-bundle"; + public String getFamilyId() { return "cf"; } + /** + * Returns the multi-version column family ({@code maxversions=10 || maxage=1h}) provisioned by + * {@code scripts/setup-test-table.sh} for tests that read historical cell versions. + */ + public String getHistoryFamilyId() { + return "cf_history"; + } + + /** + * Returns the pre-provisioned {@link AuthorizedViewId} on {@link #getTableId()} configured by + * {@code scripts/setup-test-table.sh}. + */ + public AuthorizedViewId getAuthorizedViewId() { + return AuthorizedViewId.of(getTableId(), SHARED_AUTHORIZED_VIEW_ID); + } + + /** + * Returns the pre-provisioned {@link MaterializedViewId} backed by {@link #getTableId()} + * configured by {@code scripts/setup-test-table.sh}. + */ + public MaterializedViewId getMaterializedViewId() { + return MaterializedViewId.of(getTableId().getTableId() + "-mv"); + } + + /** + * Returns the pre-provisioned schema bundle ID on {@link #getTableId()} configured by {@code + * scripts/setup-test-table.sh}. + */ + public String getSchemaBundleId() { + return SHARED_SCHEMA_BUNDLE_ID; + } + public boolean isInstanceAdminSupported() { return true; } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnv.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnv.java index 1b139dbff0ba..5a24bf9cfa95 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnv.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnv.java @@ -70,8 +70,8 @@ import javax.annotation.Nullable; /** - * Test environment that uses an existing bigtable table. The table must have a pre-existing family - * {@code cf}. The target table is configured via the system properties: + * Test environment that uses pre-provisioned shared Bigtable resources (see {@code + * scripts/setup-test-table.sh}). The target table is configured via the system properties: * *
      *
    • {@code bigtable.project} @@ -125,8 +125,8 @@ public boolean apply(InetSocketAddress input) { private BigtableDataClient dataClient; @Nullable private Shim sessionShim; - private BigtableTableAdminClient tableAdminClient; - private BigtableInstanceAdminClient instanceAdminClient; + @Nullable private BigtableTableAdminClient tableAdminClient; + @Nullable private BigtableInstanceAdminClient instanceAdminClient; static CloudEnv fromSystemProperties() { return new CloudEnv( @@ -497,8 +497,6 @@ void start() throws IOException { dataClient = null; throw e; } - tableAdminClient = BigtableTableAdminClient.create(tableAdminSettings.build()); - instanceAdminClient = BigtableInstanceAdminClient.create(instanceAdminSettings.build()); } static void verifyExpectedProtocol(ExpectedProtocol expectedProtocol, Shim shim) { @@ -523,11 +521,20 @@ static void verifyExpectedProtocol(ExpectedProtocol expectedProtocol, Shim shim) } @Override - void stop() { + synchronized void stop() { sessionShim = null; - dataClient.close(); - tableAdminClient.close(); - instanceAdminClient.close(); + if (dataClient != null) { + dataClient.close(); + dataClient = null; + } + if (tableAdminClient != null) { + tableAdminClient.close(); + tableAdminClient = null; + } + if (instanceAdminClient != null) { + instanceAdminClient.close(); + instanceAdminClient = null; + } } @Override @@ -551,7 +558,14 @@ public BigtableDataClient getDataClient() { } @Override - public BigtableTableAdminClient getTableAdminClient() { + public synchronized BigtableTableAdminClient getTableAdminClient() { + if (tableAdminClient == null) { + try { + tableAdminClient = BigtableTableAdminClient.create(tableAdminSettings.build()); + } catch (IOException e) { + throw new IllegalStateException("Caught unexpected error creating table admin client", e); + } + } return tableAdminClient; } @@ -567,7 +581,15 @@ public BigtableTableAdminClient getTableAdminClientForInstance(String instanceId } @Override - public BigtableInstanceAdminClient getInstanceAdminClient() { + public synchronized BigtableInstanceAdminClient getInstanceAdminClient() { + if (instanceAdminClient == null) { + try { + instanceAdminClient = BigtableInstanceAdminClient.create(instanceAdminSettings.build()); + } catch (IOException e) { + throw new IllegalStateException( + "Caught unexpected error creating instance admin client", e); + } + } return instanceAdminClient; } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnvTest.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnvTest.java index d7451d647203..82fdafcf6e05 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnvTest.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/CloudEnvTest.java @@ -41,6 +41,9 @@ import com.google.cloud.bigtable.data.v2.internal.compat.ShimImpl; import com.google.cloud.bigtable.data.v2.internal.util.ClientConfigurationManager; import com.google.cloud.bigtable.data.v2.internal.util.SessionScope; +import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; +import com.google.cloud.bigtable.data.v2.models.MaterializedViewId; +import com.google.cloud.bigtable.data.v2.models.TableId; import com.google.cloud.bigtable.test_helpers.env.AbstractTestEnv.ExpectedProtocol; import com.google.common.collect.ImmutableList; import com.google.protobuf.ByteString; @@ -75,6 +78,18 @@ void emulatorEnv_sessionsDisabled() { assertThat(EmulatorEnv.createBundled().isSessionsEnabled()).isFalse(); } + @Test + void sharedResourceIds_matchSetupScriptConventions() { + EmulatorEnv env = EmulatorEnv.createBundled(); + assertThat(env.getTableId()).isEqualTo(TableId.of("default-table")); + assertThat(env.getFamilyId()).isEqualTo("cf"); + assertThat(env.getHistoryFamilyId()).isEqualTo("cf_history"); + assertThat(env.getAuthorizedViewId()) + .isEqualTo(AuthorizedViewId.of("default-table", "test-authorized-view")); + assertThat(env.getMaterializedViewId()).isEqualTo(MaterializedViewId.of("default-table-mv")); + assertThat(env.getSchemaBundleId()).isEqualTo("test-schema-bundle"); + } + @Test void disabledShim_sessionsDisabled() { assertThat(CloudEnv.isSessionsEnabled(new DisabledShim())).isFalse(); diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/EmulatorEnv.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/EmulatorEnv.java index 2ba3bd72c11d..a465afd82b15 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/EmulatorEnv.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/test_helpers/env/EmulatorEnv.java @@ -78,7 +78,9 @@ void start() throws Exception { tableAdminClient = BigtableTableAdminClient.create(tableAdminSettings); tableAdminClient.createTable( - CreateTableRequest.of(TABLE_ID.getTableId()).addFamily(getFamilyId())); + CreateTableRequest.of(TABLE_ID.getTableId()) + .addFamily(getFamilyId()) + .addFamily(getHistoryFamilyId())); } @Override diff --git a/java-bigtable/scripts/setup-test-table.sh b/java-bigtable/scripts/setup-test-table.sh index ac0050af9d9d..e9397146ddff 100755 --- a/java-bigtable/scripts/setup-test-table.sh +++ b/java-bigtable/scripts/setup-test-table.sh @@ -1,39 +1,226 @@ #!/usr/bin/env bash +# 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. -# Set up a table to use for integration tests. +# Provisions the shared Bigtable instance, table, column families, and auxiliary +# resources required to run Data integration tests (`com.google.cloud.bigtable.data.v2.it.*`) +# without per-test Admin API mutations. +# +# Provisioned resources (must match AbstractTestEnv / AuthorizedViewTestHelper): +# 1. Instance: (created with 1 SSD node in $ZONE if missing) +# 2. Table: +# - Column family `cf`: maxversions=1 || maxage=1h (general Data ITs) +# - Column family `cf_history`: maxversions=10 || maxage=1h (ExecuteQueryIT#withHistoryQuery) +# 3. AuthorizedView: `test-authorized-view` on +# - SubsetView over row prefix `row#` and family `cf` qualifier prefix `qualifier` +# 4. MaterializedView: `-mv` on +# - `SELECT _key, MAX(cf['column']) AS column FROM `` GROUP BY _key` +# 5. SchemaBundle: `test-schema-bundle` on +# - Protobuf FileDescriptorSet compiled from `src/test/proto/{singer,album}.proto` +# +# Usage: +# ./scripts/setup-test-table.sh projects//instances//tables/ [admin-endpoint] [impersonate-service-account] +# +# Environment overrides: +# ADMIN_HOST (optional Bigtable Admin endpoint override; uses CLI default when unset) +# ZONE (default: us-central1-b) +# IMPERSONATE_SERVICE_ACCOUNT (optional service account email for cbt/gcloud auth) +# PROTOC (optional path to protoc binary) -# Usage: ./scripts/setup-test-table.sh projects//instances//tables/ [admin-endpoint] -# Environment overrides: ADMIN_HOST, ZONE +set -euo pipefail -set -e -set -u +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +JAVA_BIGTABLE_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" -ZONE=${ZONE:-us-central1-b} -FAMILY=cf +ZONE="${ZONE:-us-central1-b}" +FAMILY="cf" +HISTORY_FAMILY="cf_history" +AUTHORIZED_VIEW_ID="test-authorized-view" +SCHEMA_BUNDLE_ID="test-schema-bundle" # Format: projects//instances//tables/ -TABLE_NAME=$1 -ADMIN_HOST=${2:-${ADMIN_HOST:-bigtableadmin.googleapis.com:443}} +TABLE_NAME="${1:-}" +ADMIN_HOST="${2:-${ADMIN_HOST:-}}" +IMPERSONATE_SA="${3:-${IMPERSONATE_SERVICE_ACCOUNT:-}}" -if [[ ${TABLE_NAME} =~ projects\/([^/]+)\/instances\/([^/]+)\/tables\/([^/]+) ]]; then - PROJECT_ID=${BASH_REMATCH[1]} - INSTANCE_ID=${BASH_REMATCH[2]} - TABLE_ID=${BASH_REMATCH[3]} +if [[ "${TABLE_NAME}" =~ ^projects/([^/]+)/instances/([^/]+)/tables/([^/]+)$ ]]; then + PROJECT_ID="${BASH_REMATCH[1]}" + INSTANCE_ID="${BASH_REMATCH[2]}" + TABLE_ID="${BASH_REMATCH[3]}" else - echo "Invalid table name: $TABLE_NAME" 1>&2 + echo "Usage: $0 projects//instances//tables/ [admin-endpoint] [impersonate-service-account]" >&2 + echo "Invalid table name: ${TABLE_NAME}" >&2 exit 1 fi +MATERIALIZED_VIEW_ID="${TABLE_ID}-mv" + +GCLOUD_AUTH_ARGS=() +CBT_ARGS=(-project="${PROJECT_ID}" -instance="${INSTANCE_ID}") +if [[ -n "${ADMIN_HOST}" ]]; then + CBT_ARGS+=(-admin-endpoint="${ADMIN_HOST}") +fi +if [[ -n "${IMPERSONATE_SA}" ]]; then + GCLOUD_AUTH_ARGS+=(--impersonate-service-account="${IMPERSONATE_SA}") + ACCESS_TOKEN="$(gcloud auth print-access-token "${GCLOUD_AUTH_ARGS[@]}")" + CBT_ARGS+=(-access-token="${ACCESS_TOKEN}") +elif [[ -n "${GOOGLE_APPLICATION_CREDENTIALS:-}" ]]; then + CBT_ARGS+=(-creds="${GOOGLE_APPLICATION_CREDENTIALS}") +fi + call_cbt() { - cbt -admin-endpoint="${ADMIN_HOST}" -project "${PROJECT_ID}" -instance "${INSTANCE_ID}" "$@" + cbt "${CBT_ARGS[@]}" "$@" } -# Ensure that the instance exists. -if ! call_cbt listinstances | grep -Eq "^${INSTANCE_ID}([[:space:]]|$)"; then +call_gcloud() { + local env_args=() + if [[ -n "${ADMIN_HOST}" ]]; then + env_args+=("CLOUDSDK_API_ENDPOINT_OVERRIDES_BIGTABLEADMIN=https://${ADMIN_HOST%:443}/") + fi + if [[ -z "${IMPERSONATE_SA}" && -n "${GOOGLE_APPLICATION_CREDENTIALS:-}" ]]; then + env_args+=("CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE=${GOOGLE_APPLICATION_CREDENTIALS}") + fi + if [[ "${#env_args[@]}" -gt 0 ]]; then + env "${env_args[@]}" gcloud --project="${PROJECT_ID}" --quiet "${GCLOUD_AUTH_ARGS[@]}" "$@" + else + gcloud --project="${PROJECT_ID}" --quiet "${GCLOUD_AUTH_ARGS[@]}" "$@" + fi +} + +resolve_protoc() { + if [[ -n "${PROTOC:-}" ]]; then + echo "${PROTOC}" + return + fi + if command -v protoc >/dev/null 2>&1; then + command -v protoc + return + fi + local cached_protoc="" + if [[ -d "${HOME}/.m2/repository/com/google/protobuf/protoc" ]]; then + cached_protoc="$(find "${HOME}/.m2/repository/com/google/protobuf/protoc" -name 'protoc-*.exe' 2>/dev/null | sort -V | tail -n 1)" + fi + if [[ -z "${cached_protoc}" ]]; then + echo "Downloading protoc via Maven protobuf-maven-plugin..." >&2 + mvn -q -f "${JAVA_BIGTABLE_DIR}/google-cloud-bigtable/pom.xml" protobuf:test-compile >&2 + cached_protoc="$(find "${HOME}/.m2/repository/com/google/protobuf/protoc" -name 'protoc-*.exe' 2>/dev/null | sort -V | tail -n 1)" + fi + if [[ -z "${cached_protoc}" ]]; then + echo "Unable to locate protoc binary; install protoc or set PROTOC=/path/to/protoc." >&2 + exit 1 + fi + local tmp_protoc="${TMP_DIR}/protoc" + cp "${cached_protoc}" "${tmp_protoc}" + chmod +x "${tmp_protoc}" + echo "${tmp_protoc}" +} + +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "${TMP_DIR}"' EXIT + +# 1. Ensure that the instance exists. +INSTANCES="$(call_cbt listinstances)" +if ! echo "${INSTANCES}" | grep -Eq "^${INSTANCE_ID}([[:space:]]|$)"; then + echo "Creating instance ${INSTANCE_ID} in ${PROJECT_ID} (${ZONE})..." call_cbt createinstance "${INSTANCE_ID}" "${INSTANCE_ID}" "${INSTANCE_ID}-c0" "${ZONE}" 1 SSD fi -# Ensure that the table exists. -if ! call_cbt -instance "$INSTANCE_ID" ls | grep -q "^${TABLE_ID}\$"; then - call_cbt createtable "$TABLE_ID" "families=$FAMILY:maxversions=1||maxage=1h" +# 2. Ensure that the shared table and required column families exist. +TABLES="$(call_cbt ls)" +if ! echo "${TABLES}" | grep -qx "${TABLE_ID}"; then + echo "Creating table ${TABLE_ID} with families ${FAMILY} and ${HISTORY_FAMILY}..." + call_cbt createtable "${TABLE_ID}" \ + "families=${FAMILY}:maxversions=1||maxage=1h,${HISTORY_FAMILY}:maxversions=10||maxage=1h" +else + EXISTING_FAMILIES="$(call_cbt ls "${TABLE_ID}" | awk 'NR>2 {print $1}')" + if ! echo "${EXISTING_FAMILIES}" | grep -qx "${FAMILY}"; then + echo "Creating column family ${FAMILY} on ${TABLE_ID}..." + call_cbt createfamily "${TABLE_ID}" "${FAMILY}" + call_cbt setgcpolicy "${TABLE_ID}" "${FAMILY}" maxversions=1 or maxage=1h + fi + if ! echo "${EXISTING_FAMILIES}" | grep -qx "${HISTORY_FAMILY}"; then + echo "Creating column family ${HISTORY_FAMILY} on ${TABLE_ID}..." + call_cbt createfamily "${TABLE_ID}" "${HISTORY_FAMILY}" + call_cbt setgcpolicy "${TABLE_ID}" "${HISTORY_FAMILY}" maxversions=10 or maxage=1h + fi fi + +# 3. Ensure that the shared AuthorizedView exists on . +AUTHORIZED_VIEWS="$( + call_gcloud bigtable authorized-views list \ + --instance="${INSTANCE_ID}" \ + --table="${TABLE_ID}" \ + --format="value(name.basename())" +)" +if ! echo "${AUTHORIZED_VIEWS}" | grep -qx "${AUTHORIZED_VIEW_ID}"; then + echo "Creating authorized view ${AUTHORIZED_VIEW_ID} on ${TABLE_ID}..." + AV_DEF_FILE="${TMP_DIR}/authorized_view.json" + cat > "${AV_DEF_FILE}" <. +MATERIALIZED_VIEWS="$( + call_gcloud bigtable materialized-views list \ + --instance="${INSTANCE_ID}" \ + --format="value(name.basename())" +)" +if ! echo "${MATERIALIZED_VIEWS}" | grep -qx "${MATERIALIZED_VIEW_ID}"; then + echo "Creating materialized view ${MATERIALIZED_VIEW_ID} on ${INSTANCE_ID}..." + call_gcloud bigtable materialized-views create "${MATERIALIZED_VIEW_ID}" \ + --instance="${INSTANCE_ID}" \ + --query="SELECT _key, MAX(${FAMILY}['column']) AS column FROM \`${TABLE_ID}\` GROUP BY _key" \ + --deletion-protection=false +fi + +# 5. Ensure that the shared SchemaBundle exists on . +SCHEMA_BUNDLES="$( + call_gcloud bigtable schema-bundles list \ + --instance="${INSTANCE_ID}" \ + --table="${TABLE_ID}" \ + --format="value(name.basename())" +)" +if ! echo "${SCHEMA_BUNDLES}" | grep -qx "${SCHEMA_BUNDLE_ID}"; then + echo "Creating schema bundle ${SCHEMA_BUNDLE_ID} on ${TABLE_ID}..." + PROTOC_BIN="$(resolve_protoc)" + PROTO_DIR="${JAVA_BIGTABLE_DIR}/google-cloud-bigtable/src/test/proto" + DESC_FILE="${TMP_DIR}/schema_bundle_descriptors.pb" + "${PROTOC_BIN}" \ + --proto_path="${PROTO_DIR}" \ + --include_imports \ + --descriptor_set_out="${DESC_FILE}" \ + "${PROTO_DIR}/singer.proto" \ + "${PROTO_DIR}/album.proto" + call_gcloud bigtable schema-bundles create "${SCHEMA_BUNDLE_ID}" \ + --instance="${INSTANCE_ID}" \ + --table="${TABLE_ID}" \ + --proto-descriptors-file="${DESC_FILE}" +fi + +echo "Shared test resources verified for ${TABLE_NAME} (${ADMIN_HOST:-default})." From ae3f43371e5a691ea1a2bf56b612cb9a6d0a8e6c Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 30 Nov 2026 11:40:20 -0500 Subject: [PATCH 48/57] chore(ci): remove unused scorecard.yml workflow (#15219) Remove the unused and previously disabled `scorecard.yml` workflow. Fixes #11792 b/587916525 --- .github/workflows/scorecard.yml | 72 --------------------------------- 1 file changed, 72 deletions(-) delete mode 100644 .github/workflows/scorecard.yml 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 From 5121d5c3dcbd5909fa258350c6d2eba9e268cfb9 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 30 Nov 2026 11:56:48 -0500 Subject: [PATCH 49/57] chore(ci): cache JDK 8 toolcache and upgrade setup-java in java-storage-nio-ci (#15196) Cache Temurin JDK 8 and upgrade `actions/setup-java` to `v5.4.0` in `java-storage-nio-ci.yaml` to avoid transient JDK 8 download failures. b/588462105 --- .github/workflows/java-storage-nio-ci.yaml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) 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 From 8df278260d1ea6a1bd4440baeaeb794c1bbaae0c Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 30 Nov 2026 12:05:12 -0500 Subject: [PATCH 50/57] chore(firestore): ignore flaky ITQueryWatchTest.shutdownNowTerminatesActiveListener (#15284) Disable flaky `ITQueryWatchTest.shutdownNowTerminatesActiveListener` with `@Ignore` while tracked for a root-cause fix. b/580634330 --- .../java/com/google/cloud/firestore/it/ITQueryWatchTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/java-firestore/google-cloud-firestore/src/test/java/com/google/cloud/firestore/it/ITQueryWatchTest.java b/java-firestore/google-cloud-firestore/src/test/java/com/google/cloud/firestore/it/ITQueryWatchTest.java index 5bd5790569ef..ccfa32b8ade7 100644 --- a/java-firestore/google-cloud-firestore/src/test/java/com/google/cloud/firestore/it/ITQueryWatchTest.java +++ b/java-firestore/google-cloud-firestore/src/test/java/com/google/cloud/firestore/it/ITQueryWatchTest.java @@ -79,6 +79,7 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.Before; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; @@ -633,6 +634,7 @@ private static void assertQueryResultContainsDocsInOrder(Query query, String... assertThat(actualDocIds).containsExactlyElementsIn(docIds).inOrder(); } + @Ignore("b/580634330") @Test public void shutdownNowTerminatesActiveListener() throws Exception { Query query = randomColl.whereEqualTo("foo", "bar"); From a46429d871e3a4d0451b55acdba6ce89a178f4f0 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Mon, 30 Nov 2026 12:07:08 -0500 Subject: [PATCH 51/57] fix(auth): reject non-default universe refreshes for ServiceAccountCredentials and UserCredentials (#15245) Updates OAuth2 token refresh and JSON loading for non-default universe domains: - Rejects `ServiceAccountCredentials.refreshAccessToken()` when `getUniverseDomain()` is not `googleapis.com`, since OAuth2 token exchange is only supported in `googleapis.com`, and clarifies in Javadoc that `refreshAccessToken()` only applies to the OAuth2 access token flow (not self-signed JWT authentication). - Rejects `authorized_user` JSON with a non-default `universe_domain` in `UserCredentials.fromJson()`, and rejects `UserCredentials` refreshes whenever `getUniverseDomain()` is not `googleapis.com`. - Updates two pre-existing custom-universe CAB unit tests (`ClientSideCredentialAccessBoundaryFactoryTest.fetchIntermediateCredentials_withCustomUniverseDomain` and `DownscopedCredentialsTest.refreshAccessToken_withCustomUniverseDomain`) to use a custom-universe `GoogleCredentials` stub. Those two tests previously constructed a non-default-universe `ServiceAccountCredentials` and called `refreshAccessToken()` on it, so updating them here keeps CI green. All CAB production changes and new CAB tests live in the stacked follow-up PR #15172. --- ...deCredentialAccessBoundaryFactoryTest.java | 19 ++- .../oauth2/ServiceAccountCredentials.java | 22 ++- .../google/auth/oauth2/UserCredentials.java | 42 ++++-- .../oauth2/DownscopedCredentialsTest.java | 18 ++- .../oauth2/ServiceAccountCredentialsTest.java | 112 +++++++++++++++ .../auth/oauth2/UserCredentialsTest.java | 132 +++++++++++++++++- 6 files changed, 322 insertions(+), 23 deletions(-) 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..7da107f4a9cd 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 @@ -67,6 +67,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; @@ -158,10 +159,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 +172,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 @@ -611,6 +609,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/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java index b06e324a0dd2..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 @@ -525,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); 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/ServiceAccountCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java index 8b795c05aaeb..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"; 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, From 56cdb1c1918b34366a6715b182f14fc1565f4e02 Mon Sep 17 00:00:00 2001 From: Jin Seop Kim Date: Mon, 30 Nov 2026 12:18:07 -0500 Subject: [PATCH 52/57] chore(auth): synchronize async refresh tests with CountDownLatch in ClientSideCredentialAccessBoundaryFactoryTest (#15249) Synchronize `refreshCredentialsIfRequired_asyncSingleThread` and `refreshCredentialsIfRequired_asyncMultiThread` with `CountDownLatch` and remove `Thread.sleep` to eliminate timing flakiness. Fixes #12575 b/590334802 --- ...deCredentialAccessBoundaryFactoryTest.java | 81 ++++++++++++------- 1 file changed, 50 insertions(+), 31 deletions(-) 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 7da107f4a9cd..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; @@ -92,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)) { @@ -112,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; } @@ -280,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()); } @@ -352,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. @@ -365,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()); } From a337423a2da95eb3f29e4f2aad52eff62e6f04b8 Mon Sep 17 00:00:00 2001 From: Igor Bernstein Date: Mon, 30 Nov 2026 12:27:38 -0500 Subject: [PATCH 53/57] test(bigtable): use shared AuthorizedView across Data ITs (#15247) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **PR Stack (Reduce Admin API usage in Bigtable Data ITs):** 1. #15246 — Shared Data IT resource setup (`scripts/setup-test-table.sh`) and lazy `CloudEnv` admin clients 2. **#15247 (This PR)** — Mechanical swap to shared `AuthorizedView` across 7 Data ITs 3. #15248 — Shared `MaterializedView`, `ExecuteQueryIT` (`cf_history` + `SchemaBundle`), and `LargeRowIT` bounded scans --- Replace per-test `createAuthorizedView` and `deleteAuthorizedView` calls across the 7 Data integration test classes (11 test methods: `BulkMutateIT`, `BulkReadIT`, `CheckAndMutateIT`, `MutateRowIT`, `ReadIT`, `ReadModifyWriteIT`, and `RowMutationEntryBatcherIT`) with the pre-provisioned `test-authorized-view` from `AbstractTestEnv#getAuthorizedViewId()`. - Eliminates 22 `TableAdmin` mutations per Data IT job run. - Fixes an `AuthorizedView` leak when tests fail mid-execution (previously view IDs used raw UUIDs without `finally`, which `StaleResourceCleaner` could not identify). --- .../bigtable/data/v2/it/BulkMutateIT.java | 26 +---- .../cloud/bigtable/data/v2/it/BulkReadIT.java | 18 +--- .../bigtable/data/v2/it/CheckAndMutateIT.java | 22 +---- .../bigtable/data/v2/it/MutateRowIT.java | 23 +---- .../cloud/bigtable/data/v2/it/ReadIT.java | 96 ++++--------------- .../data/v2/it/ReadModifyWriteIT.java | 21 +--- .../data/v2/it/RowMutationEntryBatcherIT.java | 14 +-- .../AuthorizedViewTestHelper.java | 62 ++---------- 8 files changed, 53 insertions(+), 229 deletions(-) diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkMutateIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkMutateIT.java index dd3ea81d663b..e8b37f2b5625 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkMutateIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkMutateIT.java @@ -17,7 +17,6 @@ import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.fail; @@ -27,7 +26,6 @@ import com.google.api.gax.batching.BatcherImpl; import com.google.api.gax.batching.BatchingSettings; import com.google.api.gax.batching.FlowControlEventStats; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.BigtableDataSettings; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; @@ -110,12 +108,10 @@ public void testOnAuthorizedView() throws IOException, InterruptedException { BigtableDataSettings.Builder builder = settings.toBuilder().enableBatchMutationLatencyBasedThrottling(2L); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); try (BigtableDataClient client = BigtableDataClient.create(builder.build()); - Batcher batcher = - client.newBulkMutationBatcher( - AuthorizedViewId.of(testEnvRule.env().getTableId(), testAuthorizedView.getId()))) { + Batcher batcher = client.newBulkMutationBatcher(authorizedViewId)) { String familyId = testEnvRule.env().getFamilyId(); @@ -135,12 +131,6 @@ public void testOnAuthorizedView() throws IOException, InterruptedException { .call(Query.create(testEnvRule.env().getTableId()).rowKey(rowPrefix + "test-key")); assertThat(row.getCells()).hasSize(1); } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } @Test @@ -211,7 +201,7 @@ public void testManyMutationsOnAuthorizedView() throws IOException, InterruptedE .that(testEnvRule.env().isSessionsEnabled()) .isFalse(); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); BigtableDataSettings settings = testEnvRule.env().getDataClientSettings(); String rowPrefix = AUTHORIZED_VIEW_ROW_PREFIX + UUID.randomUUID(); @@ -225,9 +215,7 @@ public void testManyMutationsOnAuthorizedView() throws IOException, InterruptedE .setBatchingSettings( batchingSettings.toBuilder().setDelayThreshold(Duration.ofHours(1)).build()); try (BigtableDataClient client = BigtableDataClient.create(settings)) { - Batcher batcher = - client.newBulkMutationBatcher( - AuthorizedViewId.of(testEnvRule.env().getTableId(), testAuthorizedView.getId())); + Batcher batcher = client.newBulkMutationBatcher(authorizedViewId); String familyId = testEnvRule.env().getFamilyId(); for (int i = 0; i < 2; i++) { String key = rowPrefix + "test-key"; @@ -262,11 +250,5 @@ public void testManyMutationsOnAuthorizedView() throws IOException, InterruptedE // ignore } } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkReadIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkReadIT.java index a14029294f3f..7802428fb234 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkReadIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/BulkReadIT.java @@ -15,14 +15,14 @@ */ package com.google.cloud.bigtable.data.v2.it; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; +import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; +import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.batching.Batcher; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; import com.google.cloud.bigtable.data.v2.models.BulkMutation; @@ -46,8 +46,6 @@ public class BulkReadIT { @ClassRule public static TestEnvRule testEnvRule = new TestEnvRule(); - private static String AUTHORIZED_VIEW_ROW_PREFIX = "row#"; - private static String AUTHORIZED_VIEW_COLUMN_QUALIFIER = "qualifier"; @Test public void testBulkRead() throws InterruptedException, ExecutionException { @@ -117,7 +115,7 @@ public void testBulkReadOnAuthorizedView() throws InterruptedException, Executio .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); BigtableDataClient client = testEnvRule.env().getDataClient(); String family = testEnvRule.env().getFamilyId(); @@ -149,9 +147,7 @@ public void testBulkReadOnAuthorizedView() throws InterruptedException, Executio .setCell(family, "outside-authorized-view", 10_000L, "test-value")); client.bulkMutateRows(bulkMutation); - try (Batcher batcher = - client.newBulkReadRowsBatcher( - AuthorizedViewId.of(testEnvRule.env().getTableId(), testAuthorizedView.getId()))) { + try (Batcher batcher = client.newBulkReadRowsBatcher(authorizedViewId)) { List> rowFutures = new ArrayList<>(numRows); @@ -186,11 +182,5 @@ public void testBulkReadOnAuthorizedView() throws InterruptedException, Executio assertThat(actualRows.get(2)).isEqualTo(expectedRows.get(0)); assertThat(actualRows.get(3)).isNull(); } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/CheckAndMutateIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/CheckAndMutateIT.java index 8a9dddbb21cc..c744edaca1e1 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/CheckAndMutateIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/CheckAndMutateIT.java @@ -18,13 +18,11 @@ import static com.google.cloud.bigtable.data.v2.models.Filters.FILTERS; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.fail; import com.google.api.gax.rpc.PermissionDeniedException; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; import com.google.cloud.bigtable.data.v2.models.ConditionalRowMutation; @@ -100,7 +98,7 @@ public void testOnAuthorizedView() throws Exception { .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); TableId tableId = testEnvRule.env().getTableId(); String familyId = testEnvRule.env().getFamilyId(); @@ -110,14 +108,13 @@ public void testOnAuthorizedView() throws Exception { dataClient .mutateRowCallable() .call( - RowMutation.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) + RowMutation.create(authorizedViewId, rowKey) .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "1", "val1") .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "2", "val2")); dataClient .checkAndMutateRowAsync( - ConditionalRowMutation.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) + ConditionalRowMutation.create(authorizedViewId, rowKey) .condition(FILTERS.qualifier().exactMatch(AUTHORIZED_VIEW_COLUMN_QUALIFIER + "1")) .then( Mutation.create() @@ -139,9 +136,7 @@ public void testOnAuthorizedView() throws Exception { try { dataClient .checkAndMutateRowAsync( - ConditionalRowMutation.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - rowKeyOutsideAuthorizedView) + ConditionalRowMutation.create(authorizedViewId, rowKeyOutsideAuthorizedView) .condition(FILTERS.qualifier().exactMatch(AUTHORIZED_VIEW_COLUMN_QUALIFIER)) .then(Mutation.create().setCell(familyId, "new_qualifier", "new-value"))) .get(1, TimeUnit.MINUTES); @@ -154,8 +149,7 @@ public void testOnAuthorizedView() throws Exception { try { dataClient .checkAndMutateRowAsync( - ConditionalRowMutation.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) + ConditionalRowMutation.create(authorizedViewId, rowKey) .condition(FILTERS.qualifier().exactMatch(AUTHORIZED_VIEW_COLUMN_QUALIFIER)) .then(Mutation.create().setCell(familyId, "new_qualifier", "new-value"))) .get(1, TimeUnit.MINUTES); @@ -163,11 +157,5 @@ public void testOnAuthorizedView() throws Exception { } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(PermissionDeniedException.class); } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/MutateRowIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/MutateRowIT.java index a54c7268276f..3acf3853a60b 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/MutateRowIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/MutateRowIT.java @@ -17,13 +17,11 @@ import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.fail; import com.google.api.gax.rpc.PermissionDeniedException; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; import com.google.cloud.bigtable.data.v2.models.Query; import com.google.cloud.bigtable.data.v2.models.Row; @@ -87,7 +85,7 @@ public void testOnAuthorizedView() throws Exception { .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); String rowKey = AUTHORIZED_VIEW_ROW_PREFIX + UUID.randomUUID(); String familyId = testEnvRule.env().getFamilyId(); @@ -96,9 +94,7 @@ public void testOnAuthorizedView() throws Exception { .env() .getDataClient() .mutateRowAsync( - RowMutation.create( - AuthorizedViewId.of(testEnvRule.env().getTableId(), testAuthorizedView.getId()), - rowKey) + RowMutation.create(authorizedViewId, rowKey) .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER, "myVal") .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "2", "myVal2") .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "3", "myVal3") @@ -109,9 +105,7 @@ public void testOnAuthorizedView() throws Exception { .env() .getDataClient() .mutateRowAsync( - RowMutation.create( - AuthorizedViewId.of(testEnvRule.env().getTableId(), testAuthorizedView.getId()), - rowKey) + RowMutation.create(authorizedViewId, rowKey) .deleteCells(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "2")) .get(1, TimeUnit.MINUTES); @@ -136,21 +130,12 @@ public void testOnAuthorizedView() throws Exception { .env() .getDataClient() .mutateRowAsync( - RowMutation.create( - AuthorizedViewId.of( - testEnvRule.env().getTableId(), testAuthorizedView.getId()), - rowKeyOutsideAuthorizedView) + RowMutation.create(authorizedViewId, rowKeyOutsideAuthorizedView) .setCell(familyId, AUTHORIZED_VIEW_COLUMN_QUALIFIER, "myVal")) .get(1, TimeUnit.MINUTES); fail("Should not be able to mutate row outside authorized view"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(PermissionDeniedException.class); } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadIT.java index 67b192e9785a..09f1755a2149 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadIT.java @@ -17,7 +17,6 @@ import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; @@ -32,7 +31,6 @@ import com.google.api.gax.rpc.StreamController; import com.google.cloud.bigtable.admin.v2.BigtableInstanceAdminClient; import com.google.cloud.bigtable.admin.v2.BigtableTableAdminClient; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.admin.v2.models.CreateMaterializedViewRequest; import com.google.cloud.bigtable.admin.v2.models.CreateTableRequest; import com.google.cloud.bigtable.data.v2.BigtableDataClient; @@ -119,11 +117,10 @@ public void isRowExistsOnAuthorizedView() throws Exception { BigtableDataClient dataClient = testEnvRule.env().getDataClient(); TableId tableId = testEnvRule.env().getTableId(); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); String rowKey = AUTHORIZED_VIEW_ROW_PREFIX + prefix + "-isRowExistsOnAuthorizedView"; String rowKeyOutsideAuthorizedView = prefix + "-isRowExistsOnAuthorizedView"; - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); - dataClient.mutateRow( RowMutation.create(tableId, rowKey) .setCell(testEnvRule.env().getFamilyId(), AUTHORIZED_VIEW_COLUMN_QUALIFIER, "value")); @@ -131,32 +128,13 @@ public void isRowExistsOnAuthorizedView() throws Exception { RowMutation.create(tableId, rowKeyOutsideAuthorizedView) .setCell(testEnvRule.env().getFamilyId(), AUTHORIZED_VIEW_COLUMN_QUALIFIER, "value")); - assertThat(dataClient.exists(AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey)) - .isTrue(); - assertThat( - dataClient.exists( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - rowKeyOutsideAuthorizedView)) - .isFalse(); + assertThat(dataClient.exists(authorizedViewId, rowKey)).isTrue(); + assertThat(dataClient.exists(authorizedViewId, rowKeyOutsideAuthorizedView)).isFalse(); // Async - assertThat( - dataClient - .existsAsync(AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) - .get()) - .isTrue(); - assertThat( - dataClient - .existsAsync( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - rowKeyOutsideAuthorizedView) - .get()) + assertThat(dataClient.existsAsync(authorizedViewId, rowKey).get()).isTrue(); + assertThat(dataClient.existsAsync(authorizedViewId, rowKeyOutsideAuthorizedView).get()) .isFalse(); - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView(tableId.getTableId(), testAuthorizedView.getId()); } @Test @@ -184,17 +162,14 @@ public void readEmptyOnAuthorizedView() throws Throwable { .isNotInstanceOf(EmulatorEnv.class); TableId tableId = testEnvRule.env().getTableId(); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); BigtableDataClient dataClient = testEnvRule.env().getDataClient(); String uniqueKey = AUTHORIZED_VIEW_ROW_PREFIX + prefix + "-readEmptyOnAuthorizedView"; String uniqueKeyOutsideAuthorizedView = prefix + "-readEmptyOnAuthorizedView"; - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); - - Query query = - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())).rowKey(uniqueKey); + Query query = Query.create(authorizedViewId).rowKey(uniqueKey); Query queryOutsideAuthorizedView = - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) - .rowKey(uniqueKeyOutsideAuthorizedView); + Query.create(authorizedViewId).rowKey(uniqueKeyOutsideAuthorizedView); // Sync ArrayList rows = Lists.newArrayList(dataClient.readRows(query)); @@ -218,11 +193,6 @@ public void readEmptyOnAuthorizedView() throws Throwable { testEnvRule.env().getDataClient().readRowsAsync(queryOutsideAuthorizedView, observer); observer.awaitCompletion(); assertThat(observer.responses).isEmpty(); - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView(tableId.getTableId(), testAuthorizedView.getId()); } @Test @@ -342,10 +312,9 @@ public void readOnAuthorizedView() throws Throwable { String uniqueKey = AUTHORIZED_VIEW_ROW_PREFIX + prefix + "-readOnAuthorizedView"; String uniqueKeyOutsideAuthorizedView = prefix + "-readOnAuthorizedView"; TableId tableId = testEnvRule.env().getTableId(); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); BigtableDataClient dataClient = testEnvRule.env().getDataClient(); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); - long timestampMicros = System.currentTimeMillis() * 1_000; for (int i = 0; i < numRows; i++) { @@ -384,11 +353,9 @@ public void readOnAuthorizedView() throws Throwable { } // Sync - Query query = - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) - .range(uniqueKey + "-0", uniqueKey + "-" + numRows); + Query query = Query.create(authorizedViewId).range(uniqueKey + "-0", uniqueKey + "-" + numRows); Query queryOutsideAuthorizedView = - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) + Query.create(authorizedViewId) .range( uniqueKeyOutsideAuthorizedView + "-0", uniqueKeyOutsideAuthorizedView + "-" + numRows); @@ -413,37 +380,22 @@ public void readOnAuthorizedView() throws Throwable { assertThat(observer.responses).isEmpty(); // Point Sync - Row actualRow = - dataClient.readRow( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), expectedRows.get(0).getKey()); + Row actualRow = dataClient.readRow(authorizedViewId, expectedRows.get(0).getKey()); assertThat(actualRow).isEqualTo(expectedRows.get(0)); // Row exists but outside the authorized view - assertThat( - dataClient.readRow( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - uniqueKeyOutsideAuthorizedView + "-0")) + assertThat(dataClient.readRow(authorizedViewId, uniqueKeyOutsideAuthorizedView + "-0")) .isNull(); // Point Async ApiFuture actualRowFuture = - dataClient.readRowAsync( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), expectedRows.get(0).getKey()); + dataClient.readRowAsync(authorizedViewId, expectedRows.get(0).getKey()); assertThat(actualRowFuture.get()).isEqualTo(expectedRows.get(0)); // Row exists but outside the authorized view assertThat( - dataClient - .readRowAsync( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - uniqueKeyOutsideAuthorizedView + "-0") - .get()) + dataClient.readRowAsync(authorizedViewId, uniqueKeyOutsideAuthorizedView + "-0").get()) .isNull(); - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView(tableId.getTableId(), testAuthorizedView.getId()); } @Test @@ -518,7 +470,7 @@ public void rangeQueries() { } @Test - public void rangeQueriesOnAuthorizedView() throws InterruptedException { + public void rangeQueriesOnAuthorizedView() { assume() .withMessage("AuthorizedView is not supported on Emulator") .that(testEnvRule.env()) @@ -526,14 +478,13 @@ public void rangeQueriesOnAuthorizedView() throws InterruptedException { BigtableDataClient client = testEnvRule.env().getDataClient(); TableId tableId = testEnvRule.env().getTableId(); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); String familyId = testEnvRule.env().getFamilyId(); String uniqueKey = AUTHORIZED_VIEW_ROW_PREFIX + prefix + "-rangeQueriesOnAuthorizedView"; String keyA = uniqueKey + "-" + "a"; String keyZ = uniqueKey + "-" + "z"; String keyOutsideAuthorizedView = prefix; - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); - long timestampMicros = System.currentTimeMillis() * 1_000; client.bulkMutateRows( @@ -578,7 +529,7 @@ public void rangeQueriesOnAuthorizedView() throws InterruptedException { assertThat( ImmutableList.copyOf( client.readRows( - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) + Query.create(authorizedViewId) .range(ByteStringRange.unbounded().startClosed(keyA).endOpen(keyZ))))) .containsExactly(expectedRowA); @@ -586,7 +537,7 @@ public void rangeQueriesOnAuthorizedView() throws InterruptedException { assertThat( ImmutableList.copyOf( client.readRows( - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) + Query.create(authorizedViewId) .range(ByteStringRange.unbounded().startClosed(keyA).endClosed(keyZ))))) .containsExactly(expectedRowA, expectedRowZ); @@ -594,7 +545,7 @@ public void rangeQueriesOnAuthorizedView() throws InterruptedException { assertThat( ImmutableList.copyOf( client.readRows( - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) + Query.create(authorizedViewId) .range(ByteStringRange.unbounded().startOpen(keyA).endClosed(keyZ))))) .containsExactly(expectedRowZ); @@ -602,14 +553,9 @@ public void rangeQueriesOnAuthorizedView() throws InterruptedException { assertThat( ImmutableList.copyOf( client.readRows( - Query.create(AuthorizedViewId.of(tableId, testAuthorizedView.getId())) + Query.create(authorizedViewId) .range(ByteStringRange.unbounded().startOpen(keyA).endOpen(keyZ))))) .isEmpty(); - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView(tableId.getTableId(), testAuthorizedView.getId()); } @Test diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadModifyWriteIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadModifyWriteIT.java index 65bf6a226096..06aeacda4575 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadModifyWriteIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/ReadModifyWriteIT.java @@ -17,13 +17,11 @@ import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.fail; import com.google.api.gax.rpc.PermissionDeniedException; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; import com.google.cloud.bigtable.data.v2.models.ReadModifyWriteRow; import com.google.cloud.bigtable.data.v2.models.Row; @@ -87,9 +85,8 @@ public void testOnAuthorizedView() .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); - TableId tableId = testEnvRule.env().getTableId(); String family = testEnvRule.env().getFamilyId(); String rowKey = AUTHORIZED_VIEW_ROW_PREFIX + UUID.randomUUID(); @@ -98,8 +95,7 @@ public void testOnAuthorizedView() .env() .getDataClient() .readModifyWriteRowAsync( - ReadModifyWriteRow.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) + ReadModifyWriteRow.create(authorizedViewId, rowKey) .append(family, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "1", "a") .increment(family, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "2", 3) .increment(family, AUTHORIZED_VIEW_COLUMN_QUALIFIER + "3", 0x12345679)) @@ -119,9 +115,7 @@ public void testOnAuthorizedView() .env() .getDataClient() .readModifyWriteRowAsync( - ReadModifyWriteRow.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), - rowKeyOutsideAuthorizedView) + ReadModifyWriteRow.create(authorizedViewId, rowKeyOutsideAuthorizedView) .append(family, AUTHORIZED_VIEW_COLUMN_QUALIFIER, "a")) .get(1, TimeUnit.MINUTES); fail("Should not be able to modify a row outside authorized view"); @@ -135,19 +129,12 @@ public void testOnAuthorizedView() .env() .getDataClient() .readModifyWriteRowAsync( - ReadModifyWriteRow.create( - AuthorizedViewId.of(tableId, testAuthorizedView.getId()), rowKey) + ReadModifyWriteRow.create(authorizedViewId, rowKey) .append(family, "outside-authorized-view", "a")) .get(1, TimeUnit.MINUTES); fail("Should not be able to perform mutations with cells outside the authorized view"); } catch (Exception e) { assertThat(e.getCause()).isInstanceOf(PermissionDeniedException.class); } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/RowMutationEntryBatcherIT.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/RowMutationEntryBatcherIT.java index c6ace17adea8..f992a2ff2729 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/RowMutationEntryBatcherIT.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/it/RowMutationEntryBatcherIT.java @@ -17,7 +17,6 @@ import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_COLUMN_QUALIFIER; import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.AUTHORIZED_VIEW_ROW_PREFIX; -import static com.google.cloud.bigtable.misc_utilities.AuthorizedViewTestHelper.createTestAuthorizedView; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.fail; @@ -25,7 +24,6 @@ import com.google.api.core.ApiFuture; import com.google.api.gax.batching.Batcher; import com.google.api.gax.rpc.ServerStream; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; import com.google.cloud.bigtable.data.v2.BigtableDataClient; import com.google.cloud.bigtable.data.v2.models.AuthorizedViewId; import com.google.cloud.bigtable.data.v2.models.Query; @@ -92,7 +90,7 @@ public void testNewBatcherOnAuthorizedView() throws Exception { .that(testEnvRule.env()) .isNotInstanceOf(EmulatorEnv.class); - AuthorizedView testAuthorizedView = createTestAuthorizedView(testEnvRule); + AuthorizedViewId authorizedViewId = testEnvRule.env().getAuthorizedViewId(); BigtableDataClient client = testEnvRule.env().getDataClient(); TableId tableId = testEnvRule.env().getTableId(); @@ -100,7 +98,7 @@ public void testNewBatcherOnAuthorizedView() throws Exception { String rowPrefix = AUTHORIZED_VIEW_ROW_PREFIX + UUID.randomUUID(); try (Batcher batcher = - client.newBulkMutationBatcher(AuthorizedViewId.of(tableId, testAuthorizedView.getId()))) { + client.newBulkMutationBatcher(authorizedViewId)) { for (int i = 0; i < 10; i++) { @SuppressWarnings("UnusedVariable") ApiFuture ignored = @@ -131,7 +129,7 @@ public void testNewBatcherOnAuthorizedView() throws Exception { String rowKeyOutsideAuthorizedView = UUID.randomUUID() + "-outside-authorized-view"; try { try (Batcher batcher = - client.newBulkMutationBatcher(AuthorizedViewId.of(tableId, testAuthorizedView.getId()))) { + client.newBulkMutationBatcher(authorizedViewId)) { @SuppressWarnings("UnusedVariable") ApiFuture ignored = batcher.add( @@ -142,11 +140,5 @@ public void testNewBatcherOnAuthorizedView() throws Exception { } catch (Exception e) { // Ignore. } - - testEnvRule - .env() - .getTableAdminClient() - .deleteAuthorizedView( - testEnvRule.env().getTableId().getTableId(), testAuthorizedView.getId()); } } diff --git a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/misc_utilities/AuthorizedViewTestHelper.java b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/misc_utilities/AuthorizedViewTestHelper.java index 70e6a579aca3..f8b863c43ea9 100644 --- a/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/misc_utilities/AuthorizedViewTestHelper.java +++ b/java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/misc_utilities/AuthorizedViewTestHelper.java @@ -16,60 +16,14 @@ package com.google.cloud.bigtable.misc_utilities; -import com.google.api.gax.rpc.UnavailableException; -import com.google.cloud.bigtable.admin.v2.models.AuthorizedView; -import com.google.cloud.bigtable.admin.v2.models.CreateAuthorizedViewRequest; -import com.google.cloud.bigtable.admin.v2.models.FamilySubsets; -import com.google.cloud.bigtable.admin.v2.models.SubsetView; -import com.google.cloud.bigtable.data.v2.models.TableId; -import com.google.cloud.bigtable.test_helpers.env.TestEnvRule; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class AuthorizedViewTestHelper { - - public static String AUTHORIZED_VIEW_ROW_PREFIX = "row#"; - public static String AUTHORIZED_VIEW_COLUMN_QUALIFIER = "qualifier"; +/** + * Constants matching the shared pre-provisioned {@code test-authorized-view} configured by {@code + * scripts/setup-test-table.sh}. + */ +public final class AuthorizedViewTestHelper { - private static final Logger logger = Logger.getLogger(AuthorizedViewTestHelper.class.getName()); + public static final String AUTHORIZED_VIEW_ROW_PREFIX = "row#"; + public static final String AUTHORIZED_VIEW_COLUMN_QUALIFIER = "qualifier"; - public static AuthorizedView createTestAuthorizedView(TestEnvRule testEnvRule) - throws InterruptedException { - TableId tableId = testEnvRule.env().getTableId(); - String authorizedViewId = UUID.randomUUID().toString(); - CreateAuthorizedViewRequest request = - CreateAuthorizedViewRequest.of(tableId.getTableId(), authorizedViewId) - .setAuthorizedViewType( - SubsetView.create() - .addRowPrefix(AUTHORIZED_VIEW_ROW_PREFIX) - .setFamilySubsets( - testEnvRule.env().getFamilyId(), - FamilySubsets.create() - .addQualifierPrefix(AUTHORIZED_VIEW_COLUMN_QUALIFIER))) - .setDeletionProtection(false); - int retryCount = 0; - int maxRetries = 10; - while (true) { - try { - return testEnvRule.env().getTableAdminClient().createAuthorizedView(request); - } catch (UnavailableException e) { - if (++retryCount == maxRetries) { - throw e; - } - logger.log( - Level.INFO, - "Retrying createAuthorizedView " - + authorizedViewId - + " in table " - + tableId - + ", retryCount: " - + retryCount); - // Exponential backoff delay starting at 100ms. - double expSleep = 100 * Math.pow(2, retryCount); - Thread.sleep(Math.min((long) expSleep, TimeUnit.MINUTES.toMillis(1))); - } - } - } + private AuthorizedViewTestHelper() {} } From 884dea1371cbb9e4e31810a7d6fe104da9aa3627 Mon Sep 17 00:00:00 2001 From: Min Zhu Date: Mon, 30 Nov 2026 14:13:27 -0500 Subject: [PATCH 54/57] chore: bump fmt-maven-plugin to 2.29 and enable long string reflowing (#15028) ## Summary Converges the PR `lint` formatter (`fmt-maven-plugin`) with the `librarian generate` formatter (`google-java-format` CLI) so long string literals are reflowed consistently before PRs are merged to `main` (see #14862, #14896). Passing `--skip-reflowing-long-strings` in Librarian instead would lead to more generated code changes and use non-standard behavior of `google-java-format`, so aligning `fmt-maven-plugin` in `java-shared-config` with the standard `google-java-format` default is preferred. ## Changes - Bumps `com.spotify.fmt:fmt-maven-plugin` from `2.25` to `2.29` in `java-shared-config/java-shared-config/pom.xml`. - Sets `false` so `StringWrapper.wrap` is executed, matching the default behavior of the `google-java-format` CLI. - Keeps `google-java-format` explicitly pinned to `${google-java-format.version}` (`1.25.2`), so Librarian does not need any version change. ## Follow-up Work Formatting updates for pre-existing non-complying modules are separated out into follow-up PRs so this `java-shared-config` update can land cleanly without triggering unrelated downstream test suites: - **11 handwritten modules (85 files):** - `sdk-platform-java`: `gapic-generator-java` (10), `gax` (8), `gax-grpc` (1), `google-cloud-core` (3), `google-cloud-core-http` (1) - `java-bigquery/google-cloud-bigquery` (13) - `java-bigquery-jdbc` (24) - `java-spanner-jdbc` (21) - `java-storage-nio/google-cloud-nio` (2) - `grpc-gcp-java` (1) - `java-logging-logback` (1) - **3 `protoc`-generated modules (15 files, not to be formatted directly):** - `java-datamanager/proto-data-manager-v1` (11), `java-marketingplatformadminapi/proto-admin-v1alpha` (2), `java-grafeas` (2) - `google-java-format` `1.25.2` is not idempotent on `protoc`'s `descriptorData` strings (`librarian generate --all` runs a single pass matching what is on `main`, while a second pass modifies them again). `.kokoro/build.sh` currently excludes `proto-google-*` rather than `proto-*`, so those exclusions may need a follow-up before `java-shared-config` is bumped downstream. Context: b/581031020 --- java-shared-config/java-shared-config/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java-shared-config/java-shared-config/pom.xml b/java-shared-config/java-shared-config/pom.xml index 7a428420c3df..2d7d63ac98cf 100644 --- a/java-shared-config/java-shared-config/pom.xml +++ b/java-shared-config/java-shared-config/pom.xml @@ -171,10 +171,11 @@ com.spotify.fmt fmt-maven-plugin - 2.25 + 2.29 true + false From 2c38865247985a6fa48ad6af90df2e629d26f832 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:48:55 +0530 Subject: [PATCH 55/57] fix(spanner): unify streaming retry delay sanitization and backoff (#15271) ## Problem Statement - Streaming read/query resumption and `BatchWrite` retry policies implemented server `RetryInfo` parsing, retry delay clamping, exponential backoff, and retry-budget enforcement separately, leading to inconsistent behavior across Cloud Spanner streaming RPCs. - Oversized server `RetryInfo` delays were not clamped for `BatchWrite`, zero `RetryInfo` delays did not fall back to exponential backoff, malformed `RetryInfo` trailers could throw during `RESOURCE_EXHAUSTED` translation, sub-millisecond total timeouts on streaming reads/queries truncated to unlimited, and large `maxRpcTimeoutDuration` values could overflow when computing `BatchWrite` attempt timeouts. ## Solution - Unified retry delay extraction, sanitization, clamping, exponential backoff, and attempt/timeout budget checks across streaming reads/queries and `BatchWrite` while keeping per-RPC `RetrySettings` configurations completely independent. - Clamped positive server `RetryInfo` delays (`> 0`) to `[minDelay, maxRetryDelayDuration]` (defaulting the cap to `32s` when unset, preserving positive sub-millisecond delays for `BatchWrite`, and flooring them at `1ms` for streaming reads/queries), while falling back to exponential backoff on absent, malformed, zero, or negative server retry delays. - Hardened `RetryInfo` trailer and error-details parsing so malformed payloads never crash exception translation or retry evaluation, while preserving `SpannerException#getRetryDelayInMillis()` return values for valid durations (malformed payloads now return `-1` instead of throwing). - Unified client-side exponential backoff on `[0.5x, 1.0x]` full-band jitter (lowering mean default streaming read/query backoff from `1.0x` to `0.75x` while ensuring backoff never exceeds `maxRetryDelayDuration`) and enforced nanosecond-precision total timeouts and overflow-safe RPC timeout saturation. --- .../spanner/ResumableStreamIterator.java | 142 ++---- .../cloud/spanner/SpannerException.java | 24 +- .../cloud/spanner/StreamingRetryHelper.java | 261 +++++++++++ .../spanner/spi/v1/BatchWriteRetryPolicy.java | 143 +----- .../spanner/ResumableStreamIteratorTest.java | 171 ++++--- .../spanner/SpannerExceptionFactoryTest.java | 41 ++ .../spanner/StreamingRetryHelperTest.java | 425 ++++++++++++++++++ .../spi/v1/BatchWriteRetryPolicyTest.java | 205 ++++++++- 8 files changed, 1075 insertions(+), 337 deletions(-) create mode 100644 java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/StreamingRetryHelper.java create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/StreamingRetryHelperTest.java 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 9ad1f3621a01..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,12 +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; @@ -64,8 +61,10 @@ * 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. Positive server-supplied retry delays are capped at {@link - * RetrySettings#getMaxRetryDelayDuration()} (defaulting to 32s when unset or non-positive), and - * missing or non-positive server retry delays fall back to exponential backoff. + * 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 @@ -92,9 +91,8 @@ abstract class ResumableStreamIterator extends AbstractIterator retryableCodes; - private static final long DEFAULT_MAX_RETRY_DELAY_MILLIS = 32_000L; + 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; @@ -185,94 +183,17 @@ 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. */ @VisibleForTesting - boolean totalTimeoutExceeded(long proposedDelayMillis) { - long totalTimeoutMillis = streamingRetrySettings.getTotalTimeoutDuration().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; - } - - /** - * 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 zero or negative. - */ - private static long saturatedDurationMillis( - Duration duration, long nonPositiveDefaultMillis, long maxMillis) { - if (duration.isZero() || duration.isNegative()) { - return nonPositiveDefaultMillis; - } - try { - return Math.max(1L, Math.min(duration.toMillis(), maxMillis)); - } catch (ArithmeticException overflow) { - return maxMillis; - } - } - - private long effectiveMaxRetryDelayMillis() { - return saturatedDurationMillis( - streamingRetrySettings.getMaxRetryDelayDuration(), - DEFAULT_MAX_RETRY_DELAY_MILLIS, - Long.MAX_VALUE); - } - - @VisibleForTesting - BackOff newBackOff() { - int initialIntervalMillis = - (int) - saturatedDurationMillis( - streamingRetrySettings.getInitialRetryDelayDuration(), 1L, Integer.MAX_VALUE); - int maxIntervalMillis = - Math.max( - initialIntervalMillis, - (int) Math.min(effectiveMaxRetryDelayMillis(), Integer.MAX_VALUE)); - return new ExponentialBackOff.Builder() - .setMultiplier(streamingRetrySettings.getRetryDelayMultiplier()) - // All of these values must be > 0. - .setInitialIntervalMillis(initialIntervalMillis) - .setMaxIntervalMillis(maxIntervalMillis) - // 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); - } + boolean totalTimeoutExceeded(Duration proposedDelay) { + return StreamingRetryHelper.isTotalTimeoutExceeded( + streamingRetrySettings, nanoTime() - retrySequenceStartNanos, proposedDelay); } @VisibleForTesting @@ -287,10 +208,6 @@ void backoffSleep(Context context, long backoffMillis) throws SpannerException { context.addListener(listener, DirectExecutor.INSTANCE); try { - if (backoffMillis == BackOff.STOP) { - // Highly unlikely but we handle it just in case. - backoffMillis = effectiveMaxRetryDelayMillis(); - } if (latch.await(backoffMillis, TimeUnit.MILLISECONDS)) { // Woken by context cancellation. throw newSpannerExceptionForCancellation(context, null); @@ -493,42 +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: use a positive server-supplied retry delay (clamped to the - // effective max retry delay), or fall back to exponential backoff when absent or non-positive. - long delayMillis = spannerException.getRetryDelayInMillis(); - long maxRetryDelayMillis = effectiveMaxRetryDelayMillis(); - if (delayMillis <= 0L) { - if (this.backOff == null) { - this.backOff = newBackOff(); - } - long backOffMillis = nextBackOffMillis(this.backOff); - delayMillis = - backOffMillis == BackOff.STOP ? maxRetryDelayMillis : Math.max(1L, backOffMillis); - } else { - delayMillis = Math.min(delayMillis, maxRetryDelayMillis); - } + // 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) { @@ -703,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/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/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/spi/v1/BatchWriteRetryPolicy.java b/java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicy.java index c54b9ff2a7b9..603681917b49 100644 --- 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 @@ -21,22 +21,18 @@ 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; 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 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.StatusException; import io.grpc.StatusRuntimeException; -import io.grpc.protobuf.ProtoUtils; import java.time.Duration; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -45,14 +41,11 @@ import org.jspecify.annotations.Nullable; /** - * Pure retryability, backoff, {@link RetryInfo} extraction, and timeout budgeting policy for {@code + * Pure retryability, backoff, {@code RetryInfo} extraction, and timeout budgeting policy for {@code * BatchWrite} stream resumption. */ final class BatchWriteRetryPolicy { - private static final Metadata.Key KEY_RETRY_INFO = - ProtoUtils.keyForProto(RetryInfo.getDefaultInstance()); - private final RetrySettings retrySettings; private final ImmutableSet retryableCodes; private final ApiClock clock; @@ -126,8 +119,7 @@ RetryDecision evaluate( } // maxAttempts == 1 disables retries; maxAttempts == 0 means unlimited (GAX convention). - int maxAttempts = retrySettings.getMaxAttempts(); - if (maxAttempts > 0 && completedAttempts >= maxAttempts) { + if (StreamingRetryHelper.isMaxAttemptsExhausted(retrySettings, completedAttempts)) { return RetryDecision.retriesExhausted(error); } @@ -154,20 +146,16 @@ RetryDecision evaluate( @Nullable Throwable cause) { Duration effectiveDelay = additionalDelay != null && !additionalDelay.isNegative() ? additionalDelay : Duration.ZERO; - Duration totalTimeout = retrySettings.getTotalTimeoutDuration(); - if (isPositive(totalTimeout)) { - Duration elapsed = Duration.ofNanos(Math.max(0L, clock.nanoTime() - operationStartNanos)); - if (elapsed.compareTo(totalTimeout) >= 0 - || totalTimeout.minus(elapsed).compareTo(effectiveDelay) <= 0) { - return ApiExceptionFactory.createException( - "BatchWrite total timeout exceeded while retrying", - cause, - GrpcStatusCode.of(Status.Code.DEADLINE_EXCEEDED), - /* retryable= */ false); - } + 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 = toSaturatedNanos(effectiveDelay); + long additionalDelayNanos = StreamingRetryHelper.toSaturatedNanos(effectiveDelay); Deadline contextDeadline = grpcContext.getDeadline(); if (contextDeadline != null && contextDeadline.timeRemaining(TimeUnit.NANOSECONDS) <= additionalDelayNanos) { @@ -197,10 +185,12 @@ RetryDecision evaluate( if (effectiveRpcTimeout == null && isPositive(configuredRpcTimeout)) { double multiplier = Math.max(1.0, retrySettings.getRpcTimeoutMultiplier()); - double scaledMillis = - configuredRpcTimeout.toMillis() * Math.pow(multiplier, zeroBasedAttemptNumber); - Duration maxRpcTimeout = retrySettings.getMaxRpcTimeoutDuration(); - long maxMillis = isPositive(maxRpcTimeout) ? maxRpcTimeout.toMillis() : Long.MAX_VALUE; + 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)); } @@ -208,7 +198,9 @@ RetryDecision evaluate( if (isPositive(totalTimeout)) { long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(Math.max(0L, clock.nanoTime() - operationStartNanos)); - long remainingMillis = Math.max(1L, totalTimeout.toMillis() - elapsedMillis); + 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; @@ -237,31 +229,8 @@ boolean isRetryable(Throwable error) { } Duration computeNextRetryDelay(Throwable error, int completedAttempts) { - Duration serverRetryDelay = extractRetryDelay(error); - if (serverRetryDelay != null) { - return serverRetryDelay; - } - Duration initialDelay = retrySettings.getInitialRetryDelayDuration(); - if (!isPositive(initialDelay)) { - return Duration.ZERO; - } - Duration maxDelay = retrySettings.getMaxRetryDelayDuration(); - Duration effectiveMaxDelay = - maxDelay != null && maxDelay.compareTo(initialDelay) >= 0 ? maxDelay : initialDelay; - - 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); - // Full-band jitter in [0.5 * capped, 1.0 * capped] so delay never exceeds maxRetryDelay. - double jitterFactor = 0.5 + (0.5 * jitterRandom.getAsDouble()); - return fromNanosDouble(capped * jitterFactor); - } - - long computeNextRetryDelayMillis(Throwable error, int completedAttempts) { - return computeNextRetryDelay(error, completedAttempts).toMillis(); + return StreamingRetryHelper.computeRetryDelay( + retrySettings, error, completedAttempts, jitterRandom, Duration.ZERO); } static @Nullable Code extractStatusCode(Throwable error) { @@ -278,78 +247,10 @@ long computeNextRetryDelayMillis(Throwable error, int completedAttempts) { return null; } - static @Nullable Duration extractRetryDelay(@Nullable Throwable error) { - if (error instanceof ApiException) { - try { - ErrorDetails details = ((ApiException) error).getErrorDetails(); - if (details != null) { - Duration delay = toNonNegativeDuration(details.getRetryInfo()); - if (delay != null) { - return delay; - } - } - } catch (IllegalArgumentException | ArithmeticException ignored) { - // Fall through to trailers / exponential backoff if RetryInfo is malformed. - } - } - if (error != null) { - try { - Metadata trailers = Status.trailersFromThrowable(error); - if (trailers != null) { - Duration delay = toNonNegativeDuration(trailers.get(KEY_RETRY_INFO)); - if (delay != null) { - return delay; - } - } - } catch (IllegalArgumentException | ArithmeticException ignored) { - // Fall back to exponential backoff if RetryInfo trailer is corrupted or out of range. - } - } - return null; - } - - static long extractRetryDelayMillis(@Nullable Throwable error) { - Duration delay = extractRetryDelay(error); - return delay != null ? delay.toMillis() : -1L; - } - - private static @Nullable Duration toNonNegativeDuration(@Nullable RetryInfo retryInfo) { - if (retryInfo != null && retryInfo.hasRetryDelay()) { - com.google.protobuf.Duration protoDelay = retryInfo.getRetryDelay(); - Durations.checkValid(protoDelay); - if (protoDelay.getSeconds() >= 0L && protoDelay.getNanos() >= 0) { - return Duration.ofSeconds(protoDelay.getSeconds(), protoDelay.getNanos()); - } - } - 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 <= 0.0) { - return Duration.ZERO; - } - if (nanos >= (double) Long.MAX_VALUE) { - return Duration.ofNanos(Long.MAX_VALUE); - } - return Duration.ofNanos((long) nanos); - } - - private static long toSaturatedNanos(Duration duration) { - try { - return duration.toNanos(); - } catch (ArithmeticException e) { - return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE; - } - } - static ApiException createContextCancellationException(Context ctx) { Throwable cause = ctx.cancellationCause(); Status.Code code = Status.Code.CANCELLED; 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 7e3d449a4077..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 @@ -26,7 +26,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.google.api.client.util.BackOff; import com.google.api.core.ApiFuture; import com.google.api.gax.core.ExecutorProvider; import com.google.api.gax.retrying.RetrySettings; @@ -72,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; @@ -121,18 +121,6 @@ private static StatusRuntimeException statusWithRetryInfo( return code.getGrpcStatus().asRuntimeException(trailers); } - private static BackOff fixedBackOff(long delayMillis) { - return new BackOff() { - @Override - public void reset() {} - - @Override - public long nextBackOffMillis() { - return delayMillis; - } - }; - } - static class RetryableException extends SpannerException { RetryableException(ErrorCode code, @Nullable String message) { // OK to instantiate SpannerException directly for this unit test. @@ -192,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() { @@ -261,6 +250,11 @@ long nanoTime() { return nanoTime.getAsLong(); } + @Override + double nextJitterRandom() { + return jitterRandom.getAsDouble(); + } + @Override void backoffSleep(Context context, long backoffMillis) throws SpannerException { if (recordedSleeps != null) { @@ -574,7 +568,7 @@ private boolean totalTimeoutExceeded(long timeoutMillis, long elapsedMillis, lon nanoTime = () -> 0L; assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(exception)); nanoTime = () -> TimeUnit.MILLISECONDS.toNanos(elapsedMillis); - return resumableStreamIterator.totalTimeoutExceeded(delayMillis); + return resumableStreamIterator.totalTimeoutExceeded(java.time.Duration.ofMillis(delayMillis)); } @Test @@ -627,8 +621,8 @@ public void retryInfoWithZeroDelay_fallsBackToExponentialBackoff() { assertThat(delayMillis).isAtLeast(5L); assertThat(delayMillis).isAtMost(15L); - // Positive sub-millisecond RetryInfo truncates to 0L in Durations.toMillis and must also use - // exponential backoff rather than spinning at zero delay. + // 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( @@ -636,10 +630,7 @@ public void retryInfoWithZeroDelay_fallsBackToExponentialBackoff() { "sub-millisecond delay", statusWithRetryInfo(errorCodeParameter, 0L, 500_000)); assertEquals(0L, subMillisecondException.getRetryDelayInMillis()); - long subMsBackoff = - resumableStreamIterator.checkRetryBudgetAndGetDelay(subMillisecondException); - assertThat(subMsBackoff).isAtLeast(5L); - assertThat(subMsBackoff).isAtMost(15L); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(subMillisecondException)); List recordedSleeps = new ArrayList<>(); initWithRecordingBackoffSleep(defaultTestRetrySettings(), recordedSleeps); @@ -809,7 +800,7 @@ public void retryInfoWithinMaxRetryDelay_honorsServerDelayAndChecksTotalTimeout( } @Test - public void nonPositiveRetryInfo_floorsZeroBackoffToOneMsAndMapsBackOffStopToEffectiveMax() { + public void nonPositiveRetryInfo_floorsMinimumBackoffToOneMs() { SpannerException zeroDelayException = new RetryableException( errorCodeParameter, "zero delay", statusWithRetryInfo(errorCodeParameter, 0L, 0)); @@ -819,27 +810,10 @@ public void nonPositiveRetryInfo_floorsZeroBackoffToOneMsAndMapsBackOffStopToEff "absent delay", errorCodeParameter.getGrpcStatus().asRuntimeException()); - ResumableStreamIterator zeroBackoffIterator = - new FixedBackOffTestIterator(RetrySettings.newBuilder().build(), 0L); - assertEquals(1L, zeroBackoffIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); - assertEquals(1L, zeroBackoffIterator.checkRetryBudgetAndGetDelay(absentDelayException)); - - ResumableStreamIterator stopBackoffUnsetMaxIterator = - new FixedBackOffTestIterator(RetrySettings.newBuilder().build(), BackOff.STOP); - assertEquals( - 32_000L, stopBackoffUnsetMaxIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); - assertEquals( - 32_000L, stopBackoffUnsetMaxIterator.checkRetryBudgetAndGetDelay(absentDelayException)); - - RetrySettings customMaxSettings = - RetrySettings.newBuilder() - .setInitialRetryDelayDuration(java.time.Duration.ofMillis(10L)) - .setMaxRetryDelayDuration(java.time.Duration.ofMillis(250L)) - .build(); - ResumableStreamIterator stopBackoffCustomMaxIterator = - new FixedBackOffTestIterator(customMaxSettings, BackOff.STOP); - assertEquals( - 250L, stopBackoffCustomMaxIterator.checkRetryBudgetAndGetDelay(absentDelayException)); + initWithLimitAndRetrySettings(Integer.MAX_VALUE, RetrySettings.newBuilder().build()); + jitterRandom = () -> 0.0; + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException)); + assertEquals(1L, resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException)); initWithLimitAndRetrySettings( Integer.MAX_VALUE, @@ -854,7 +828,7 @@ public void nonPositiveRetryInfo_floorsZeroBackoffToOneMsAndMapsBackOffStopToEff } @Test - public void effectiveMaxRetryDelayAndNewBackOff_handleSubMillisecondAndOverflowingDurations() { + public void effectiveMaxRetryDelayAndBackoff_handleSubMillisecondAndOverflowingDurations() { SpannerException twoHundredMsException = new RetryableException( errorCodeParameter, @@ -883,7 +857,7 @@ public void effectiveMaxRetryDelayAndNewBackOff_handleSubMillisecondAndOverflowi assertEquals(200L, resumableStreamIterator.checkRetryBudgetAndGetDelay(twoHundredMsException)); long backoffDelay = resumableStreamIterator.checkRetryBudgetAndGetDelay(zeroDelayException); assertThat(backoffDelay).isAtLeast(5L); - assertThat(backoffDelay).isAtMost(15L); + assertThat(backoffDelay).isAtMost(10L); RetrySettings overflowInitialAndMaxSettings = RetrySettings.newBuilder() @@ -896,7 +870,7 @@ public void effectiveMaxRetryDelayAndNewBackOff_handleSubMillisecondAndOverflowi } @Test - public void newBackOff_unsetMaxRetryDelayUsesDefaultCeilingForClientBackoff() { + public void unsetMaxRetryDelayUsesDefaultCeilingForClientBackoff() { initWithLimitAndRetrySettings( Integer.MAX_VALUE, RetrySettings.newBuilder().setRetryDelayMultiplier(10.0).build()); SpannerException absentDelayException = @@ -908,13 +882,92 @@ public void newBackOff_unsetMaxRetryDelayUsesDefaultCeilingForClientBackoff() { for (int i = 0; i < 6; i++) { long delayMillis = resumableStreamIterator.checkRetryBudgetAndGetDelay(absentDelayException); assertThat(delayMillis).isAtLeast(1L); - assertThat(delayMillis).isAtMost(48_000L); + assertThat(delayMillis).isAtMost(32_000L); maxObserved = Math.max(maxObserved, delayMillis); } - // Intervals 1, 10, 100, 1000, 10000, 32000 (+/-50% jitter): the 32s ceiling is reached. + // 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 @@ -3315,30 +3368,6 @@ private abstract static class TestResumableStreamIterator extends ResumableStrea } } - private static final class FixedBackOffTestIterator extends TestResumableStreamIterator { - private final long delayMillis; - - FixedBackOffTestIterator(RetrySettings retrySettings, long delayMillis) { - super( - new TraceWrapper(Tracing.getTracer(), OpenTelemetry.noop().getTracer(""), false), - retrySettings); - this.delayMillis = delayMillis; - } - - @Override - BackOff newBackOff() { - return fixedBackOff(delayMillis); - } - - @Override - CloseableIterator startStream( - @Nullable ByteString resumeToken, - @Nullable StreamMessageListener streamMessageListener, - XGoogSpannerRequestId requestId) { - throw new AssertionError("unexpected startStream"); - } - } - private static TraceWrapper mockTracerWithSpan(ISpan span) { TraceWrapper tracer = mock(TraceWrapper.class); when(tracer.spanBuilderWithExplicitParent(Mockito.any(), Mockito.any(), Mockito.any())) 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/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/spi/v1/BatchWriteRetryPolicyTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/spi/v1/BatchWriteRetryPolicyTest.java index b1beec374d32..2fa609be7e43 100644 --- 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 @@ -30,10 +30,12 @@ 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; @@ -150,13 +152,13 @@ public void backoffAppliesJitterAndCapsAtMaxRetryDelay() { new BatchWriteRetryPolicy(defaultSettings(), DEFAULT_CODES, clock, () -> 1.0); Throwable err = apiException(Status.Code.UNAVAILABLE, "transient"); - assertEquals(50L, minJitter.computeNextRetryDelayMillis(err, 1)); - assertEquals(100L, maxJitter.computeNextRetryDelayMillis(err, 1)); - assertEquals(100L, minJitter.computeNextRetryDelayMillis(err, 2)); - assertEquals(200L, maxJitter.computeNextRetryDelayMillis(err, 2)); + 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(5_000L, minJitter.computeNextRetryDelayMillis(err, 10)); - assertEquals(10_000L, maxJitter.computeNextRetryDelayMillis(err, 10)); + assertEquals(Duration.ofSeconds(5), minJitter.computeNextRetryDelay(err, 10)); + assertEquals(Duration.ofSeconds(10), maxJitter.computeNextRetryDelay(err, 10)); } @Test @@ -171,7 +173,7 @@ public void retryInfoTrailerOverridesExponentialBackoffAndCorruptedTrailerFallsB StatusRuntimeException withRetryInfo = Status.UNAVAILABLE.withDescription("retry later").asRuntimeException(trailers); - assertEquals(345L, policy.computeNextRetryDelayMillis(withRetryInfo, 1)); + assertEquals(Duration.ofMillis(345), policy.computeNextRetryDelay(withRetryInfo, 1)); // RetryInfo provided via ApiException.getErrorDetails() overrides exponential backoff. RetryInfo detailsRetryInfo = @@ -195,16 +197,16 @@ public void retryInfoTrailerOverridesExponentialBackoffAndCorruptedTrailerFallsB StatusRuntimeException withBadTrailer = Status.UNAVAILABLE.withDescription("corrupt trailer").asRuntimeException(badTrailers); - assertEquals(100L, policy.computeNextRetryDelayMillis(withBadTrailer, 1)); + assertEquals(Duration.ofMillis(100), policy.computeNextRetryDelay(withBadTrailer, 1)); - // Negative RetryInfo duration must explicitly return -1L and fall back to exponential backoff. + // 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); - assertEquals(-1L, BatchWriteRetryPolicy.extractRetryDelayMillis(withNegativeRetryInfo)); - assertEquals(100L, policy.computeNextRetryDelayMillis(withNegativeRetryInfo, 1)); + 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); @@ -383,7 +385,186 @@ public void zeroInitialRetryDelayProducesZeroBackoff() { new BatchWriteRetryPolicy(zeroDelaySettings, DEFAULT_CODES, clock, () -> 1.0); Throwable unavailable = apiException(Status.Code.UNAVAILABLE, "transient"); assertEquals(Duration.ZERO, policy.computeNextRetryDelay(unavailable, 1)); - assertEquals(0L, policy.computeNextRetryDelayMillis(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 From e902bb01f8034e57fe547725df07897729567136 Mon Sep 17 00:00:00 2001 From: Sakthivel Subramanian <179120858+sakthivelmanii@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:00:07 +0530 Subject: [PATCH 56/57] feat(spanner): support per-client built-in Cloud Monitoring metrics (#15261) ## Problem Statement - Built-in Cloud Monitoring metrics were previously backed by a single process-wide provider shared across all Spanner clients in a JVM. - Applications running multiple Spanner clients in the same JVM with different credentials, monitoring endpoints, or universe domains could not isolate built-in metrics export per client, causing all clients to export through the first client's Cloud Monitoring exporter and fallback project. - Built-in metrics exporters were also not shut down when `Spanner.close()` was called. ## Solution - Add per-client built-in Cloud Monitoring metrics support by scoping the metrics provider to each `SpannerOptions` / `Spanner` client so each client exports using its own credentials, monitoring endpoint, universe domain, fallback project, and unique `client_uid`. - Close each client's built-in metrics exporter during `Spanner.close()` with a bounded final flush (up to 10 seconds on `Spanner.close()`, or within the caller's remaining timeout on bounded close), while resetting state cleanly so reusing `SpannerOptions.getService()` after closing creates a fresh exporter. --- .../cloud/spanner/BuiltInMetricsProvider.java | 382 ++++++++--- .../SpannerCloudMonitoringExporter.java | 21 +- .../SpannerCloudMonitoringExporterUtils.java | 16 +- .../com/google/cloud/spanner/SpannerImpl.java | 12 + .../google/cloud/spanner/SpannerOptions.java | 26 +- .../spanner/BuiltInMetricsBothSinksTest.java | 69 +- ...BuiltInMetricsCustomOpenTelemetryTest.java | 47 +- ...iltInMetricsMultiClientMockServerTest.java | 407 ++++++++++++ ...iltInOpenTelemetryMetricsProviderTest.java | 620 +++++++++++++++++- .../ChannelPoolBuiltInMetricsTest.java | 89 +-- .../spanner/GrpcMetricsDualWireTest.java | 3 +- .../cloud/spanner/MetricsProviderTest.java | 8 +- ...OpenTelemetryBuiltInMetricsTracerTest.java | 2 +- .../SpannerCloudMonitoringExporterTest.java | 120 +++- .../google/cloud/spanner/SpannerImplTest.java | 52 ++ .../cloud/spanner/SpannerOptionsTest.java | 1 + .../spanner/spi/v1/GapicSpannerRpcTest.java | 39 ++ 17 files changed, 1657 insertions(+), 257 deletions(-) create mode 100644 java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsMultiClientMockServerTest.java 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 2e42c7bcae7f..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,109 +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; +/** + * 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 { - static BuiltInMetricsProvider INSTANCE = new 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; // 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 @@ -198,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) @@ -234,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()); @@ -246,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; } @@ -282,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/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/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 e02de5a9c352..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 @@ -328,9 +328,8 @@ static GcpChannelPoolOptions mergeWithDefaultChannelPoolOptions( private final boolean enableGrpcGcpOtelMetrics; private final boolean enableChannelPoolBuiltInMetrics; - // Non-final so tests can observe the arguments passed to the process-wide metrics provider. - @VisibleForTesting - 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}. @@ -3228,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); } @@ -3279,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 = @@ -3297,9 +3305,9 @@ 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 = 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 46b0f47fdec8..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 @@ -56,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 { @@ -85,17 +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())) - .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) - .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) { @@ -124,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 dd4cb4b6e27c..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() { + public void resetEnvironment() { SpannerOptions.useDefaultEnvironment(); - // Reset the process-wide Cloud Monitoring singleton so state cannot leak across tests sharing - // the JVM fork. - BuiltInMetricsProvider.INSTANCE.reset(); } private Spanner createSpanner(MetricsProvider metricsProvider) { @@ -153,17 +150,16 @@ 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()); } - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); } @Test @@ -175,34 +171,33 @@ public boolean isEnableGRPCBuiltInMetrics() { return true; } }); - BuiltInMetricsProvider.INSTANCE.reset(); try { // Default provider with NoCredentials and built-in metrics enabled must not initialize GCM. - try (Spanner defaultSpanner = + SpannerOptions defaultOptions = spannerBuilder(DefaultMetricsProvider.INSTANCE) .setEmulatorHost(null) .setBuiltInMetricsEnabled(true) - .build() - .getService()) { + .build(); + try (Spanner defaultSpanner = defaultOptions.getService()) { executeSelect1(defaultSpanner); + assertNull(defaultOptions.builtInMetricsProvider.getOpenTelemetry()); } - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); // Custom provider with NoCredentials and built-in metrics enabled still records custom - // metrics while leaving the GCM singleton uninitialized. + // metrics while leaving the GCM provider uninitialized. InMemoryMetricReader metricReader = InMemoryMetricReader.create(); OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); try { - try (Spanner customSpanner = + SpannerOptions customOptions = spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry)) .setEmulatorHost(null) .setBuiltInMetricsEnabled(true) - .build() - .getService()) { + .build(); + try (Spanner customSpanner = customOptions.getService()) { executeSelect1(customSpanner); + assertNull(customOptions.builtInMetricsProvider.getOpenTelemetry()); } - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); assertNotNull( getMetric( metricReader, @@ -213,7 +208,6 @@ public boolean isEnableGRPCBuiltInMetrics() { customOpenTelemetry.close(); } } finally { - BuiltInMetricsProvider.INSTANCE.reset(); SpannerOptions.useDefaultEnvironment(); } } @@ -231,7 +225,6 @@ public boolean isEnableGRPCBuiltInMetrics() { return true; } }); - BuiltInMetricsProvider.INSTANCE.reset(); InMemoryMetricReader metricReader = InMemoryMetricReader.create(); OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader); try { @@ -250,13 +243,12 @@ public boolean isEnableGRPCBuiltInMetrics() { 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()); } - // Even with the NoCredentials guard lifted and gRPC built-in metrics enabled, the custom host - // must NOT initialize the GCM singleton. - assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry()); - assertNull(BuiltInMetricsProvider.INSTANCE.getProjectId()); - // Caller-owned CustomOpenTelemetryMetricsProvider still records metrics end-to-end. assertNotNull( getMetric( @@ -266,7 +258,6 @@ public boolean isEnableGRPCBuiltInMetrics() { + BuiltInMetricsConstant.OPERATION_COUNT_NAME)); } finally { customOpenTelemetry.close(); - BuiltInMetricsProvider.INSTANCE.reset(); SpannerOptions.useDefaultEnvironment(); if (previousJmhEnabled == null) { System.clearProperty("jmh.enabled"); 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 88784a17e4a9..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 @@ -58,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 { @@ -86,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(); @@ -104,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(); @@ -114,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(); @@ -156,7 +158,8 @@ public ApiCallContext configure( } }; try (Spanner spanner = - createOptions().setCallContextConfigurator(configurator).build().getService()) { + buildWithBuiltInMetrics(createOptions().setCallContextConfigurator(configurator)) + .getService()) { executeSelect1(spanner); assertThat( @@ -221,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(); @@ -231,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(); @@ -243,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(); @@ -253,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(); @@ -275,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() @@ -336,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(); @@ -347,15 +355,15 @@ public void adminCallsDoNotReportChannelLoad() { @Test public void dynamicPoolReportsDynamicPoolModeAndChannelLoad() { 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()) - .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); @@ -400,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(); @@ -410,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(); @@ -418,6 +427,12 @@ 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") @@ -431,16 +446,16 @@ private SpannerOptions.Builder createOptions() { } private SpannerOptions createDirectPathFallbackOptions() { - return SpannerOptions.newBuilder() - .setProjectId("my-project") - .setEnableDirectAccess(true) - .setHost("http://localhost:1") - .setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE) - .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/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 23573e57f167..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,7 +61,6 @@ public void setUp() { @After public void reset() { SpannerOptions.useDefaultEnvironment(); - BuiltInMetricsProvider.INSTANCE.reset(); } private static SpannerOptions.Builder cloudBuilder() { @@ -292,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/OpenTelemetryBuiltInMetricsTracerTest.java b/java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/OpenTelemetryBuiltInMetricsTracerTest.java index 38a1dc32a1cd..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 @@ -74,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") 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/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 b2381cf52abf..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 @@ -2608,6 +2608,7 @@ public void testCloudMonitoringExporterHonorsResolvedUniverseDomain() throws Exc SpannerCloudMonitoringExporter exporter = SpannerCloudMonitoringExporter.create( () -> "test-project", + Collections.emptyMap(), NoCredentials.getInstance(), null, options.getResolvedUniverseDomain()); 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 5e5496897d89..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; @@ -3304,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); } From 60ee6263d00825a82af68d54c33607ef41df22cb Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Sun, 22 Nov 2026 20:54:32 +0000 Subject: [PATCH 57/57] docs(gax): fix broken URLs, invalid Javadoc tags, and raw Markdown syntax --- .../java/com/google/api/core/ApiService.java | 8 ++-- .../google/api/gax/grpc/GrpcCallContext.java | 4 +- .../InstantiatingGrpcChannelProvider.java | 44 +++++++++---------- .../gax/core/GoogleCredentialsProvider.java | 4 +- .../google/api/gax/rpc/ApiStreamObserver.java | 11 +++-- .../google/api/gax/rpc/EndpointContext.java | 26 +++++------ .../com/google/api/gax/rpc/StatusCode.java | 5 +-- .../com/google/api/gax/rpc/StubSettings.java | 10 ++--- .../google/api/gax/rpc/mtls/MtlsProvider.java | 2 +- .../tracing/OpenTelemetryMetricsRecorder.java | 10 ++--- 10 files changed, 60 insertions(+), 64 deletions(-) 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/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/EndpointContext.java b/sdk-platform-java/gax-java/gax/src/main/java/com/google/api/gax/rpc/EndpointContext.java index 4dc72df11299..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 @@ -89,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(); @@ -211,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 dd9a5c301f3d..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 @@ -671,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