66
77from ai .backend .common .exception import InvalidMetricPresetTemplate
88
9- __all__ = ("validate_query_template" ,)
9+ __all__ = (
10+ "PLACEHOLDER_NAMES" ,
11+ "escape_non_placeholders" ,
12+ "validate_query_template" ,
13+ )
14+
15+ PLACEHOLDER_NAMES = frozenset ({"labels" , "window" , "group_by" })
1016
11- _PLACEHOLDER_NAMES = frozenset ({"labels" , "window" , "group_by" })
1217_BRACE_BLOCK_RE = re .compile (r"\{([^{}]*)\}" )
1318_UNSUPPORTED_TEMPLATE_VAR_RE = re .compile (r"\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*" )
1419
1520
16- def _escape_non_placeholders (template : str ) -> str :
21+ def escape_non_placeholders (template : str ) -> str :
22+ """Normalize each ``{X}`` so ``str.format`` produces a single PromQL ``{value}``
23+ regardless of how many braces the user wrote.
24+ """
25+
1726 def repl (match : re .Match [str ]) -> str :
1827 name = match .group (1 )
1928 start , end = match .span ()
2029 text = match .string
2130 already_wrapped = (
2231 start > 0 and text [start - 1 ] == "{" and end < len (text ) and text [end ] == "}"
2332 )
24- if name not in _PLACEHOLDER_NAMES :
33+ if name not in PLACEHOLDER_NAMES :
2534 return match .group (0 ) if already_wrapped else "{{" + name + "}}"
2635 if name != "labels" :
2736 return match .group (0 )
@@ -36,13 +45,13 @@ def validate_query_template(template: str) -> str:
3645 raise InvalidMetricPresetTemplate ("Template must not be empty." )
3746 unsupported_vars = _UNSUPPORTED_TEMPLATE_VAR_RE .findall (template )
3847 if unsupported_vars :
39- placeholders = ", " .join (f"{{{ name } }}" for name in sorted (_PLACEHOLDER_NAMES ))
48+ placeholders = ", " .join (f"{{{ name } }}" for name in sorted (PLACEHOLDER_NAMES ))
4049 raise InvalidMetricPresetTemplate (
4150 f"Unsupported template variables: { unsupported_vars } . "
4251 f"Use placeholders { placeholders } or literal PromQL values."
4352 )
4453 try :
45- _escape_non_placeholders (template ).format (labels = "" , window = "" , group_by = "" )
54+ escape_non_placeholders (template ).format (labels = "" , window = "" , group_by = "" )
4655 except (ValueError , KeyError , IndexError ) as e :
4756 raise InvalidMetricPresetTemplate (
4857 f"Failed to render PromQL template ({ type (e ).__name__ } : { e } ): { template !r} "
0 commit comments