Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,6 @@ public final class GrpcStorageOptions extends StorageOptions
private static final long serialVersionUID = -4499446543857945349L;
private static final String GCS_SCOPE = "https://www.googleapis.com/auth/devstorage.full_control";
private static final Set<String> SCOPES = ImmutableSet.of(GCS_SCOPE);
private static final String DEFAULT_HOST = "https://storage.googleapis.com";
// If true, disable the bound-token-by-default feature for DirectPath.
private static final boolean DIRECT_PATH_BOUND_TOKEN_DISABLED =
Boolean.parseBoolean(
Expand Down Expand Up @@ -171,6 +170,11 @@ private GrpcStorageOptions(Builder builder, GrpcStorageDefaults serviceDefaults)
this.openTelemetry = builder.openTelemetry;
}

@Override
protected String getDefaultHost() {
return "https://storage." + resolveUniverseDomain();
}

@Override
protected Set<String> getScopes() {
return SCOPES;
Expand Down Expand Up @@ -352,7 +356,7 @@ private Tuple<StorageSettings, Opts<UserProject>> resolveSettingsAndOpts() throw
ChannelConfigurator.lift(channelProviderBuilder.getChannelConfigurator()),
endpoint,
this.getProjectId(),
this.getUniverseDomain(),
this.resolveUniverseDomain(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI] OpenTelemetryBootstrappingUtils.createMetricServiceSettings already reads GOOGLE_CLOUD_UNIVERSE_DOMAIN when universeDomain is null, and relies on null to skip exporting metrics when the storage host doesn't end in .googleapis.com. Passing resolveUniverseDomain() here (and in StorageClientMetrics.java:120) falls back to "googleapis.com" when nothing is configured, which bypasses that guard and configures Cloud Monitoring export for custom hosts like localhost:9000 when default credentials are present.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Closing this PR as superseded by #15235, #15238 and #15239, which cover the same host and universe domain resolution; their metrics wiring passes the configured universe domain, which stays unset when none is configured.

Co-authored by AI Agent

this.getCredentials(),
!grpcClientMetricsManuallyEnabled);
channelProviderBuilder.setChannelConfigurator(channelConfigurator);
Expand Down Expand Up @@ -474,7 +478,7 @@ && isEnableOtelDebugMetrics() == that.isEnableOtelDebugMetrics()
* @since 2.14.0
*/
public static GrpcStorageOptions.Builder newBuilder() {
return new GrpcStorageOptions.Builder().setHost(DEFAULT_HOST);
return new GrpcStorageOptions.Builder();
}

