Skip to content
Merged
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 @@ -25,6 +25,7 @@
"""

__CROSS_SYNC_OUTPUT__ = "google.cloud.spanner_v1.client"
import copy
import logging
import os
import threading
Expand Down Expand Up @@ -445,6 +446,7 @@ def __init__(
"http://" in self._emulator_host or "https://" in self._emulator_host
):
warnings.warn(_EMULATOR_HOST_HTTP_SCHEME)
self._disable_builtin_metrics = disable_builtin_metrics
if (
_get_spanner_enable_builtin_metrics_env()
and not disable_builtin_metrics
Expand Down Expand Up @@ -704,16 +706,58 @@ def directed_read_options(self):
"""
return self._directed_read_options

def copy(self):
def copy(self) -> "Client":
"""Make a copy of this client.

Copies the local data stored as simple types but does not copy the
current state of any open connections with the Cloud Bigtable API.
Copies local client configuration (including ``client_options``,
``client_info``, ``query_options``, ``route_to_leader_enabled``,
``directed_read_options``, ``observability_options``,
``default_transaction_options``, ``disable_builtin_metrics``,
``client_context``, ``instance_type``, and TLS settings) without
copying open RPC connections. Clears ``credentials_file`` and
``api_key`` on the copied ``client_options`` because resolved
credentials are passed directly.

:rtype: :class:`.Client`
:returns: A copy of the current client.
"""
return self.__class__(project=self.project, credentials=self._credentials)
if not self._client_options:
client_options = None
else:
client_options = copy.copy(self._client_options)

if client_options is not None:
# Resolved self._credentials is forwarded directly; keeping
# credentials_file or api_key would raise DuplicateCredentialArgs.
client_options.credentials_file = None
client_options.api_key = None

if self._instance_type == "omni":
if client_options is None:
client_options = google.api_core.client_options.ClientOptions(
api_endpoint=self._host
)
else:
client_options.api_endpoint = self._host

return self.__class__(
project=self.project,
credentials=self._credentials,
client_info=self._client_info,
client_options=client_options,
query_options=self._query_options,
route_to_leader_enabled=self._route_to_leader_enabled,
directed_read_options=copy.copy(self._directed_read_options),
observability_options=copy.copy(self._observability_options),
default_transaction_options=self._default_transaction_options,
disable_builtin_metrics=self._disable_builtin_metrics,
client_context=self._client_context,
instance_type=self._instance_type,
use_plain_text=self._use_plain_text,
ca_certificate=self._ca_certificate,
client_certificate=self._client_certificate,
client_key=self._client_key,
)

@CrossSync.convert
async def list_instance_configs(self, page_size=None):
Expand Down
47 changes: 43 additions & 4 deletions packages/google-cloud-spanner/google/cloud/spanner_v1/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
:class:`~google.cloud.spanner_v1.database.Database`
"""

import copy
import logging
import os
import threading
Expand Down Expand Up @@ -389,6 +390,7 @@ def __init__(
"http://" in self._emulator_host or "https://" in self._emulator_host
):
warnings.warn(_EMULATOR_HOST_HTTP_SCHEME)
self._disable_builtin_metrics = disable_builtin_metrics
if (
_get_spanner_enable_builtin_metrics_env()
and (not disable_builtin_metrics)
Expand Down Expand Up @@ -590,15 +592,52 @@ def directed_read_options(self):
:returns: The directed_read_options for the client."""
return self._directed_read_options

def copy(self):
def copy(self) -> "Client":
"""Make a copy of this client.

Copies the local data stored as simple types but does not copy the
current state of any open connections with the Cloud Bigtable API.
Copies local client configuration (including ``client_options``,
``client_info``, ``query_options``, ``route_to_leader_enabled``,
``directed_read_options``, ``observability_options``,
``default_transaction_options``, ``disable_builtin_metrics``,
``client_context``, ``instance_type``, and TLS settings) without
copying open RPC connections. Clears ``credentials_file`` and
``api_key`` on the copied ``client_options`` because resolved
credentials are passed directly.

:rtype: :class:`.Client`
:returns: A copy of the current client."""
return self.__class__(project=self.project, credentials=self._credentials)
if not self._client_options:
client_options = None
else:
client_options = copy.copy(self._client_options)
if client_options is not None:
client_options.credentials_file = None
client_options.api_key = None
if self._instance_type == "omni":
if client_options is None:
client_options = google.api_core.client_options.ClientOptions(
api_endpoint=self._host
)
else:
client_options.api_endpoint = self._host
return self.__class__(
project=self.project,
credentials=self._credentials,
client_info=self._client_info,
client_options=client_options,
query_options=self._query_options,
route_to_leader_enabled=self._route_to_leader_enabled,
directed_read_options=copy.copy(self._directed_read_options),
observability_options=copy.copy(self._observability_options),
default_transaction_options=self._default_transaction_options,
disable_builtin_metrics=self._disable_builtin_metrics,
client_context=self._client_context,
instance_type=self._instance_type,
use_plain_text=self._use_plain_text,
ca_certificate=self._ca_certificate,
client_certificate=self._client_certificate,
client_key=self._client_key,
)

