|
3 | 3 | import datetime |
4 | 4 | from app.schemas import MetricsSchema |
5 | 5 | from types import SimpleNamespace |
| 6 | +import re |
6 | 7 |
|
7 | 8 | PRODUCT_BASE_URL = os.getenv('PRODUCT_BASE_URL') |
8 | 9 | PROJECT_ENDPOINT = f"{PRODUCT_BASE_URL}/projects" |
@@ -106,3 +107,46 @@ def get_app_data(request): |
106 | 107 | namespace=project_data.namespace, |
107 | 108 | status_code=200 |
108 | 109 | ) |
| 110 | + |
| 111 | + |
| 112 | + |
| 113 | +# default mx data points for prometheus |
| 114 | +MAX_DATA_POINTS = 11000 |
| 115 | +STEP_UNITS_IN_SECONDS = { |
| 116 | + "s": 1, |
| 117 | + "m": 60, |
| 118 | + "h": 3600, |
| 119 | + "d": 86400, |
| 120 | + "w": 604800, |
| 121 | +} |
| 122 | + |
| 123 | +def parse_step_to_seconds(step: str) -> int: |
| 124 | + """ |
| 125 | + Parses a Prometheus step string like '1m', '2h', '4d' into seconds. |
| 126 | + """ |
| 127 | + match = re.match(r"^(\d+)([smhdw])$", step) |
| 128 | + if not match: |
| 129 | + raise ValueError("Invalid step format. Use formats like 30s, 5m, 2h, 1d.") |
| 130 | + value, unit = match.groups() |
| 131 | + return int(value) * STEP_UNITS_IN_SECONDS[unit] |
| 132 | + |
| 133 | +def is_valid_prometheus_query(step: str, start_ts: int, end_ts: int) -> (bool, str): |
| 134 | + """ |
| 135 | + Validates if the number of points in a Prometheus query is within the allowed range. |
| 136 | + """ |
| 137 | + try: |
| 138 | + step_seconds = parse_step_to_seconds(step) |
| 139 | + except ValueError as e: |
| 140 | + return False, str(e) |
| 141 | + |
| 142 | + if start_ts >= end_ts: |
| 143 | + return False, "Start timestamp must be less than end timestamp." |
| 144 | + |
| 145 | + total_duration = end_ts - start_ts |
| 146 | + num_points = total_duration // step_seconds |
| 147 | + |
| 148 | + if num_points > MAX_DATA_POINTS: |
| 149 | + return False, f"Query returns {num_points} points, which exceeds the limit of {MAX_DATA_POINTS}. Increase the step or reduce the time range." |
| 150 | + |
| 151 | + return True, f"Query valid: {num_points} data points." |
| 152 | + |
0 commit comments