/**
Expand Down Expand Up @@ -855,9 +859,17 @@ public GrpcStorageOptions.Builder setMetricInterval(Duration metricInterval) {
public GrpcStorageOptions build() {
GrpcStorageOptions options = new GrpcStorageOptions(this, defaults());
// TODO: Remove when https://github.com/googleapis/sdk-platform-java/issues/2911 is resolved
if (options.getUniverseDomain() != null) {
this.setHost("https://storage." + options.getUniverseDomain());
return new GrpcStorageOptions(this, defaults());
String resolvedHost = options.getResolvedHost("storage");
if (!resolvedHost.equals(options.getHost())) {
// Only reached for the legacy https://www.googleapis.com explicit host; restore it so the
// builder stays reusable.
String originalHost = options.getHost();
try {
super.setHost(null);
return new GrpcStorageOptions(this, defaults());
} finally {
super.setHost(originalHost);
}
}
return options;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ private HttpStorageOptions(Builder builder, StorageDefaults serviceDefaults) {
openTelemetry = builder.openTelemetry;
}

@Override
protected String getDefaultHost() {
return "https://storage." + resolveUniverseDomain() + "/";
}

@Override
protected Set<String> getScopes() {
return SCOPES;
Expand Down Expand Up @@ -110,13 +115,6 @@ public HttpStorageOptions.Builder toBuilder() {
return new HttpStorageOptions.Builder(this);
}

@Override
boolean usesDefaultHost() {
String universeDomain =
MoreObjects.firstNonNull(getUniverseDomain(), Credentials.GOOGLE_DEFAULT_UNIVERSE);
return getHost().equals("https://storage." + universeDomain + "/");
}

@Override
public int hashCode() {
return Objects.hash(
Expand Down Expand Up @@ -313,19 +311,23 @@ public HttpStorageOptions.Builder setApiTracerFactory(ApiTracerFactory apiTracer

@Override
public HttpStorageOptions build() {
if (!isHostManuallySet()) {
// Resolve the default host from the current universe domain on every build.
setResolvedHostInternal(null);
}
HttpStorageOptions options = new HttpStorageOptions(this, defaults());

// todo: In the future, this step will be done automatically, and the getResolvedApiaryHost
// helper method will
// be removed. When that happens, delete the following block.
// https://github.com/googleapis/google-api-java-client-services/issues/19286
if (options.getHost() != null) {
setResolvedHostInternal(options.getResolvedApiaryHost("storage"));
return new HttpStorageOptions(this, defaults());
String resolvedHost = options.getResolvedApiaryHost("storage");
if (!resolvedHost.equals(options.getHost())) {
// Only reached for the legacy https://www.googleapis.com explicit host; restore it so the
// builder stays reusable.
String originalHost = options.getHost();
try {
super.setHost(null);
return new HttpStorageOptions(this, defaults());
} finally {
super.setHost(originalHost);
}
}
return options;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ static StorageClientMetrics fromOptions(StorageOptions options) {
OpenTelemetryBootstrappingUtils.createDefaultClientMeterProvider(
options.getHost(),
options.getProjectId(),
options.getUniverseDomain(),
options.resolveUniverseDomain(),
options.getCredentials(),
options.getMetricInterval(),
options instanceof GrpcStorageOptions ? "grpc" : "json");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.google.api.services.storage.model.BucketAccessControl;
import com.google.api.services.storage.model.ObjectAccessControl;
import com.google.api.services.storage.model.StorageObject;
import com.google.auth.Credentials;
import com.google.auth.ServiceAccountSigner;
import com.google.cloud.BaseService;
import com.google.cloud.BatchResult;
Expand Down Expand Up @@ -87,6 +88,7 @@
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -1202,27 +1204,29 @@ private SignatureInfo buildSignatureInfo(

signatureInfoBuilder.setTimestamp(getOptions().getClock().millisTime());

ImmutableMap.Builder<String, String> extHeadersBuilder = new ImmutableMap.Builder<>();
Map<String, String> extHeaders = new LinkedHashMap<>();

boolean isV4 =
SignUrlOption.SignatureVersion.V4.equals(
optionMap.get(SignUrlOption.Option.SIGNATURE_VERSION));
if (isV4) { // We don't sign the host header for V2 signed URLs; only do this for V4.
// Add the host here first, allowing it to be overridden in the EXT_HEADERS option below.
if (optionMap.containsKey(SignUrlOption.Option.VIRTUAL_HOSTED_STYLE)) {
extHeadersBuilder.put(
extHeaders.put(
"host",
slashlessBucketNameFromBlobInfo(blobInfo) + "." + getBaseStorageHostName(optionMap));
} else if (optionMap.containsKey(SignUrlOption.Option.HOST_NAME)
|| optionMap.containsKey(SignUrlOption.Option.BUCKET_BOUND_HOST_NAME)
|| getOptions().getUniverseDomain() != null) {
extHeadersBuilder.put("host", getBaseStorageHostName(optionMap));
// An explicitly set universe (even googleapis.com) or a non-default resolved universe
// signs the configured host.
|| getOptions().getUniverseDomain() != null
|| !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(getOptions().resolveUniverseDomain())) {
extHeaders.put("host", getBaseStorageHostName(optionMap));
}
}

if (optionMap.containsKey(SignUrlOption.Option.EXT_HEADERS)) {
extHeadersBuilder.putAll(
(Map<String, String>) optionMap.get(SignUrlOption.Option.EXT_HEADERS));
extHeaders.putAll((Map<String, String>) optionMap.get(SignUrlOption.Option.EXT_HEADERS));
}

ImmutableMap.Builder<String, String> queryParamsBuilder = new ImmutableMap.Builder<>();
Expand All @@ -1232,7 +1236,7 @@ private SignatureInfo buildSignatureInfo(
}

return signatureInfoBuilder
.setCanonicalizedExtensionHeaders(extHeadersBuilder.build())
.setCanonicalizedExtensionHeaders(ImmutableMap.copyOf(extHeaders))
.setCanonicalizedQueryParams(queryParamsBuilder.build())
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,13 @@ public abstract static class Builder
private Duration metricInterval = Duration.ofSeconds(60);
private boolean customOpenTelemetryConfigured = false;
private boolean customMeterProviderConfigured = false;
private boolean hostManuallySet = false;

Builder() {
setUseJwtAccessWithScope(false);
}

Builder(StorageOptions options) {
super(options);
this.hostManuallySet = !options.usesDefaultHost();
this.enableOtelMetrics = options.getRawEnableOtelMetrics();
this.enableOtelDebugMetrics = options.getRawEnableOtelDebugMetrics();
this.meterProvider = options.getMeterProvider();
Expand All @@ -143,22 +141,6 @@ public abstract static class Builder
this.customOpenTelemetryConfigured = options.isCustomOpenTelemetryConfigured();
}

@Override
public Builder setHost(String host) {
this.hostManuallySet = host != null;
return super.setHost(host);
}

/** Whether the host was set with {@link #setHost(String)}. */
boolean isHostManuallySet() {
return hostManuallySet;
}

