from __future__ import annotations import json import math from typing import Callable ErrorFactory = Callable[[str], Exception] SUPPORTED_OPERATORS = {"contains", "eq", "exists", "gt", "gte", "in", "lt", "lte", "missing", "ne"} def parse_sample_percent(value: object, label: str, error_factory: ErrorFactory) -> float: if isinstance(value, bool): raise error_factory(f"{label} must be numeric") try: sample_percent = float(value) except (TypeError, ValueError) as err: raise error_factory(f"{label} must be numeric") from err if not math.isfinite(sample_percent): raise error_factory(f"{label} must be finite") if sample_percent <= 0 or sample_percent > 100: raise error_factory(f"{label} must be in the range (0, 100]") return sample_percent def normalize_sampling_rules_json( value: str, *, error_factory: ErrorFactory = RuntimeError, label: str = "SAMPLING_RULES_JSON", ) -> str: raw = str(value or "").strip() if not raw: raise error_factory(f"{label} is required") try: rules = json.loads(raw) except json.JSONDecodeError as err: raise error_factory(f"{label} must be valid JSON: {err}") from err if not isinstance(rules, list) or not rules: raise error_factory(f"{label} must be a non-empty JSON array") rule_ids: set[str] = set() for index, rule in enumerate(rules): if not isinstance(rule, dict): raise error_factory(f"{label}[{index}] must be an object") for key in ("id", "field", "operator", "value", "samplePercent"): if key not in rule: raise error_factory(f"{label}[{index}].{key} is required") rule_id = str(rule.get("id", "")).strip() field_path = str(rule.get("field", "")).strip() operator = str(rule.get("operator", "")).strip() if not rule_id: raise error_factory(f"{label}[{index}].id must be non-empty") if rule_id in rule_ids: raise error_factory(f"{label} contains duplicate id: {rule_id}") rule_ids.add(rule_id) if not field_path: raise error_factory(f"{label}[{index}].field must be non-empty") if operator not in SUPPORTED_OPERATORS: raise error_factory(f"{label}[{index}].operator must be one of {', '.join(sorted(SUPPORTED_OPERATORS))}") parse_sample_percent(rule.get("samplePercent"), f"{label}[{index}].samplePercent", error_factory) return json.dumps(rules, ensure_ascii=False)