# -*- coding: utf-8 -*- """**动作引用**(`action_ref`):任务/计划里"引用"动作库里的一个组合,而不是把步骤拷进去。 用户 2026-10-17 的要求:**"如果有计划或者调度任务使用了某一个组合,删除之前一定要提示操作者, 删除后会影响所有的任务或计划"** —— 而在这之前,把自定义动作拖进画布是把它的 steps **深拷贝展开**成一个 `group` 步骤(`static/admin/editor.js`),**一个 action_id 都不落地**, 所以"谁在用这个组合"**根本查不出来**。 有了引用之后: | 场景 | 行为 | |---|---| | 改组合 | 所有引用它的任务/计划**同步生效**(执行时**现展开**,不用重发任务) | | 删组合 | **先列出到底影响谁**(`usage_scan`),有精确引用 → 拒绝(要删得显式 `force`) | | 组合被删了 | 运行时**明确报错**(不静默跳过),步骤明细里写清"引用的动作已被删除" | | 循环引用 | A→B→A:`_exec_action_ref` 用引用栈挡住 + 引擎本来的 `depth>5` 护栏,报错不递归 | **执行时现读库**(`load_steps`,带 10 秒小缓存)—— 走的就是本模块自己的 app context, 和 `core/video_plan.py` 里 worker 线程读库的写法一样(worker 线程没有请求上下文)。 """ import json import time from core.logger import get_logger _log = get_logger("core.action_ref") _app = None _CACHE = {} # action_id -> (读到的时刻, steps) _TTL = 10.0 # 秒:同一条动作在一次运行里会被反复取(内容循环),别每步都查库 _MAX_DEPTH = 8 # 展平引用时最多跟几层(防 A→B→C→… 的链式轰炸) def init_app(app): """web_server 启动时调用:绑 app(worker 线程里读库要自推 context)。""" global _app _app = app def _ctx(): if _app is None: raise RuntimeError("action_ref 未关联 Flask app(web_server 启动时调用 init_app)") return _app.app_context() def invalidate(action_id=""): """清缓存(动作被改/删时调;`action_id` 空 = 全清)。""" if action_id: _CACHE.pop(action_id, None) else: _CACHE.clear() def load_steps(action_id, use_cache=True): """取这条动作的步骤(**现读库**)。没有这条动作 / 没有步骤 → `None`。""" aid = (action_id or "").strip() if not aid: return None now = time.time() if use_cache: hit = _CACHE.get(aid) if hit and now - hit[0] < _TTL: return hit[1] steps = None try: from core.models import CustomAction with _ctx(): row = CustomAction.query.get(aid) if row is not None: steps = row.get_steps() or None except Exception as e: _log.warning("读动作引用 %s 失败:%s", aid, e) return None if steps is not None: _CACHE[aid] = (now, steps) return steps # ==================== 引用扫描("删之前先看看影响了谁")==================== def find_refs(steps): """在一串步骤里**递归**找动作引用。返回 `[{"action_id", "path"}, …]`。 path 是人能看懂的路径(如 `steps[0].params.children[2]`),页面直接显示给用户定位。 """ out = [] def walk(arr, path): if not isinstance(arr, list): return for i, s in enumerate(arr): if not isinstance(s, dict): continue here = "%s[%d]" % (path, i) p = s.get("params") or {} if s.get("type") == "action_ref" and (p.get("action_id") or "").strip(): out.append({"action_id": p["action_id"].strip(), "path": here}) for key in ("children", "then", "else"): if isinstance(p.get(key), list): walk(p[key], here + ".params." + key) walk(steps or [], "steps") return out def _label_group_refs(steps, label): """**老任务**里"展开副本"的痕迹:拖入时生成的是 `group` 步骤、label = 动作名。""" n = 0 def walk(arr): nonlocal n if not isinstance(arr, list): return for s in arr: if not isinstance(s, dict): continue p = s.get("params") or {} if s.get("type") == "group" and (s.get("label") or "").strip() == label: n += 1 for key in ("children", "then", "else"): if isinstance(p.get(key), list): walk(p[key]) walk(steps) return n def usage_scan(action_id): """**谁在用这条动作** —— 删之前必须能回答这个问题。 返回: ``` {"exact": {"tasks": [{"id","name","path"}], "actions": [...], "plans": [...]}, "legacy_guess": {"tasks": [{"id","name","hits"}]}, # 老任务里"展开副本",按名字猜的 "total_exact": 3} ``` 精确来源三处:`task_job.params.steps`(递归找 `action_ref`)、**别的动作**的 steps (组合引用组合)、**计划**的 `action_id`/`prep_action_id`。 """ from core.models import db, TaskJob, CustomAction, AePlan aid = (action_id or "").strip() exact = {"tasks": [], "actions": [], "plans": []} guess = {"tasks": []} with _ctx(): row = CustomAction.query.get(aid) label = (row.name if row is not None else "") or "" for j in TaskJob.query.all(): p = j.get_params() # ⚠ `TaskJob.params` 在模型上是**JSON 文本**, for r in find_refs(p.get("steps")): # 一定要走 get_params() 才是 dict if r["action_id"] == aid: exact["tasks"].append({"id": j.id, "name": j.name or "", "path": r["path"]}) if label and _label_group_refs(p.get("steps"), label): guess["tasks"].append({"id": j.id, "name": j.name or "", "hits": _label_group_refs(p.get("steps"), label)}) for a in CustomAction.query.all(): if a.id == aid: continue for r in find_refs(a.get_steps()): if r["action_id"] == aid: exact["actions"].append({"id": a.id, "name": a.name or "", "path": r["path"]}) for pl in AePlan.query.all(): for f in ("action_id", "prep_action_id"): if (getattr(pl, f) or "").strip() == aid: exact["plans"].append({"id": pl.id, "name": pl.name or "", "field": f}) # 动作编排(segments)里的每一段都是引用 —— 删组合前必须算进来 try: segs = pl.get_json("segments", []) or [] except Exception: segs = [] for i, s in enumerate(segs): if isinstance(s, dict) and (s.get("action_id") or "").strip() == aid: exact["plans"].append({"id": pl.id, "name": pl.name or "", "field": "segments[%d]" % i}) total = sum(len(v) for v in exact.values()) return {"exact": exact, "legacy_guess": guess, "total_exact": total} def usage_summary(usage): """一句人话(通知/弹窗标题用)。""" e = (usage or {}).get("exact") or {} n_t, n_a, n_p = len(e.get("tasks") or []), len(e.get("actions") or []), len(e.get("plans") or []) if not (n_t or n_a or n_p): g = len(((usage or {}).get("legacy_guess") or {}).get("tasks") or []) return "没有精确引用" + (";%d 个老任务里可能是它的展开副本(按名字猜的)" % g if g else "") return "被 %d 个任务、%d 个动作、%d 个计划引用" % (n_t, n_a, n_p) def can_delete(action_id): """**能不能删**(删除接口与前端共用这一处判断)。 规则(用户定的): · `kind=builtin`(代码播种的内置件)→ **不能删**(可复制来改); · 标了 **★ 标准件**(`starred`)→ 要先**取消标记**才能删(防手滑删掉常用件); · 有**精确引用** → 不能直接删,返回 409 让页面列出"影响谁";确实要删得显式 `force=1`; · 只有"老任务里疑似展开副本" → **允许删**,但把清单带回去让页面提示。 返回 `{"ok":bool, "code":int|None, "error":str, "usage":{...}, "action":{...}}`。 """ from core.models import CustomAction aid = (action_id or "").strip() with _ctx(): row = CustomAction.query.get(aid) if row is None: return {"ok": False, "code": 404, "error": "动作不存在", "usage": {}} d = row.to_dict() usage = usage_scan(aid) if (d.get("kind") or "") == "builtin": return {"ok": False, "code": 400, "usage": usage, "action": d, "error": "『%s』是**内置动作**,不能删(可以「复制」一份再改)" % (d.get("name") or aid)} if d.get("starred"): return {"ok": False, "code": 400, "usage": usage, "action": d, "error": "『%s』是**标准件**(★)—— 要删请先取消标准标记" % (d.get("name") or aid)} if usage["total_exact"]: return {"ok": False, "code": 409, "usage": usage, "action": d, "error": "『%s』%s —— 删掉后这些任务/计划运行时**会直接报错**" % (d.get("name") or aid, usage_summary(usage))} return {"ok": True, "code": None, "error": "", "usage": usage, "action": d} # ==================== 编辑器用:把引用摊平成步骤("转为快照展开")==================== def flatten(steps, _seen=None, _depth=0): """把步骤树里的 `action_ref` **摊平**成真实的 group 副本("转为快照展开"用)。 ⚠ 展开后**与动作库脱钩**(改组合不再影响它)—— 这是给"我就要改这一处"的逃生口。 循环引用/超深 → 保留原节点不动(宁可让它运行时报错,也别在这里无限递归)。 """ _seen = _seen or set() if _depth > _MAX_DEPTH: return steps out = [] for s in (steps or []): if not isinstance(s, dict): continue if s.get("type") == "action_ref": aid = ((s.get("params") or {}).get("action_id") or "").strip() sub = load_steps(aid) if aid and aid not in _seen else None if not sub: out.append(s) # 取不到就原样留着(运行时明确报错) continue _seen.add(aid) out.append({"type": "group", "label": s.get("label") or aid, "icon": s.get("icon") or "📦", "params": {"children": flatten(sub, _seen, _depth + 1)}}) _seen.discard(aid) continue s = json.loads(json.dumps(s, ensure_ascii=False)) p = s.get("params") or {} for key in ("children", "then", "else"): if isinstance(p.get(key), list): p[key] = flatten(p[key], _seen, _depth + 1) out.append(s) return out