/** Sets a host resolved by the builder itself, leaving {@link #isHostManuallySet()} as is. */
Builder setResolvedHostInternal(@Nullable String host) {
return super.setHost(host);
}

@Nullable Boolean getEnableOtelMetrics() {
return enableOtelMetrics;
}
Expand Down Expand Up @@ -310,14 +292,6 @@ public StorageOptions.Builder setMetricInterval(Duration metricInterval) {
}
}

/**
* Whether {@link #getHost()} is the host this transport derives from {@link #getUniverseDomain()}
* when no host is set with {@link Builder#setHost(String)}.
*/
boolean usesDefaultHost() {
return false;
}

@Nullable Boolean getRawEnableOtelMetrics() {
return rawEnableOtelMetrics;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,4 +420,46 @@ public void blobWriteSessionConfig_pcu() throws IOException, ClassNotFoundExcept
"com.google.cloud.storage.ParallelCompositeUploadBlobWriteSessionConfig$ExecutorSupplier$SuppliedExecutorSupplier;"
+ " Not serializable");
}

@Test
public void storageOptions_deserializedPreservesHasExplicitHostAndToBuilderResolution()
throws IOException, ClassNotFoundException {
HttpStorageOptions httpDefault =
StorageOptions.http()
.setProjectId("http-p")
.setCredentials(NoCredentials.getInstance())
.build();
HttpStorageOptions httpCopy = serializeAndDeserialize(httpDefault);
assertThat(httpCopy).isEqualTo(httpDefault);
assertThat(httpCopy.hasExplicitHost()).isFalse();
assertThat(httpCopy.toBuilder().setUniverseDomain("explicit.example.com").build().getHost())
.isEqualTo("https://storage.explicit.example.com/");

GrpcStorageOptions grpcDefault =
StorageOptions.grpc()
.setProjectId("grpc-p")
.setCredentials(NoCredentials.getInstance())
.build();
GrpcStorageOptions grpcCopy = serializeAndDeserialize(grpcDefault);
assertThat(grpcCopy).isEqualTo(grpcDefault);
assertThat(grpcCopy.hasExplicitHost()).isFalse();
assertThat(grpcCopy.toBuilder().setUniverseDomain("explicit.example.com").build().getHost())
.isEqualTo("https://storage.explicit.example.com");

GrpcStorageOptions grpcExplicit =
StorageOptions.grpc()
.setProjectId("grpc-p")
.setCredentials(NoCredentials.getInstance())
.setHost("https://custom.example.com")
.build();
GrpcStorageOptions grpcExplicitCopy = serializeAndDeserialize(grpcExplicit);
assertThat(grpcExplicitCopy).isEqualTo(grpcExplicit);
assertThat(grpcExplicitCopy.hasExplicitHost()).isTrue();
assertThat(
grpcExplicitCopy.toBuilder()
.setUniverseDomain("explicit.example.com")
.build()
.getHost())
.isEqualTo("https://custom.example.com");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

import static com.google.common.truth.Truth.assertThat;

import com.google.auth.Credentials;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.collect.ImmutableList;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
Expand All @@ -40,6 +43,7 @@
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public final class StorageClientMetricsTest {

Expand Down Expand Up @@ -413,6 +417,28 @@ public void createContext_nullMetrics_returnsNull() {
assertThat(StorageClientMetrics.createMultiStepContext(null, "WriteObject")).isNull();
}

@Test
public void fromOptions_usesResolvedUniverseDomain() {
Credentials credentials =
GoogleCredentials.newBuilder()
.setAccessToken(new AccessToken("token", null))
.setUniverseDomain("example.com")
.build();
HttpStorageOptions options =
Mockito.spy(
StorageOptions.http()
.setCredentials(credentials)
.setProjectId("test-project")
.setEnableOtelMetrics(true)
.build());
Mockito.doReturn("example.com").when(options).resolveUniverseDomain();

try (StorageClientMetrics metrics = StorageClientMetrics.fromOptions(options)) {
assertThat(metrics).isNotNull();
Mockito.verify(options).resolveUniverseDomain();
}
}

static final class TestMetricReader implements MetricReader {
private final MetricReader delegate = InMemoryMetricReader.create();
final AtomicBoolean shutdownCalled = new AtomicBoolean(false);
Expand Down
Loading
Loading