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 @@ -55,6 +55,7 @@
from google.cloud.spanner_v1._async.streamed import StreamedResultSet
from google.cloud.spanner_v1._helpers import (
_augment_errors_with_request_id,
_clone_request_options,
_merge_query_options,
_metadata_with_leader_aware_routing,
_metadata_with_prefix,
Expand Down Expand Up @@ -922,8 +923,10 @@ async def execute_partitioned_dml(
)
if request_options is None:
request_options = RequestOptions()
elif type(request_options) is dict:
request_options = RequestOptions(request_options)
else:
# Always clone non-None input so clearing transaction_tag never
# mutates a caller-provided RequestOptions or dict subclass.
request_options = _clone_request_options(request_options)
request_options.transaction_tag = None

if params is not None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,39 @@ def _validate_client_context(client_context):
return client_context


# The protobuf class underlying the proto-plus ``RequestOptions`` wrapper.
_REQUEST_OPTIONS_PB = RequestOptions.pb()


def _clone_request_options(request_options):
"""Return an independent RequestOptions copy without mutating caller input.

Uses protobuf ``CopyFrom`` and ``RequestOptions.wrap`` directly for
proto-plus ``RequestOptions`` inputs to avoid Python ``copy.deepcopy``
overhead in ``RequestOptions(mapping)``, while delegating dicts, raw
protobufs, and invalid types to ``RequestOptions(...)``.

:type request_options: :class:`~google.cloud.spanner_v1.types.RequestOptions`
or :class:`dict`
:param request_options: Non-``None`` request options to clone.

:rtype: :class:`~google.cloud.spanner_v1.types.RequestOptions`
:returns: A fresh ``RequestOptions`` backed by an independent protobuf.
"""
if isinstance(request_options, RequestOptions):
copied_pb = _REQUEST_OPTIONS_PB()
copied_pb.CopyFrom(RequestOptions.pb(request_options))
return RequestOptions.wrap(copied_pb)
return RequestOptions(request_options)


def _merge_request_options(request_options, client_context):
"""Merge RequestOptions and ClientContext.
"""Merge RequestOptions and ClientContext without mutating caller input.

Always returns a fresh :class:`~google.cloud.spanner_v1.types.RequestOptions`
copy whenever ``request_options`` is provided so callers may safely merge
``client_context`` or update ``transaction_tag``/``request_tag`` without
polluting a caller-shared options instance across requests or threads.

:type request_options: :class:`~google.cloud.spanner_v1.types.RequestOptions`
or :class:`dict` or None
Expand All @@ -425,15 +456,18 @@ def _merge_request_options(request_options, client_context):
:rtype: :class:`~google.cloud.spanner_v1.types.RequestOptions`
or None
:returns:
RequestOptions object formed by merging the given ClientContext.
A new RequestOptions instance formed by cloning ``request_options`` and
merging ``client_context``, or ``None`` when both inputs are ``None``.
"""
if request_options is None and client_context is None:
return None

if request_options is None:
request_options = RequestOptions()
elif isinstance(request_options, dict):
request_options = RequestOptions(request_options)
else:
# Always clone non-None input (RequestOptions, raw protobuf, or dict)
# so merging client_context or adjusting tags never mutates caller state.
request_options = _clone_request_options(request_options)

if client_context:
request_options.client_context = _merge_client_context(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from google.cloud.spanner_admin_database_v1.types import DatabaseDialect
from google.cloud.spanner_v1._helpers import (
_augment_errors_with_request_id,
_clone_request_options,
_merge_query_options,
_metadata_with_leader_aware_routing,
_metadata_with_prefix,
Expand Down Expand Up @@ -812,8 +813,8 @@ def execute_partitioned_dml(
)
if request_options is None:
request_options = RequestOptions()
elif type(request_options) is dict:
request_options = RequestOptions(request_options)
else:
request_options = _clone_request_options(request_options)
request_options.transaction_tag = None
if params is not None:
from google.cloud.spanner_v1.transaction import Transaction
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1751,6 +1751,36 @@ async def test_execute_partitioned_dml_w_req_tag_used(self):
request_options=RequestOptions(request_tag="req-tag"),
)

@CrossSync.pytest
async def test_execute_partitioned_dml_does_not_mutate_request_options(self):
request_options = RequestOptions(
priority=RequestOptions.Priority.PRIORITY_LOW,
request_tag="req-tag",
transaction_tag="keep-tag",
)
await self._execute_partitioned_dml_helper(
dml=DML_W_PARAM,
request_options=request_options,
)
self.assertEqual(request_options.priority, RequestOptions.Priority.PRIORITY_LOW)
self.assertEqual(request_options.request_tag, "req-tag")
self.assertEqual(request_options.transaction_tag, "keep-tag")

class _OptionsDict(dict):
pass

dict_options = _OptionsDict(
priority=RequestOptions.Priority.PRIORITY_LOW,
request_tag="req-tag",
transaction_tag="keep-tag",
)
await self._execute_partitioned_dml_helper(
dml=DML_W_PARAM,
request_options=dict_options,
)
self.assertEqual(dict_options["transaction_tag"], "keep-tag")
self.assertFalse(hasattr(dict_options, "transaction_tag"))

@CrossSync.pytest
async def test_execute_partitioned_dml_wo_params_retry_aborted(self):
await self._execute_partitioned_dml_helper(dml=DML_WO_PARAM, retried=True)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,65 @@ async def test_execute_sql_twice_single_use_fails(self):
with self.assertRaisesRegex(ValueError, "Cannot re-use single-use snapshot."):
await snapshot.execute_sql("SELECT 1")

async def test_execute_sql_reuses_shared_request_options_across_tenants(self):
from google.protobuf import struct_pb2

from google.cloud.spanner_v1.types import RequestOptions

shared_options = RequestOptions(
priority=RequestOptions.Priority.PRIORITY_LOW,
request_tag="req-orig",
transaction_tag="keep-tag",
)
ctx_a = RequestOptions.ClientContext(
secure_context={
"tenant": struct_pb2.Value(string_value="A"),
"only_a": struct_pb2.Value(string_value="secret"),
}
)
ctx_b = RequestOptions.ClientContext(
secure_context={"tenant": struct_pb2.Value(string_value="B")}
)

session_a = _Session()
session_a._database.spanner_api.execute_streaming_sql.return_value = (
_MockIterator(PartialResultSet())
)
snap_a = self._make_snapshot(session_a, client_context=ctx_a)
result_a = await snap_a.execute_sql("SELECT 1", request_options=shared_options)
async for _ in result_a:
pass
req_a = session_a._database.spanner_api.execute_streaming_sql.call_args.kwargs[
"request"
]

session_b = _Session()
session_b._database.spanner_api.execute_streaming_sql.return_value = (
_MockIterator(PartialResultSet())
)
snap_b = self._make_snapshot(session_b, client_context=ctx_b)
result_b = await snap_b.execute_sql("SELECT 1", request_options=shared_options)
async for _ in result_b:
pass
req_b = session_b._database.spanner_api.execute_streaming_sql.call_args.kwargs[
"request"
]

self.assertEqual(
dict(req_a.request_options.client_context.secure_context),
{"tenant": "A", "only_a": "secret"},
)
self.assertEqual(
dict(req_b.request_options.client_context.secure_context),
{"tenant": "B"},
)
self.assertEqual(req_a.request_options.transaction_tag, "")
self.assertEqual(req_b.request_options.transaction_tag, "")
self.assertEqual(shared_options.priority, RequestOptions.Priority.PRIORITY_LOW)
self.assertEqual(shared_options.request_tag, "req-orig")
self.assertEqual(shared_options.transaction_tag, "keep-tag")
self.assertNotIn("client_context", shared_options)

async def test_read_twice_single_use_fails(self):
from google.cloud.spanner_v1.keyset import KeySet

Expand Down
Loading
Loading