Skip to content

Commit ce02bf3

Browse files
authored
chore: Add type to metrics code and deprecate CWMetricsPublisher (#3025)
1 parent 2787cc1 commit ce02bf3

File tree

4 files changed

+51
-12
lines changed

4 files changed

+51
-12
lines changed

samtranslator/internal/deprecation_control.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ def _make_message(message: str, replacement: Optional[str]) -> str:
2323
return f"{message}, please use {replacement}" if replacement else message
2424

2525

26-
def deprecated(replacement: Optional[str]) -> Callable[[Callable[PT, RT]], Callable[PT, RT]]:
26+
# TODO: make @deprecated able to decorate a class
27+
28+
29+
def deprecated(replacement: Optional[str] = None) -> Callable[[Callable[PT, RT]], Callable[PT, RT]]:
2730
"""
2831
Mark a function/method as deprecated.
2932

samtranslator/metrics/method_decorator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def _send_cw_metric(prefix, name, execution_time_ms, func, args): # type: ignor
7676
try:
7777
metric_name = _get_metric_name(prefix, name, func, args) # type: ignore[no-untyped-call]
7878
LOG.debug("Execution took %sms for %s", execution_time_ms, metric_name)
79-
MetricsMethodWrapperSingleton.get_instance().record_latency(metric_name, execution_time_ms) # type: ignore[no-untyped-call]
79+
MetricsMethodWrapperSingleton.get_instance().record_latency(metric_name, execution_time_ms)
8080
except Exception as e:
8181
LOG.warning("Failed to add metrics", exc_info=e)
8282

samtranslator/metrics/metrics.py

Lines changed: 45 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44
import logging
55
from abc import ABC, abstractmethod
66
from datetime import datetime
7-
from typing import Any, Dict, List, Optional
7+
from typing import Any, Dict, List, Optional, Union
8+
9+
from typing_extensions import TypedDict
10+
11+
from samtranslator.internal.deprecation_control import deprecated
812

913
LOG = logging.getLogger(__name__)
1014

@@ -25,6 +29,7 @@ def publish(self, namespace: str, metrics: List["MetricDatum"]) -> None:
2529
class CWMetricsPublisher(MetricsPublisher):
2630
BATCH_SIZE = 20
2731

32+
@deprecated()
2833
def __init__(self, cloudwatch_client) -> None: # type: ignore[no-untyped-def]
2934
"""
3035
Constructor
@@ -66,7 +71,7 @@ class DummyMetricsPublisher(MetricsPublisher):
6671
def __init__(self) -> None:
6772
MetricsPublisher.__init__(self)
6873

69-
def publish(self, namespace, metrics): # type: ignore[no-untyped-def]
74+
def publish(self, namespace: str, metrics: List["MetricDatum"]) -> None:
7075
"""Do not publish any metric, this is a dummy publisher used for offline use."""
7176
LOG.debug(f"Dummy publisher ignoring {len(metrics)} metrices")
7277

@@ -90,7 +95,14 @@ class MetricDatum:
9095
Class to hold Metric data.
9196
"""
9297

93-
def __init__(self, name, value, unit, dimensions=None, timestamp=None) -> None: # type: ignore[no-untyped-def]
98+
def __init__(
99+
self,
100+
name: str,
101+
value: Union[int, float],
102+
unit: str,
103+
dimensions: Optional[List["MetricDimension"]] = None,
104+
timestamp: Optional[datetime] = None,
105+
) -> None:
94106
"""
95107
Constructor
96108
@@ -116,6 +128,11 @@ def get_metric_data(self) -> Dict[str, Any]:
116128
}
117129

118130

131+
class MetricDimension(TypedDict):
132+
Name: str
133+
Value: Any
134+
135+
119136
class Metrics:
120137
def __init__(
121138
self, namespace: str = "ServerlessTransform", metrics_publisher: Optional[MetricsPublisher] = None
@@ -138,7 +155,14 @@ def __del__(self) -> None:
138155
)
139156
self.publish()
140157

141-
def _record_metric(self, name, value, unit, dimensions=None, timestamp=None): # type: ignore[no-untyped-def]
158+
def _record_metric(
159+
self,
160+
name: str,
161+
value: Union[int, float],
162+
unit: str,
163+
dimensions: Optional[List["MetricDimension"]] = None,
164+
timestamp: Optional[datetime] = None,
165+
) -> None:
142166
"""
143167
Create and save metric object in internal cache.
144168
@@ -150,7 +174,13 @@ def _record_metric(self, name, value, unit, dimensions=None, timestamp=None): #
150174
"""
151175
self.metrics_cache.setdefault(name, []).append(MetricDatum(name, value, unit, dimensions, timestamp))
152176

153-
def record_count(self, name, value, dimensions=None, timestamp=None): # type: ignore[no-untyped-def]
177+
def record_count(
178+
self,
179+
name: str,
180+
value: int,
181+
dimensions: Optional[List["MetricDimension"]] = None,
182+
timestamp: Optional[datetime] = None,
183+
) -> None:
154184
"""
155185
Create metric with unit Count.
156186
@@ -160,9 +190,15 @@ def record_count(self, name, value, dimensions=None, timestamp=None): # type: i
160190
:param dimensions: array of dimensions applied to the metric
161191
:param timestamp: timestamp of metric (datetime.datetime object)
162192
"""
163-
self._record_metric(name, value, Unit.Count, dimensions, timestamp) # type: ignore[no-untyped-call]
193+
self._record_metric(name, value, Unit.Count, dimensions, timestamp)
164194

165-
def record_latency(self, name, value, dimensions=None, timestamp=None): # type: ignore[no-untyped-def]
195+
def record_latency(
196+
self,
197+
name: str,
198+
value: Union[int, float],
199+
dimensions: Optional[List["MetricDimension"]] = None,
200+
timestamp: Optional[datetime] = None,
201+
) -> None:
166202
"""
167203
Create metric with unit Milliseconds.
168204
@@ -172,7 +208,7 @@ def record_latency(self, name, value, dimensions=None, timestamp=None): # type:
172208
:param dimensions: array of dimensions applied to the metric
173209
:param timestamp: timestamp of metric (datetime.datetime object)
174210
"""
175-
self._record_metric(name, value, Unit.Milliseconds, dimensions, timestamp) # type: ignore[no-untyped-call]
211+
self._record_metric(name, value, Unit.Milliseconds, dimensions, timestamp)
176212

177213
def publish(self) -> None:
178214
"""Calls publish method from the configured metrics publisher to publish metrics"""
@@ -184,7 +220,7 @@ def publish(self) -> None:
184220
self.metrics_publisher.publish(self.namespace, all_metrics)
185221
self.metrics_cache = {}
186222

187-
def get_metric(self, name): # type: ignore[no-untyped-def]
223+
def get_metric(self, name: str) -> List[MetricDatum]:
188224
"""
189225
Returns a list of metrics from the internal cache for a metric name
190226

samtranslator/model/eventsources/pull.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -659,7 +659,7 @@ def get_vpc_permission(self) -> Dict[str, Any]:
659659
}
660660

661661
@staticmethod
662-
@deprecated(None)
662+
@deprecated()
663663
def get_kms_policy(secrets_manager_kms_key_id: str) -> Dict[str, Any]:
664664
return {
665665
"Action": ["kms:Decrypt"],

0 commit comments

Comments
 (0)