def list_instance_configs(self, page_size=None):
"""List available instance configurations for the client's project.
Expand Down
244 changes: 244 additions & 0 deletions packages/google-cloud-spanner/tests/unit/_async/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,3 +1056,247 @@ async def test_constructor_w_omni_explicit_credentials_instance(self):
credentials=creds,
)
self.assertIs(client._credentials, creds)

def _make_credentials(self):
from google.auth import credentials as ga_credentials

class _TestCredentials(ga_credentials.Credentials):
def refresh(self, request):
self.token = "token"

def with_quota_project(self, quota_project_id):
return self

return _TestCredentials()

@CrossSync.pytest
async def test_copy_preserves_client_options_and_configuration_without_mutating_original(
self,
):
from google.api_core.client_options import ClientOptions
from google.api_core.gapic_v1 import client_info as client_info_lib

from google.cloud.spanner_v1._async import client as MUT
from google.cloud.spanner_v1.types import RequestOptions

credentials = self._make_credentials()
custom_info = client_info_lib.ClientInfo(user_agent="custom-agent/1.0")
original_options = ClientOptions(
universe_domain="custom.example",
api_endpoint="spanner.custom.example:443",
quota_project_id="quota-proj",
)
original_observability_options = {"enable_extended_tracing": False}
original_directed_read_options = {
"include_replicas": {
"replica_selections": [{"location": "us-east1"}],
"auto_failover_disabled": True,
}
}
client_context = RequestOptions.ClientContext(secure_context={"key": "value"})

with (
mock.patch.dict(
os.environ,
{"SPANNER_DISABLE_BUILTIN_METRICS": "false"},
clear=False,
),
mock.patch.object(MUT, "_initialize_metrics") as mock_initialize_metrics,
):
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("SPANNER_EMULATOR_HOST", None)
client = self._make_one(
project=self.PROJECT,
credentials=credentials,
client_info=custom_info,
client_options=original_options,
query_options={"optimizer_version": "4"},
route_to_leader_enabled=False,
directed_read_options=original_directed_read_options,
observability_options=original_observability_options,
default_transaction_options=self.DEFAULT_TRANSACTION_OPTIONS,
disable_builtin_metrics=True,
client_context=client_context,
use_plain_text=True,
ca_certificate="/tmp/ca.pem",
client_certificate="/tmp/cert.pem",
client_key="/tmp/key.pem",
)
client._instance_admin_api = mock.Mock()
client._database_admin_api = mock.Mock()
copied = client.copy()
mock_initialize_metrics.assert_not_called()

self.assertIsNot(copied, client)
self.assertIsNot(copied._client_options, original_options)
self.assertEqual(copied._client_options.universe_domain, "custom.example")
self.assertEqual(
copied._client_options.api_endpoint, "spanner.custom.example:443"
)
self.assertEqual(copied._client_options.quota_project_id, "quota-proj")
self.assertEqual(copied._host, "spanner.custom.example:443")
self.assertIs(copied._client_info, custom_info)
self.assertEqual(copied._query_options, client._query_options)
self.assertFalse(copied.route_to_leader_enabled)
self.assertEqual(copied.directed_read_options, original_directed_read_options)
self.assertIsNot(copied.directed_read_options, original_directed_read_options)
self.assertEqual(copied._observability_options, original_observability_options)
self.assertIsNot(copied._observability_options, original_observability_options)
self.assertEqual(
copied.default_transaction_options, self.DEFAULT_TRANSACTION_OPTIONS
)
self.assertTrue(copied._disable_builtin_metrics)
self.assertEqual(copied._client_context, client._client_context)
self.assertTrue(copied._use_plain_text)
self.assertEqual(copied._ca_certificate, "/tmp/ca.pem")
self.assertEqual(copied._client_certificate, "/tmp/cert.pem")
self.assertEqual(copied._client_key, "/tmp/key.pem")
self.assertIsNone(copied._instance_admin_api)
self.assertIsNone(copied._database_admin_api)

with mock.patch.dict(os.environ, {}, clear=False):
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("SPANNER_EMULATOR_HOST", None)
empty_options_client = self._make_one(
project=self.PROJECT, credentials=credentials, client_options={}
)
copied_empty = empty_options_client.copy()
self.assertIsNone(copied_empty._client_options)

@CrossSync.pytest
async def test_copy_clears_credential_options_without_mutating_original(self):
from google.api_core.client_options import ClientOptions

credentials = self._make_credentials()
with (
mock.patch.dict(os.environ, {}, clear=False),
mock.patch(
"google.auth.load_credentials_from_file",
return_value=(credentials, self.PROJECT),
),
):
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("SPANNER_EMULATOR_HOST", None)
file_options = ClientOptions(
credentials_file="/tmp/fake-credentials.json",
api_endpoint="spanner.custom.example",
)
client_from_file = self._make_one(
project=self.PROJECT, client_options=file_options
)
copied_file = client_from_file.copy()
self.assertIsNone(copied_file._client_options.credentials_file)
self.assertEqual(
file_options.credentials_file, "/tmp/fake-credentials.json"
)
self.assertEqual(copied_file._host, "spanner.custom.example")

with (
mock.patch.dict(os.environ, {}, clear=False),
mock.patch("google.auth.default", return_value=(credentials, self.PROJECT)),
):
os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
os.environ.pop("SPANNER_EMULATOR_HOST", None)
api_key_options = ClientOptions(
api_key="test-api-key",
api_endpoint="spanner.custom.example",
)
client_api_key = self._make_one(
project=self.PROJECT, client_options=api_key_options
)
copied_api_key = client_api_key.copy()
self.assertIsNone(copied_api_key._client_options.api_key)
self.assertEqual(api_key_options.api_key, "test-api-key")

@CrossSync.pytest
async def test_copy_preserves_omni_configuration(self):
import warnings

from google.api_core.client_options import ClientOptions

from google.cloud.spanner_v1._async.client import InstanceType
from google.cloud.spanner_v1.omni.credentials import (
SpannerOmniCredentials,
)

standard_omni_client = self._make_one(
project=self.PROJECT,
instance_type=InstanceType.OMNI,
client_options={"api_endpoint": "omni.host:15000"},
username="omni_user",
password="omni_password",
ca_certificate="/tmp/omni-ca.pem",
client_certificate="/tmp/omni-cert.pem",
client_key="/tmp/omni-key.pem",
)
copied_standard_omni = standard_omni_client.copy()
self.assertEqual(copied_standard_omni.instance_type, InstanceType.OMNI)
self.assertEqual(copied_standard_omni._host, "omni.host:15000")
self.assertEqual(
copied_standard_omni._client_options.api_endpoint, "omni.host:15000"
)
self.assertIsInstance(copied_standard_omni._credentials, SpannerOmniCredentials)
self.assertIs(
copied_standard_omni._credentials, standard_omni_client._credentials
)
self.assertEqual(copied_standard_omni._ca_certificate, "/tmp/omni-ca.pem")
self.assertEqual(copied_standard_omni._client_certificate, "/tmp/omni-cert.pem")
self.assertEqual(copied_standard_omni._client_key, "/tmp/omni-key.pem")

with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
omni_client = self._make_one(
project=self.PROJECT,
experimental_host="omni.host:15000",
use_plain_text=True,
)
copied_omni = omni_client.copy()
self.assertEqual(copied_omni.instance_type, InstanceType.OMNI)
self.assertEqual(copied_omni._host, "omni.host:15000")
self.assertEqual(copied_omni._client_options.api_endpoint, "omni.host:15000")
self.assertTrue(copied_omni._use_plain_text)

original_omni_options = ClientOptions()
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
omni_client_options = self._make_one(
project=self.PROJECT,
experimental_host="omni.host:15000",
client_options=original_omni_options,
use_plain_text=True,
)
copied_omni_options = omni_client_options.copy()
self.assertEqual(copied_omni_options.instance_type, InstanceType.OMNI)
self.assertEqual(copied_omni_options._host, "omni.host:15000")
self.assertEqual(
copied_omni_options._client_options.api_endpoint, "omni.host:15000"
)
self.assertIsNone(original_omni_options.api_endpoint)

conflicting_omni_options = ClientOptions(api_endpoint="other.host:443")
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
conflicting_omni_client = self._make_one(
project=self.PROJECT,
experimental_host="omni.host:15000",
client_options=conflicting_omni_options,
use_plain_text=True,
)
copied_conflicting_omni = conflicting_omni_client.copy()
self.assertEqual(copied_conflicting_omni._host, "omni.host:15000")
self.assertEqual(
copied_conflicting_omni._client_options.api_endpoint,
"omni.host:15000",
)
self.assertEqual(conflicting_omni_options.api_endpoint, "other.host:443")

@CrossSync.pytest
async def test_copy_preserves_anonymous_credentials_client(self):
anonymous_client = self._make_one(
project=self.PROJECT,
credentials=AnonymousCredentials(),
client_options={"api_endpoint": "localhost:9010"},
)
copied_anonymous = anonymous_client.copy()
self.assertEqual(copied_anonymous._emulator_host, "localhost:9010")
self.assertEqual(copied_anonymous._host, "localhost:9010")
Loading
Loading