Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ public class DatastoreOptions extends ServiceOptions<Datastore, DatastoreOptions
@Deprecated public static final int MAX_CHANNEL_COUNT = 10;

private transient TransportChannelProvider channelProvider = null;
// Tracks whether channelProvider was explicitly supplied by the caller vs. synthesized in the
// constructor, so toBuilder() can safely rebuild auto-generated providers when settings change.
private final boolean hasCustomChannelProvider;
// Tracks whether host was explicitly overridden by the caller vs. populated as a transport
// default in build(), so switching transports via toBuilder() does not carry over a stale
// default endpoint (e.g., gRPC's datastore.googleapis.com:443 into HTTP transport).
private final boolean hasCustomHost;

private final String namespace;
private final String databaseId;
Expand Down Expand Up @@ -135,7 +142,9 @@ public static class Builder extends ServiceOptions.Builder<Datastore, DatastoreO
private String databaseId;
private ImmutableList<String> requestTags = ImmutableList.of();
private TransportChannelProvider channelProvider = null;
private boolean hasCustomChannelProvider = false;
private String host;
private boolean hasCustomHost = false;

@Nonnull
private TransportOptions transportOptions =
Expand All @@ -152,7 +161,9 @@ private Builder(DatastoreOptions options) {
this.requestTags = options.requestTags;
this.openTelemetryOptions = options.openTelemetryOptions;
this.channelProvider = options.channelProvider;
this.hasCustomChannelProvider = options.hasCustomChannelProvider;
this.host = options.getHost();
this.hasCustomHost = options.hasCustomHost;
this.transportOptions = options.getTransportOptions();
}

Expand All @@ -172,7 +183,22 @@ public Builder setTransportOptions(@Nonnull TransportOptions transportOptions) {
throw new IllegalArgumentException(
"Only http and grpc transport are allowed for " + API_SHORT_NAME + ".");
}
boolean transportChanged =
!this.transportOptions.getClass().equals(transportOptions.getClass());
this.transportOptions = transportOptions;
if (transportChanged) {
if (!this.hasCustomHost) {
// Reset transport-defaulted host (e.g., gRPC's datastore.googleapis.com:443 or HTTP's
// https://datastore.googleapis.com) so build() populates the new transport's default.
this.host = null;
super.setHost(null);
}
if (!this.hasCustomChannelProvider) {
// Clear any auto-generated gRPC channel provider so switching to HTTP does not retain it
// and switching to gRPC builds a fresh provider.
this.channelProvider = null;
}
}
return super.setTransportOptions(transportOptions);
}

