Skip to content

Commit 32a351a

Browse files
committed
Moved method/direct_path to setters from constructor
1 parent 0b3ece0 commit 32a351a

File tree

4 files changed

+53
-91
lines changed

4 files changed

+53
-91
lines changed

google/cloud/spanner_v1/metrics/metrics_tracer.py

Lines changed: 32 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -89,28 +89,23 @@ class MetricOpTracer:
8989
_start_time: datetime
9090
_current_attempt: MetricAttemptTracer
9191
status: str
92-
direct_path_enabled: bool
9392

9493
def __init__(self, is_direct_path_enabled: bool = False):
9594
"""
9695
Initialize a MetricOpTracer instance with the given parameters.
9796
98-
This constructor sets up a MetricOpTracer instance with the provided metric name, instrumentations for attempt latency,
99-
attempt counter, operation latency, operation counter, and a flag indicating whether the direct path is enabled.
100-
It initializes the method name, start time, attempt count, current attempt, direct path enabled status, and status of the metric operation.
97+
This constructor sets up a MetricOpTracer instance with the provided instrumentations for attempt latency,
98+
attempt counter, operation latency and operation counter.
10199
102100
Args:
103-
metric_name (str): The name of the metric operation.
104101
instrument_attempt_latency (Histogram): The instrumentation for measuring attempt latency.
105102
instrument_attempt_counter (Counter): The instrumentation for counting attempts.
106103
instrument_operation_latency (Histogram): The instrumentation for measuring operation latency.
107104
instrument_operation_counter (Counter): The instrumentation for counting operations.
108-
is_direct_path_enabled (bool, optional): A flag indicating whether the direct path is enabled. Defaults to False.
109105
"""
110106
self._attempt_count = 0
111107
self._start_time = datetime.now()
112108
self._current_attempt = None
113-
self.direct_path_enabled = is_direct_path_enabled
114109
self.status = ""
115110

116111
@property
@@ -159,15 +154,15 @@ def increment_attempt_count(self):
159154

160155
def start(self):
161156
"""
162-
Sets the start time of the metric operation to the current time.
157+
Set the start time of the metric operation to the current time.
163158
164159
This method updates the start time of the metric operation to the current time, indicating the operation has started.
165160
"""
166161
self._start_time = datetime.now()
167162

168163
def new_attempt(self):
169164
"""
170-
Initializes a new MetricAttemptTracer instance for the current metric operation.
165+
Initialize a new MetricAttemptTracer instance for the current metric operation.
171166
172167
This method sets up a new MetricAttemptTracer instance, indicating a new attempt is being made within the metric operation.
173168
"""
@@ -193,9 +188,7 @@ class should not have any knowledge about the observability framework used for m
193188

