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
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Any

BUILT_IN_METRICS_METER_NAME = "gax-python"
NATIVE_METRICS_PREFIX = "spanner.googleapis.com/internal/client"
SPANNER_RESOURCE_TYPE = "spanner_instance_client"
Expand All @@ -21,6 +23,18 @@
GOOGLE_CLOUD_REGION_GLOBAL = "global"
SPANNER_METHOD_PREFIX = "/google.spanner.v1."


def _safe_decode_utf8(value: Any) -> str:
"""Safely decode bytes to str or return str representation without raising."""
if value is None:
return ""
if isinstance(value, str):
return value
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
return str(value)


# Monitored resource labels
MONITORED_RES_LABEL_KEY_PROJECT = "project_id"
MONITORED_RES_LABEL_KEY_INSTANCE = "instance_id"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def __init__(self, resource_info: dict = None):
resource_info (dict): Optional dictionary containing project, instance and database info.
"""
self._resource_info = resource_info
self._token = None

def __enter__(self):
"""Enter the runtime context related to this object.
Expand Down Expand Up @@ -88,15 +89,16 @@ def __exit__(self, exc_type, exc_value, traceback):
Returns:
bool: False to propagate the exception if any occurred.
"""
# Short circuit out if metrics are disable
if not SpannerMetricsTracerFactory().enabled:
token = self._token
if token is None:
return False

tracer = SpannerMetricsTracerFactory.get_current_tracer()
if tracer:
tracer.record_operation_completion()

# Reset the context var using the token
if getattr(self, "_token", None):
SpannerMetricsTracerFactory.reset_current_tracer(self._token)
try:
tracer = SpannerMetricsTracerFactory.get_current_tracer()
if tracer:
tracer.record_operation_completion()
finally:
# Reset the context var using the token
SpannerMetricsTracerFactory.reset_current_tracer(token)
self._token = None
return False # Propagate the exception if any
Loading
Loading