Expand All @@ -192,9 +218,31 @@ public Builder setTransportOptions(GrpcTransportOptions transportOptions) {
@Override
public Builder setHost(String host) {
this.host = host;
// Treat null or default Datastore endpoints as non-custom so universe-domain resolution and
// transport switching still apply.
this.hasCustomHost = host != null && !DatastoreUtils.isDefaultHost(host);
if (!this.hasCustomChannelProvider) {
// Clear auto-generated channel provider so the constructor rebuilds it with the new host
// (or defers the endpoint to GAX when reset to null/default).
this.channelProvider = null;
}
return super.setHost(host);
}

/**
* Sets the universe domain and resets any auto-generated channel provider so endpoint
* resolution reflects the updated configuration.
*/
@Override
public Builder setUniverseDomain(String universeDomain) {
if (!this.hasCustomChannelProvider) {
// Rebuild auto-generated channel provider so stale endpoints are not reused across
// toBuilder() clones.
this.channelProvider = null;
}
return super.setUniverseDomain(universeDomain);
}

/**
* Sets the {@link TransportChannelProvider} to use with this Datastore client.
*
Expand All @@ -209,6 +257,9 @@ public Builder setHost(String host) {
@BetaApi
public Builder setChannelProvider(TransportChannelProvider channelProvider) {
this.channelProvider = channelProvider;
// Setting a non-null provider marks it as caller-owned so later host/universe changes do not
// discard it; passing null reverts to auto-generated provider behavior.
this.hasCustomChannelProvider = channelProvider != null;
return this;
}

Expand All @@ -227,12 +278,15 @@ public Builder setChannelProvider(TransportChannelProvider channelProvider) {
@Override
public DatastoreOptions build() {
if (this.host == null) {
// Use whatever host value the user passes in, otherwise use the transport specific default
// host values
// Populate the transport-specific default host via super.setHost() instead of
// this.setHost()
// so hasCustomHost remains false and future toBuilder() transport switches can reset it.
if (this.transportOptions instanceof GrpcTransportOptions) {
this.setHost(DatastoreSettings.getDefaultEndpoint());
this.host = DatastoreSettings.getDefaultEndpoint();
super.setHost(this.host);
} else if (this.transportOptions instanceof HttpTransportOptions) {
this.setHost(DEFAULT_HOST);
this.host = DEFAULT_HOST;
super.setHost(this.host);
}
}
return new DatastoreOptions(this);
Expand Down Expand Up @@ -273,6 +327,11 @@ public Builder setRequestTags(List<String> requestTags) {
@Nonnull
public Builder setOpenTelemetryOptions(
@Nonnull DatastoreOpenTelemetryOptions openTelemetryOptions) {
if (!this.hasCustomChannelProvider) {
// Rebuild auto-generated channel provider so the updated telemetry channel configurator is
// attached.
this.channelProvider = null;
}
this.openTelemetryOptions = openTelemetryOptions;
return this;
}
Expand All @@ -281,6 +340,8 @@ public Builder setOpenTelemetryOptions(
private DatastoreOptions(Builder builder) {
super(DatastoreFactory.class, DatastoreRpcFactory.class, builder, new DatastoreDefaults());

this.hasCustomChannelProvider = builder.hasCustomChannelProvider;
this.hasCustomHost = builder.hasCustomHost;
this.openTelemetryOptions =
builder.openTelemetryOptions != null
? builder.openTelemetryOptions
Expand Down Expand Up @@ -317,7 +378,7 @@ private DatastoreOptions(Builder builder) {
.setChannelPoolSettings(datastoreChannelPoolSettings);
// Only pin the endpoint when a custom host is configured; otherwise leave it unset
// so GAX resolves datastore.<universeDomain>:443 automatically.
if (getHost() != null && !DatastoreSettings.getDefaultEndpoint().equals(getHost())) {
if (getHost() != null && !DatastoreUtils.isDefaultHost(getHost())) {
channelProviderBuilder.setEndpoint(getHost());
}
if (traceUtil.getChannelConfigurator() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,73 @@

import com.google.api.core.InternalApi;
import com.google.cloud.NoCredentials;
import com.google.cloud.datastore.v1.DatastoreSettings;
import com.google.common.base.Strings;
import com.google.common.net.InetAddresses;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

@InternalApi
public class DatastoreUtils {

private static final String DEFAULT_DATASTORE_HOSTNAME = "datastore.googleapis.com";

public static boolean isEmulator(DatastoreOptions datastoreOptions) {
return isLocalHost(datastoreOptions.getHost())
|| NoCredentials.getInstance().equals(datastoreOptions.getCredentials());
}

/**
* Returns {@code true} if {@code host} matches the default Datastore service host for either HTTP
* ({@code https://datastore.googleapis.com}) or gRPC ({@code datastore.googleapis.com:443}).
*
* <p>Recognizing both transport defaults allows transport switches via {@code toBuilder()} and
* custom universe-domain endpoint resolution to distinguish default hosts from explicit custom
* host overrides.
*/
public static boolean isDefaultHost(String host) {
if (Strings.isNullOrEmpty(host)) {
return false;
}
// removeScheme() lowercases the input before stripping http:// or https://.
String normalized = removeScheme(host);
return DEFAULT_DATASTORE_HOSTNAME.equals(normalized)
|| DatastoreSettings.getDefaultEndpoint().equals(normalized);
}
Comment thread
jinseopkim0 marked this conversation as resolved.
Resolved

public static boolean isLocalHost(String host) {
if (Strings.isNullOrEmpty(host)) {
return false;
}
String hostWithoutScheme = removeScheme(host);
if (Strings.isNullOrEmpty(hostWithoutScheme)) {
return false;
}
try {
String normalizedHost = "http://" + removeScheme(host);
InetAddress hostAddr = InetAddress.getByName(new URL(normalizedHost).getHost());
String hostname = new URL("http://" + hostWithoutScheme).getHost();
// Short-circuit the default Datastore host before DNS resolution so default clients in
// air-gapped or non-default-universe networks never look up datastore.googleapis.com.
if (Strings.isNullOrEmpty(hostname) || DEFAULT_DATASTORE_HOSTNAME.equals(hostname)) {
return false;
}
// Avoid DNS lookups for literal "localhost" and numeric IPv4/IPv6 addresses (e.g., 127.0.0.1,
// 0.0.0.0, [::1]).
if ("localhost".equals(hostname)) {
return true;
}
if (InetAddresses.isUriInetAddress(hostname)) {
InetAddress hostAddr = InetAddresses.forUriString(hostname);
return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress();
}
// Fall back to DNS for custom local aliases (e.g., /etc/hosts entries mapped to loopback).
InetAddress hostAddr = InetAddress.getByName(hostname);
return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress();
} catch (Exception e) {
throw new RuntimeException(e);
} catch (UnknownHostException | MalformedURLException e) {
// Unresolvable or malformed hosts are not local emulators; fail open to non-emulator mode
// instead of crashing client initialization in air-gapped networks.
return false;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.cloud.datastore.spi.v1;

import static com.google.cloud.datastore.DatastoreUtils.isDefaultHost;
import static com.google.cloud.datastore.DatastoreUtils.isEmulator;
import static com.google.cloud.datastore.DatastoreUtils.removeScheme;
import static com.google.cloud.datastore.spi.v1.RpcUtils.retrySettingSetter;
Expand Down Expand Up @@ -205,8 +206,7 @@ ClientContext getClientContext(DatastoreOptions datastoreOptions) throws IOExcep
// and validates credentials against it.
settingsBuilder.setUniverseDomain(datastoreOptions.getUniverseDomain());
// Preserve custom host overrides; default hosts are resolved by GAX from the universe domain.
if (datastoreOptions.getHost() != null
&& !DatastoreSettings.getDefaultEndpoint().equals(datastoreOptions.getHost())) {
if (datastoreOptions.getHost() != null && !isDefaultHost(datastoreOptions.getHost())) {
settingsBuilder.setEndpoint(datastoreOptions.getHost());
}
return ClientContext.create(settingsBuilder.build());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@

package com.google.cloud.datastore.spi.v1;

import static com.google.cloud.datastore.DatastoreUtils.isDefaultHost;
import static com.google.cloud.datastore.DatastoreUtils.isLocalHost;
import static com.google.cloud.datastore.DatastoreUtils.removeScheme;

import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
Expand Down Expand Up @@ -47,8 +51,6 @@
import com.google.rpc.Code;
import io.opencensus.trace.Tracing;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import javax.annotation.Nullable;

@InternalApi
Expand Down Expand Up @@ -115,9 +117,9 @@ static com.google.datastore.v1.client.DatastoreOptions.Builder createClientOptio

if (isLocalHost(normalizedHost)) {
clientBuilder = clientBuilder.localHost(removeScheme(normalizedHost));
} else if (!removeScheme(normalizedHost)
.equals(removeScheme(com.google.datastore.v1.client.DatastoreFactory.DEFAULT_HOST))
&& !normalizedHost.isEmpty()) {
} else if (!isDefaultHost(normalizedHost) && !normalizedHost.isEmpty()) {
// Only treat non-default hosts as custom overrides; both HTTP and gRPC default hosts fall
// through to universe-domain host resolution below.
// DatastoreFactory.create(...) automatically builds the valid endpoint URL using the host,
// so we only need to set the host without any suffix.
clientBuilder = clientBuilder.host(removeScheme(normalizedHost));
Expand Down Expand Up @@ -184,30 +186,6 @@ public void initialize(HttpRequest httpRequest) throws IOException {
};
}

private static boolean isLocalHost(String host) {
if (!host.isEmpty()) {
try {
String normalizedHost = "http://" + removeScheme(host);
InetAddress hostAddr = InetAddress.getByName(new URL(normalizedHost).getHost());
return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress();
} catch (Exception e) {
// ignore
}
}
return false;
}

private static String removeScheme(String url) {
if (url != null) {
if (url.startsWith("https://")) {
return url.substring("https://".length());
} else if (url.startsWith("http://")) {
return url.substring("http://".length());
}
}
return url;
}

private static DatastoreException translate(
com.google.datastore.v1.client.DatastoreException exception) {
return translate(exception, true);
Expand Down
Loading
Loading