rules.py 8.41 KB
"""规则表达式:安全求值。

口径、判定、SOP 分支条件、Action 前置校验共用这一套。语法是 Python 表达式的子集:
算术、比较、and/or/not、条件表达式、`a.b` 取字段、`a[0]` 下标、白名单函数。
不支持赋值、lambda、推导式、任意属性/方法调用 —— 规则由业务人员录入、也可能由 AI 起草,
绝不能是一个能执行任意代码的口子。
"""
from __future__ import annotations

import ast
import datetime as dt
import math
from typing import Any


class RuleError(ValueError):
    pass


def _to_date(v: Any) -> dt.date:
    if isinstance(v, dt.datetime):
        return v.date()
    if isinstance(v, dt.date):
        return v
    return dt.date.fromisoformat(str(v)[:10])


def _coalesce(*xs: Any) -> Any:
    for x in xs:
        if x is not None and x != "":
            return x
    return None


def _safe_div(a: Any, b: Any, default: Any = None) -> Any:
    try:
        return a / b if b else default
    except Exception:  # noqa: BLE001
        return default


FUNCS: dict[str, Any] = {
    "min": min, "max": max, "abs": abs, "round": round, "len": len, "sum": sum,
    "int": int, "float": float, "str": str, "bool": bool,
    "floor": math.floor, "ceil": math.ceil,
    "coalesce": _coalesce, "safe_div": _safe_div,
    "today": lambda: dt.date.today().isoformat(),
    "date": lambda v: _to_date(v).isoformat(),
    "day": lambda v: _to_date(v).day,
    "month": lambda v: _to_date(v).month,
    "year": lambda v: _to_date(v).year,
    "days_between": lambda a, b: (_to_date(b) - _to_date(a)).days,
    "contains": lambda a, b: (b in a) if a is not None else False,
    "startswith": lambda a, b: str(a or "").startswith(str(b)),
}

CONSTS = {"true": True, "false": False, "null": None, "True": True, "False": False, "None": None}

_BIN = {
    ast.Add: lambda a, b: a + b, ast.Sub: lambda a, b: a - b, ast.Mult: lambda a, b: a * b,
    ast.Div: lambda a, b: a / b, ast.FloorDiv: lambda a, b: a // b,
    ast.Mod: lambda a, b: a % b, ast.Pow: lambda a, b: a ** b,
}
_CMP = {
    ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b, ast.Lt: lambda a, b: a < b,
    ast.LtE: lambda a, b: a <= b, ast.Gt: lambda a, b: a > b, ast.GtE: lambda a, b: a >= b,
    ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b,
    ast.Is: lambda a, b: a is b, ast.IsNot: lambda a, b: a is not b,
}
_ALLOWED = (ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare, ast.IfExp,
            ast.Call, ast.Constant, ast.Name, ast.Load, ast.Attribute, ast.Subscript,
            ast.List, ast.Tuple, ast.Dict, ast.And, ast.Or, ast.Not, ast.USub, ast.UAdd,
            ast.Slice, *_BIN.keys(), *_CMP.keys())


def _prep(expr: str) -> str:
    # 业务人员常写中文标点与 && ||,这里宽容一下
    return (expr.replace("(", "(").replace(")", ")").replace(",", ",")
            .replace("≥", ">=").replace("≤", "<=").replace("≠", "!=")
            .replace("&&", " and ").replace("||", " or ").strip())


def parse(expr: str) -> ast.Expression:
    if not expr or not expr.strip():
        raise RuleError("表达式为空")
    if len(expr) > 2000:
        raise RuleError("表达式过长")
    try:
        tree = ast.parse(_prep(expr), mode="eval")
    except SyntaxError as e:
        raise RuleError(f"语法错误:{e.msg}") from e
    for node in ast.walk(tree):
        if not isinstance(node, _ALLOWED):
            raise RuleError(f"不允许的语法:{type(node).__name__}")
        if isinstance(node, ast.Call):
            if not isinstance(node.func, ast.Name) or node.func.id not in FUNCS:
                raise RuleError("只能调用白名单函数:" + "、".join(sorted(FUNCS)))
            if node.keywords:
                raise RuleError("函数不支持关键字参数")
        if isinstance(node, ast.Attribute) and node.attr.startswith("_"):
            raise RuleError("不允许访问下划线开头的字段")
    return tree


