Skip to content
Open
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
86 changes: 74 additions & 12 deletions packages/google-cloud-ndb/google/cloud/ndb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@

import contextlib
import os
from collections.abc import Mapping

import google.api_core.client_options
import grpc
import requests
from google.api_core import universe
from google.api_core.gapic_v1 import client_info
from google.auth import compute_engine
from google.auth import credentials as auth_credentials
from google.cloud.datastore_v1.services.datastore.transports import (
grpc as datastore_grpc,
)
Expand All @@ -31,13 +35,63 @@
from google.cloud.ndb import context as context_module
from google.cloud.ndb import key as key_module

try:
# google.auth.aio was added in google-auth 2.28.0; older supported versions
# only provide synchronous AnonymousCredentials.
from google.auth.aio import credentials as _aio_credentials

_ANONYMOUS_CREDENTIAL_TYPES: tuple[type, ...] = (
auth_credentials.AnonymousCredentials,
_aio_credentials.AnonymousCredentials,
)
except ImportError: # pragma: NO COVER
_ANONYMOUS_CREDENTIAL_TYPES = (auth_credentials.AnonymousCredentials,)

_CLIENT_INFO = client_info.ClientInfo(
user_agent="google-cloud-ndb/{}".format(__version__)
)

DATASTORE_API_HOST = "datastore.googleapis.com"


# TODO(universe-domain): Replace with
# google.api_core.universe.resolve_client_universe once
# testing/constraints-3.10.txt exceeds google-api-core 2.44.0.
def _resolve_client_universe(client_options=None):
"""Resolve a client's universe domain from ``client_options`` or the environment."""
if client_options is None:
options_universe = None
elif isinstance(client_options, Mapping):
options_universe = client_options.get("universe_domain")
elif isinstance(client_options, google.api_core.client_options.ClientOptions):
options_universe = client_options.universe_domain
else:
raise TypeError(
"client_options must be a ClientOptions instance, Mapping, or None; "
f"got {type(client_options).__name__}"
)
return universe.determine_domain(
options_universe,
os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN"),
).strip()


# TODO(universe-domain): Replace with
# google.api_core.universe.validate_credentials_universe once
# testing/constraints-3.10.txt exceeds google-api-core 2.44.0.
def _validate_credentials_universe(client_universe, credentials):
Comment thread
ohmayr marked this conversation as resolved.
Resolved
"""Validate that resolved client credentials match ``client_universe``."""
if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
return
# Avoid synchronous GCE metadata server HTTP calls when
# compute_engine.Credentials hasn't resolved its universe yet.
if isinstance(credentials, compute_engine.Credentials) and not getattr(
credentials, "_universe_domain_cached", False
):
return
universe.compare_domains(client_universe, credentials)
Comment thread
ohmayr marked this conversation as resolved.
Resolved


def _get_gcd_project():
"""Gets the GCD application ID if it can be inferred."""
return os.getenv(environment_vars.GCD_DATASET)
Expand Down Expand Up @@ -104,27 +158,29 @@ def __init__(
database=None,
):
self.namespace = namespace
self.host = os.environ.get(environment_vars.GCD_HOST, DATASTORE_API_HOST)
self.client_info = _CLIENT_INFO
self._client_options = client_options
self.database = database

# Use insecure connection when using Datastore Emulator, otherwise
# use secure connection
emulator = bool(os.environ.get(environment_vars.GCD_HOST))
emulator_host = os.environ.get(environment_vars.GCD_HOST)
emulator = bool(emulator_host)
self.secure = not emulator

# Use Datastore API host from client_options if provided, otherwise use default
api_endpoint = DATASTORE_API_HOST
if client_options is not None:
if isinstance(client_options, dict):
client_options = google.api_core.client_options.from_dict(
client_options
)
if client_options.api_endpoint:
api_endpoint = client_options.api_endpoint
if isinstance(client_options, Mapping):
client_options = google.api_core.client_options.from_dict(client_options)

universe_domain = _resolve_client_universe(client_options)
self._universe_domain = universe_domain

# Use Datastore API host from client_options if provided, otherwise
# template using the resolved universe_domain.
api_endpoint = f"datastore.{universe_domain}"
if client_options is not None and client_options.api_endpoint:
api_endpoint = client_options.api_endpoint

self.host = os.environ.get(environment_vars.GCD_HOST, api_endpoint)
self.host = emulator_host or api_endpoint

if emulator:
# When using the emulator, in theory, the client shouldn't need to
Expand Down Expand Up @@ -153,6 +209,7 @@ def __init__(
],
)
else:
_validate_credentials_universe(self._universe_domain, self._credentials)
user_agent = self.client_info.to_user_agent()
channel = _helpers.make_secure_channel(
self._credentials, user_agent, self.host
Expand Down Expand Up @@ -238,6 +295,11 @@ def context(
# Finish up any work left to do on the event loop
context.eventloop.run()

@property
def universe_domain(self):
"""The universe domain used by the client."""
return self._universe_domain

@property
def _http(self):
"""Getter for object used for HTTP transport.
Expand Down
3 changes: 2 additions & 1 deletion packages/google-cloud-ndb/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ def initialize_environment(request, environ):
the current request, determines whether it's in a unit test, or not, and
does the right thing.
"""
if request.module.__name__.startswith("tests.unit"): # pragma: NO COVER
if request.module.__name__.startswith(("tests.unit", "unit.")): # pragma: NO COVER
environ.pop(environment_vars.GCD_DATASET, None)
environ.pop(environment_vars.GCD_HOST, None)
environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)


@pytest.fixture
Expand Down
Loading
Loading