droboticflow/scripts/lib/sampling_rules.py
2026-06-16 22:41:09 +08:00

52 lines
2.2 KiB
Python

from __future__ import annotations
import json
from typing import Callable
ErrorFactory = Callable[[str], Exception]
SUPPORTED_OPERATORS = {"contains", "eq", "exists", "gt", "gte", "in", "lt", "lte", "missing", "ne"}
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))}")
try:
sample_percent = float(rule.get("samplePercent"))
except (TypeError, ValueError) as err:
raise error_factory(f"{label}[{index}].samplePercent must be numeric") from err
if sample_percent <= 0 or sample_percent > 100:
raise error_factory(f"{label}[{index}].samplePercent must be in the range (0, 100]")
return json.dumps(rules, ensure_ascii=False)