|
1 | 1 | from __future__ import annotations
|
2 | 2 |
|
| 3 | +from datetime import datetime, timezone |
| 4 | + |
3 | 5 | from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import (
|
4 | 6 | MetricResolutionError,
|
5 | 7 | MetricUnitError,
|
6 | 8 | )
|
7 | 9 | from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit
|
| 10 | +from aws_lambda_powertools.shared import constants |
8 | 11 | from aws_lambda_powertools.shared.types import List
|
9 | 12 |
|
10 | 13 |
|
@@ -69,3 +72,57 @@ def extract_cloudwatch_metric_unit_value(metric_units: List, metric_valid_option
|
69 | 72 | unit = unit.value
|
70 | 73 |
|
71 | 74 | return unit
|
| 75 | + |
| 76 | + |
| 77 | +def validate_emf_timestamp(timestamp: int | datetime) -> bool: |
| 78 | + """ |
| 79 | + Validates a given timestamp based on CloudWatch Timestamp guidelines. |
| 80 | +
|
| 81 | + Timestamp must meet CloudWatch requirements, otherwise an InvalidTimestampError will be raised. |
| 82 | + See [Timestamps](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#about_timestamp) |
| 83 | + for valid values. |
| 84 | +
|
| 85 | + Parameters: |
| 86 | + ---------- |
| 87 | + timestamp: int | datetime |
| 88 | + Datetime object or epoch time representing the timestamp to validate. |
| 89 | +
|
| 90 | + Returns |
| 91 | + ------- |
| 92 | + bool |
| 93 | + Valid or not timestamp values |
| 94 | + """ |
| 95 | + |
| 96 | + if not isinstance(timestamp, (int, datetime)): |
| 97 | + return False |
| 98 | + |
| 99 | + if isinstance(timestamp, datetime): |
| 100 | + # Assuming the integer timestamp represents seconds since the epoch |
| 101 | + timestamp = int(timestamp.timestamp() * 1000) |
| 102 | + |
| 103 | + current_time = int(datetime.now(timezone.utc).timestamp() * 1000) |
| 104 | + min_valid_timestamp = current_time - constants.EMF_MAX_TIMESTAMP_PAST_AGE |
| 105 | + max_valid_timestamp = current_time + constants.EMF_MAX_TIMESTAMP_FUTURE_AGE |
| 106 | + |
| 107 | + return min_valid_timestamp <= timestamp <= max_valid_timestamp |
| 108 | + |
| 109 | + |
| 110 | +def convert_timestamp_to_emf_format(timestamp: int | datetime) -> int: |
| 111 | + """ |
| 112 | + Converts a timestamp to EMF compatible format. |
| 113 | +
|
| 114 | + Parameters |
| 115 | + ---------- |
| 116 | + timestamp: int | datetime |
| 117 | + The timestamp to convert. If already in milliseconds format, returns it as is. |
| 118 | + If datetime object, converts it to milliseconds since Unix epoch. |
| 119 | +
|
| 120 | + Returns: |
| 121 | + -------- |
| 122 | + int |
| 123 | + The timestamp converted to EMF compatible format (milliseconds since Unix epoch). |
| 124 | + """ |
| 125 | + if isinstance(timestamp, int): |
| 126 | + return timestamp |
| 127 | + |
| 128 | + return int(round(timestamp.timestamp() * 1000)) |
0 commit comments