def free_names(expr: str) -> list[str]:
    """表达式里引用的顶层变量名(不含函数名与常量),按出现顺序去重。"""
    tree = parse(expr)
    out: list[str] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Name) and node.id not in FUNCS and node.id not in CONSTS:
            if node.id not in out:
                out.append(node.id)
    return out


def _get(obj: Any, key: Any) -> Any:
    if isinstance(obj, dict):
        return obj.get(key)
    if isinstance(obj, (list, tuple, str)) and isinstance(key, (int, slice)):
        try:
            return obj[key]
        except IndexError:
            return None
    return None


def _num(v: Any) -> Any:
    """数据库回来的数常是 Decimal / 字符串,比较前尽量转成数。"""
    if isinstance(v, bool) or v is None:
        return v
    if isinstance(v, (int, float)):
        return v
    try:
        from decimal import Decimal
        if isinstance(v, Decimal):
            return float(v)
    except Exception:  # noqa: BLE001
        pass
    if isinstance(v, str):
        s = v.strip().rstrip("%")
        try:
            return float(s) if "." in s or "e" in s.lower() else int(s)
        except ValueError:
            return v
    return v


def _ev(node: ast.AST, env: dict) -> Any:
    if isinstance(node, ast.Expression):
        return _ev(node.body, env)
    if isinstance(node, ast.Constant):
        return node.value
    if isinstance(node, ast.Name):
        if node.id in CONSTS:
            return CONSTS[node.id]
        if node.id not in env:
            raise RuleError(f"缺少变量:{node.id}")
        return env[node.id]
    if isinstance(node, ast.Attribute):
        return _get(_ev(node.value, env), node.attr)
    if isinstance(node, ast.Subscript):
        return _get(_ev(node.value, env), _ev(node.slice, env))
    if isinstance(node, ast.List):
        return [_ev(x, env) for x in node.elts]
    if isinstance(node, ast.Tuple):
        return tuple(_ev(x, env) for x in node.elts)
    if isinstance(node, ast.Dict):
        return {_ev(k, env): _ev(v, env) for k, v in zip(node.keys, node.values) if k is not None}
    if isinstance(node, ast.BoolOp):
        if isinstance(node.op, ast.And):
            val: Any = True
            for x in node.values:
                val = _ev(x, env)
                if not val:
                    return val
            return val
        val = False
        for x in node.values:
            val = _ev(x, env)
            if val:
                return val
        return val
    if isinstance(node, ast.UnaryOp):
        v = _ev(node.operand, env)
        if isinstance(node.op, ast.Not):
            return not v
        v = _num(v)
        return -v if isinstance(node.op, ast.USub) else +v
    if isinstance(node, ast.BinOp):
        a, b = _num(_ev(node.left, env)), _num(_ev(node.right, env))
        if isinstance(node.op, ast.Pow) and isinstance(b, (int, float)) and abs(b) > 100:
            raise RuleError("指数过大")
        try:
            return _BIN[type(node.op)](a, b)
        except ZeroDivisionError:
            return None
        except TypeError as e:
            raise RuleError(f"运算类型不匹配:{e}") from e
    if isinstance(node, ast.Compare):
        left = _num(_ev(node.left, env))
        for op, comp in zip(node.ops, node.comparators):
            right = _num(_ev(comp, env))
            try:
                ok = _CMP[type(op)](left, right)
            except TypeError:
                ok = False     # None 与数比较一律视为不成立,而不是让整个流程崩掉
            if not ok:
                return False
            left = right
        return True
    if isinstance(node, ast.IfExp):
        return _ev(node.body, env) if _ev(node.test, env) else _ev(node.orelse, env)
    if isinstance(node, ast.Call):
        fn = FUNCS[node.func.id]  # type: ignore[attr-defined]
        args = [_ev(a, env) for a in node.args]
        if node.func.id not in ("str", "len", "contains", "startswith", "coalesce", "date",  # type: ignore[attr-defined]
                                "day", "month", "year", "days_between", "today"):
            args = [_num(a) for a in args]
        try:
            return fn(*args)
        except Exception as e:  # noqa: BLE001
            raise RuleError(f"函数 {node.func.id} 调用失败:{e}") from e  # type: ignore[attr-defined]
    raise RuleError(f"不支持的语法:{type(node).__name__}")


def evaluate(expr: str, env: dict | None = None) -> Any:
    return _ev(parse(expr), dict(env or {}))