99
1010from ..shared import constants
1111from ..shared .functions import resolve_env_var_choice
12- from ..shared .lazy_import import LazyLoader
1312from .exceptions import MetricUnitError , MetricValueError , SchemaValidationError
14- from .schema import CLOUDWATCH_EMF_SCHEMA
1513
16- fastjsonschema = LazyLoader ("fastjsonschema" , globals (), "fastjsonschema" )
1714logger = logging .getLogger (__name__ )
1815
1916MAX_METRICS = 100
17+ MAX_DIMENSIONS = 9
2018
2119
2220class MetricUnit (Enum ):
@@ -180,6 +178,12 @@ def serialize_metric_set(self, metrics: Dict = None, dimensions: Dict = None, me
180178 if self .service and not self .dimension_set .get ("service" ):
181179 self .dimension_set ["service" ] = self .service
182180
181+ if len (metrics ) == 0 :
182+ raise SchemaValidationError ("Must contain at least one metric." )
183+
184+ if self .namespace is None :
185+ raise SchemaValidationError ("Must contain a metric namespace." )
186+
183187 logger .debug ({"details" : "Serializing metrics" , "metrics" : metrics , "dimensions" : dimensions })
184188
185189 metric_names_and_units : List [Dict [str , str ]] = [] # [ { "Name": "metric_name", "Unit": "Count" } ]
@@ -209,12 +213,6 @@ def serialize_metric_set(self, metrics: Dict = None, dimensions: Dict = None, me
209213 ** metric_names_and_values , # "single_metric": 1.0
210214 }
211215
212- try :
213- logger .debug ("Validating serialized metrics against CloudWatch EMF schema" )
214- fastjsonschema .validate (definition = CLOUDWATCH_EMF_SCHEMA , data = embedded_metrics_object )
215- except fastjsonschema .JsonSchemaException as e :
216- message = f"Invalid format. Error: { e .message } , Invalid item: { e .name } " # noqa: B306, E501
217- raise SchemaValidationError (message )
218216 return embedded_metrics_object
219217
220218 def add_dimension (self , name : str , value : str ):
@@ -234,7 +232,10 @@ def add_dimension(self, name: str, value: str):
234232 Dimension value
235233 """
236234 logger .debug (f"Adding dimension: { name } :{ value } " )
237-
235+ if len (self .dimension_set ) == 9 :
236+ raise SchemaValidationError (
237+ f"Maximum number of dimensions exceeded ({ MAX_DIMENSIONS } ): Unable to add dimension { name } ."
238+ )
238239 # Cast value to str according to EMF spec
239240 # Majority of values are expected to be string already, so
240241 # checking before casting improves performance in most cases
@@ -295,7 +296,7 @@ def __extract_metric_unit_value(self, unit: Union[str, MetricUnit]) -> str:
295296 if unit in self ._metric_unit_options :
296297 unit = MetricUnit [unit ].value
297298
298- if unit not in self ._metric_units : # str correta
299+ if unit not in self ._metric_units :
299300 raise MetricUnitError (
300301 f"Invalid metric unit '{ unit } ', expected either option: { self ._metric_unit_options } "
301302 )
0 commit comments