194189
def __init__(
195190
self,
196-
method: str,
197191
enabled: bool,
198-
is_direct_path_enabled: bool,
199192
instrument_attempt_latency: Histogram,
200193
instrument_attempt_counter: Counter,
201194
instrument_operation_latency: Histogram,
@@ -210,17 +203,14 @@ def __init__(
210203
It sets up the necessary metrics tracing infrastructure for recording metrics related to RPC operations.
211204
212205
Args:
213-
method (str): The name of the method for which metrics are being traced.
214206
enabled (bool): A flag indicating if metrics tracing is enabled.
215-
is_direct_path_enabled (bool): A flag indicating if the direct path is enabled for metrics tracing.
216207
instrument_attempt_latency (Histogram): The instrument for measuring attempt latency.
217208
instrument_attempt_counter (Counter): The instrument for counting attempts.
218209
instrument_operation_latency (Histogram): The instrument for measuring operation latency.
219210
instrument_operation_counter (Counter): The instrument for counting operations.
220211
client_attributes (dict[str, str]): A dictionary of client attributes used for metrics tracing.
221212
"""
222-
self.method = method
223-
self.current_op = MetricOpTracer(is_direct_path_enabled=is_direct_path_enabled)
213+
self.current_op = MetricOpTracer()
224214
self._client_attributes = client_attributes
225215
self._instrument_attempt_latency = instrument_attempt_latency
226216
self._instrument_attempt_counter = instrument_attempt_counter
@@ -396,63 +386,31 @@ def record_operation_completion(self) -> None:
396386
self.current_op.attempt_count, attributes=attempt_attributes
397387
)
398388

399-
def _create_otel_attributes(self) -> Dict[str, str]:
389+
def _create_operation_otel_attributes(self) -> dict:
400390
"""
401-
Create a dictionary of attributes for OpenTelemetry metrics tracing.
391+
Create additional attributes for operation metrics tracing.
402392
403-
This method initializes a copy of the client attributes and adds specific operation attributes
404-
such as the method name, direct path enabled status, and direct path used status.
405-
These attributes are used to provide context to the metrics being traced.
406-
If metrics tracing is not enabled, this method does not perform any operations.
407-
Returns:
408-
dict[str, str]: A dictionary of attributes for OpenTelemetry metrics tracing.
393+
This method populates the client attributes dictionary with the operation status if metrics tracing is enabled.
394+
It returns the updated client attributes dictionary.
409395
"""
410396
if not self.enabled:
411-
return
412-
413-
self.client_attributes[METRIC_LABEL_KEY_METHOD] = self.method
414-
self.client_attributes[METRIC_LABEL_KEY_DIRECT_PATH_ENABLED] = str(
415-
self.current_op.direct_path_enabled
416-
)
417-
if self.current_op.current_attempt is not None:
418-
self.client_attributes[METRIC_LABEL_KEY_DIRECT_PATH_USED] = str(
419-
self.current_op.current_attempt.direct_path_used
420-
)
421-
422-
return self.client_attributes
397+
return {}
423398

424-
def _create_operation_otel_attributes(self) -> Dict[str, str]:
425-
"""
426-
Create a dictionary of attributes specific to an operation for OpenTelemetry metrics tracing.
427-
428-
This method builds upon the base attributes created by `_create_otel_attributes` and adds the operation status.
429-
These attributes are used to provide context to the metrics being traced for a specific operation.
430-
If metrics tracing is not enabled, this method does not perform any operations.
431-
432-
Returns:
433-
dict[str, str]: A dictionary of attributes specific to an operation for OpenTelemetry metrics tracing.
434-
"""
435-
if not self.enabled:
436-
return
399+
self._client_attributes[METRIC_LABEL_KEY_STATUS] = self.current_op.status
400+
return self._client_attributes
437401

438-
attributes = self._create_otel_attributes()
439-
attributes[METRIC_LABEL_KEY_STATUS] = self.current_op.status
440-
return attributes
441402

442-
def _create_attempt_otel_attributes(self) -> Dict[str, str]:
403+
def _create_attempt_otel_attributes(self) -> dict:
443404
"""
444-
Create a dictionary of attributes specific to an attempt within an operation for OpenTelemetry metrics tracing.
405+
Create additional attributes for attempt metrics tracing.
445406
446-
This method builds upon the operation attributes created by `_create_operation_otel_attributes` and adds the attempt status.
447-
These attributes are used to provide context to the metrics being traced for a specific attempt within an operation.
448-
If metrics tracing is not enabled, this method does not perform any operations.
449-
Returns:
450-
dict[str, str]: A dictionary of attributes specific to an attempt within an operation for OpenTelemetry metrics tracing.
407+
This method populates the attributes dictionary with the attempt status if metrics tracing is enabled and an attempt exists.
408+
It returns the updated attributes dictionary.
451409
"""
452410
if not self.enabled:
453-
return
411+
return {}
454412

455-
attributes = self._create_operation_otel_attributes()
413+
attributes = {}
456414
# Short circuit out if we don't have an attempt
457415
if self.current_op.current_attempt is not None:
458416
attributes[METRIC_LABEL_KEY_STATUS] = self.current_op.current_attempt.status
@@ -573,6 +531,20 @@ def set_database(self, database: str) -> "MetricsTracer":
573531
self._client_attributes[METRIC_LABEL_KEY_DATABASE] = database
574532
return self
575533

534+
def set_method(self, method: str) -> "MetricsTracer":
535+
"""
536+
Set the method attribute for metrics tracing.
537+
538+
This method updates the method attribute in the client attributes dictionary for metrics tracing purposes.
539+
If the database attribute already has a value, this method does nothing and returns.
540+
541+
:param method: The method name to set.
542+
:return: This instance of MetricsTracer for method chaining.
543+
"""
544+
if METRIC_LABEL_KEY_METHOD not in self._client_attributes:
545+
self.client_attributes[METRIC_LABEL_KEY_METHOD] = method
546+
return self
547+
576548
def enable_direct_path(self, enable: bool = False) -> "MetricsTracer":
577549
"""
578550
Enable or disable the direct path for metrics tracing.

google/cloud/spanner_v1/metrics/metrics_tracer_factory.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -240,30 +240,24 @@ def enable_direct_path(self, enable: bool = False) -> "MetricsTracerFactory":
240240
self._client_attributes[METRIC_LABEL_KEY_DIRECT_PATH_ENABLED] = enable
241241
return self
242242

243-
def create_metrics_tracer(
244-
self, method: str, is_direct_path_enabled: bool = False
245-
) -> MetricsTracer:
246-
"""Create and return a MetricsTracer instance with default settings and client attributes.
243+
def create_metrics_tracer(self) -> MetricsTracer:
244+
"""
245+
Create and return a MetricsTracer instance with default settings and client attributes.
247246
248247
This method initializes a MetricsTracer instance with default settings for metrics tracing,
249-
with disabled metrics tracing and no direct path enabled by default.
248+
including metrics tracing enabled if OpenTelemetry is installed and the direct path disabled by default.
250249
It also sets the client attributes based on the factory's configuration.
251250
252-
Args:
253-
method (str): The name of the method for which metrics are being traced.
254-
255251
Returns:
256252
MetricsTracer: A MetricsTracer instance with default settings and client attributes.
257253
"""
258254
metrics_tracer = MetricsTracer(
259255
enabled=self.enabled and HAS_OPENTELEMETRY_INSTALLED,
260-
method=method,
261-
is_direct_path_enabled=is_direct_path_enabled,
262-
instrument_attempt_latency=self.instrument_attempt_latency,
263-
instrument_attempt_counter=self.instrument_attempt_counter,
264-
instrument_operation_latency=self.instrument_operation_latency,
265-
instrument_operation_counter=self.instrument_operation_counter,
266-
client_attributes=self.client_attributes.copy(),
256+
instrument_attempt_latency=self._instrument_attempt_latency,
257+
instrument_attempt_counter=self._instrument_attempt_counter,
258+
instrument_operation_latency=self._instrument_operation_latency,
259+
instrument_operation_counter=self._instrument_operation_counter,
260+
client_attributes=self._client_attributes.copy(),
267261
)
268262
return metrics_tracer
269263

tests/unit/test_metrics_tracer.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,7 @@ def metrics_tracer():
3030
mock_operation_counter = mock.create_autospec(Counter, instance=True)
3131
mock_operation_latency = mock.create_autospec(Histogram, instance=True)
3232
return MetricsTracer(
33-
method="test_method",
3433
enabled=True,
35-
is_direct_path_enabled=False,
3634
instrument_attempt_latency=mock_attempt_latency,
3735
instrument_attempt_counter=mock_attempt_counter,
3836
instrument_operation_latency=mock_operation_latency,
@@ -41,11 +39,6 @@ def metrics_tracer():
4139
)
4240

4341

44-
def test_initialization(metrics_tracer):
45-
assert metrics_tracer.method == "test_method"
46-
assert metrics_tracer.enabled is True
47-
48-
4942
def test_record_attempt_start(metrics_tracer):
5043
metrics_tracer.record_attempt_start()
5144
assert metrics_tracer.current_op.current_attempt is not None
@@ -107,11 +100,8 @@ def test_disabled(metrics_tracer):
107100
assert metrics_tracer.instrument_attempt_counter.add.call_count == 0
108101
assert metrics_tracer.instrument_operation_latency.record.call_count == 0
109102
assert metrics_tracer.instrument_operation_counter.add.call_count == 0
110-
111-
assert metrics_tracer._create_otel_attributes() is None
112-
assert metrics_tracer._create_operation_otel_attributes() is None
113-
assert metrics_tracer._create_attempt_otel_attributes() is None
114-
103+
assert not metrics_tracer._create_operation_otel_attributes()
104+
assert not metrics_tracer._create_attempt_otel_attributes()
115105

116106
def test_get_ms_time_diff():
117107
# Create two datetime objects
@@ -144,7 +134,7 @@ def test_get_ms_time_diff_negative():
144134

145135

146136
def test_set_project(metrics_tracer):
147-
# Set from fixture
137+
metrics_tracer.set_project("test_project")
148138
assert metrics_tracer.client_attributes["project_id"] == "test_project"
149139

150140
# Ensure it does not overwrite
@@ -222,3 +212,11 @@ def test_enable_direct_path(metrics_tracer):
222212
# Ensure it does not overwrite
223213
metrics_tracer.enable_direct_path(False)
224214
assert metrics_tracer.client_attributes["directpath_enabled"] == "True"
215+
216+
def test_set_method(metrics_tracer):
217+
metrics_tracer.set_method("test_method")
218+
assert metrics_tracer.client_attributes["method"] == "test_method"
219+
220+
# Ensure it does not overwrite
221+
metrics_tracer.set_method("new_method")
222+
assert metrics_tracer.client_attributes["method"] == "test_method"

tests/unit/test_metrics_tracer_factory.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,8 @@ def test_initialization(metrics_tracer_factory):
4949

5050

5151
def test_create_metrics_tracer(metrics_tracer_factory):
52-
tracer = metrics_tracer_factory.create_metrics_tracer("test_method")
52+
tracer = metrics_tracer_factory.create_metrics_tracer()
5353
assert isinstance(tracer, MetricsTracer)
54-
assert tracer.method == "test_method"
55-
assert tracer.enabled is True
5654

5755

5856
def test_client_attributes(metrics_tracer_factory):

0 commit comments

Comments
 (0)