FlowExecutor.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Xml.Linq;
  9. using TeamAAS.FlowEditor.Models;
  10. using TeamAAS.FlowEditor.Plugins;
  11. using TeamAAS.FlowEngine;
  12. namespace TeamAAS.FlowEditor.Execution
  13. {
  14. /// <summary>
  15. /// 流程执行引擎 - 并行任务流模型
  16. /// 1. 无输入连线的节点是任务起点,每个作为独立线程启动
  17. /// 2. 每个节点等待所有前驱节点完成后再运行(IF判断除外)
  18. /// 3. 节点完成后,启动后继节点为独立线程(fire-and-forget),自身立即返回
  19. /// 4. Decision 节点只启动匹配分支的后继
  20. /// 5. 主线程通过计数器等待所有节点完成
  21. /// </summary>
  22. /// <summary>
  23. /// 执行一个 <see cref="FlowGraph"/>。
  24. ///
  25. /// 执行器只负责调度节点、维护节点状态和发布结果;具体业务动作由流程节点插件实现。
  26. /// 这样可以在不改变流程图数据结构的情况下扩展新的硬件或业务节点。
  27. /// </summary>
  28. public class FlowExecutor
  29. {
  30. private readonly FlowGraph _graph;
  31. private CancellationToken _token;
  32. /// <summary>已启动的节点ID集合(防止多前驱重复启动同一后继)</summary>
  33. private readonly HashSet<string> _startedNodes = new HashSet<string>();
  34. private readonly object _startLock = new object();
  35. /// <summary>正在运行的节点计数(主线程等待此计数归零)</summary>
  36. private int _pendingCount = 0;
  37. private readonly object _pendingLock = new object();
  38. /// <summary>所有已启动的节点任务(StartNode / TryStartExceptionBranchQueue / SkipNode 的 Task.Run 收集于此,供 ExecuteCoreAsync 等待)</summary>
  39. private readonly System.Collections.Concurrent.ConcurrentBag<Task> _nodeTasks = new System.Collections.Concurrent.ConcurrentBag<Task>();
  40. /// <summary>单节点模式:不启动后继节点</summary>
  41. private bool _singleNodeMode = false;
  42. /// <summary>跳过前驱等待的节点(用于从指定节点开始运行)</summary>
  43. private readonly HashSet<string> _skipPredecessorNodes = new HashSet<string>();
  44. public bool IsRunning { get; private set; }
  45. public event Action<FlowNode> NodeStatusChanged;
  46. public event Action<bool> ExecutionCompleted;
  47. public event Action EndNodeEncountered;
  48. public bool SkipReset { get; set; }
  49. public FlowExecutor(FlowGraph graph)
  50. {
  51. _graph = graph;
  52. // 反序列化(BinaryFormatter 跳过字段初始化)可能导致 Registry 为 null,兜底绑定 Debug 注册表
  53. if (_graph.Registry == null) _graph.Registry = ResultRegistry.Debug;
  54. }
  55. /// <summary>
  56. /// 异步执行整个流程图
  57. /// </summary>
  58. public async Task ExecuteAsync(CancellationToken token = default)
  59. {
  60. _singleNodeMode = false;
  61. // 空流程:没有任何节点可执行,直接完成(不进入等待循环,避免后续循环运行模式 CPU 满载)
  62. if (_graph.Nodes.Count == 0)
  63. {
  64. IsRunning = true;
  65. IsRunning = false;
  66. Application.Current?.Dispatcher.Invoke(() =>
  67. {
  68. ExecutionCompleted?.Invoke(true);
  69. });
  70. return;
  71. }
  72. await ExecuteCoreAsync(() =>
  73. {
  74. var rootNodes = GetRootNodes();
  75. if (rootNodes.Count == 0 && _graph.Nodes.Count > 0)
  76. rootNodes = _graph.Nodes.ToList();
  77. foreach (var root in rootNodes)
  78. StartNode(root);
  79. }, token);
  80. }
  81. /// <summary>
  82. /// 从指定节点开始执行(向下流转)
  83. /// </summary>
  84. public async Task ExecuteFromNodeAsync(FlowNode startNode, CancellationToken token = default)
  85. {
  86. _singleNodeMode = false;
  87. _skipPredecessorNodes.Clear();
  88. _skipPredecessorNodes.Add(startNode.NodeId);
  89. await ExecuteCoreAsync(() => StartNode(startNode), token);
  90. }
  91. /// <summary>
  92. /// 仅执行单个节点(不启动后继)
  93. /// </summary>
  94. public async Task ExecuteSingleNodeAsync(FlowNode node, CancellationToken token = default)
  95. {
  96. _singleNodeMode = true;
  97. _skipPredecessorNodes.Clear();
  98. _skipPredecessorNodes.Add(node.NodeId);
  99. await ExecuteCoreAsync(() => StartNode(node), token);
  100. }
  101. private async Task ExecuteCoreAsync(Action startAction, CancellationToken token)
  102. {
  103. _token = token;
  104. _startedNodes.Clear();
  105. _pendingCount = 0;
  106. IsRunning = true;
  107. bool success = true;
  108. await Task.Run(() =>
  109. {
  110. try
  111. {
  112. if (!SkipReset) ResetAllNodes();
  113. startAction();
  114. lock (_pendingLock)
  115. {
  116. while (_pendingCount > 0)
  117. {
  118. if (_token.IsCancellationRequested) break;
  119. Monitor.Wait(_pendingLock, 100);
  120. }
  121. }
  122. }
  123. catch (OperationCanceledException)
  124. {
  125. success = false;
  126. }
  127. catch (Exception)
  128. {
  129. success = false;
  130. }
  131. });
  132. IsRunning = false;
  133. // 兜底:流程结束时强制收尾残留的 Running 状态。
  134. // 即使 RunNodeAsync 的 try/catch 漏网(例如 Thread.Abort、SEH 异常等),
  135. // 也不会让 UI 永久卡在 Running 同时 ExecutionCompleted 已触发。
  136. Application.Current?.Dispatcher.Invoke(() =>
  137. {
  138. foreach (var node in _graph.Nodes)
  139. {
  140. if (node.Status == NodeRunStatus.Running)
  141. {
  142. node.Status = NodeRunStatus.Failed;
  143. node.NotifyStatusChanged();
  144. }
  145. }
  146. ExecutionCompleted?.Invoke(success);
  147. });
  148. }
  149. /// <summary>
  150. /// 启动一个节点为独立线程(fire-and-forget)
  151. /// </summary>
  152. private void StartNode(FlowNode node)
  153. {
  154. // 禁用节点:跳过执行,级联启动后继
  155. if (!node.IsEnabled)
  156. {
  157. SkipNode(node);
  158. return;
  159. }
  160. // 异常分支节点不走常规去重+前驱等待路径,改由独立路径触发(支持排队重入)
  161. if (node.Category == NodeCategory.ExceptionBranch)
  162. {
  163. StartExceptionBranchNode(node);
  164. return;
  165. }
  166. // 去重:多前驱可能同时尝试启动同一后继
  167. lock (_startLock)
  168. {
  169. if (_startedNodes.Contains(node.NodeId)) return;
  170. _startedNodes.Add(node.NodeId);
  171. }
  172. // 计数+1
  173. lock (_pendingLock) { _pendingCount++; }
  174. // 每个节点独立线程运行,不等待;Task 收集到 _nodeTasks 供 ExecuteCoreAsync 统一等待
  175. var nodeTask = Task.Run(async () =>
  176. {
  177. try
  178. {
  179. await RunNodeAsync(node);
  180. }
  181. catch (Exception ex) { AppLogger.Error($"节点任务异常:{node.NodeName} @ 流程 {_graph.GraphName}", ex, nameof(FlowExecutor)); }
  182. finally
  183. {
  184. // 计数-1,通知主线程
  185. lock (_pendingLock)
  186. {
  187. _pendingCount--;
  188. Monitor.Pulse(_pendingLock);
  189. }
  190. }
  191. });
  192. _nodeTasks.Add(nodeTask);
  193. }
  194. /// <summary>
  195. /// 运行单个节点:等待前驱 → 执行 → 启动后继
  196. /// 关键修复:try/finally 保证任何异常路径都把 Status 从 Running 切到最终态,
  197. /// 避免外层 Task.Run 的 catch 吞掉异常后 Status 永久卡在 Running、_pendingCount 归零触发 ExecutionCompleted(true)。
  198. /// </summary>
  199. private async Task RunNodeAsync(FlowNode node)
  200. {
  201. // 跟踪本节点是否已置为 Running;异常时据此决定是否需要兜底收尾
  202. bool wasMarkedRunning = false;
  203. try
  204. {
  205. if (_token.IsCancellationRequested)
  206. {
  207. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  208. return;
  209. }
  210. var predecessors = GetPredecessors(node);
  211. bool skipWait = _skipPredecessorNodes.Contains(node.NodeId);
  212. // 等待所有前驱节点完成(从指定节点开始运行时跳过等待)
  213. if (predecessors.Count > 0 && !skipWait)
  214. {
  215. while (true)
  216. {
  217. if (_token.IsCancellationRequested)
  218. {
  219. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  220. return;
  221. }
  222. // 前驱有失败 → 跳过本节点,但仍启动后继
  223. if (predecessors.Any(p => p.Status == NodeRunStatus.Failed))
  224. {
  225. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  226. StartSuccessors(node, null);
  227. return;
  228. }
  229. // 所有前驱完成(Success或Skipped)
  230. if (predecessors.All(p => p.Status == NodeRunStatus.Success || p.Status == NodeRunStatus.Skipped))
  231. {
  232. // 所有前驱都是Skipped(无Success)→ 级联跳过
  233. if (!predecessors.Any(p => p.Status == NodeRunStatus.Success))
  234. {
  235. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  236. var cascadeResults = new Dictionary<string, object>
  237. {
  238. ["状态"] = NodeRunStatus.Skipped.ToString(),
  239. ["耗时"] = 0
  240. };
  241. _graph.Registry.SetResult(_graph.GraphId, node.NodeId, node.NodeName, cascadeResults);
  242. Application.Current?.Dispatcher.BeginInvoke(
  243. System.Windows.Threading.DispatcherPriority.Normal,
  244. new Action(() =>
  245. {
  246. node.SetResults(_graph.GraphId, cascadeResults);
  247. }));
  248. if (!_singleNodeMode)
  249. StartSuccessors(node, null);
  250. return;
  251. }
  252. break;
  253. }
  254. try { await Task.Delay(50, _token); }
  255. catch (OperationCanceledException)
  256. {
  257. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  258. return;
  259. }
  260. }
  261. }
  262. // 禁用的节点直接跳过,但仍启动后继
  263. if (!node.IsEnabled)
  264. {
  265. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  266. StartSuccessors(node, null);
  267. return;
  268. }
  269. // 标记运行中
  270. UpdateNodeStatus(node, NodeRunStatus.Running, 0);
  271. wasMarkedRunning = true;
  272. await Task.Delay(50, _token); // 短暂延迟让UI能看到Running状态(取消时按外层异常路径处理)
  273. // 执行节点
  274. var sw = Stopwatch.StartNew();
  275. NodeRunStatus result;
  276. List<string> branchTargets = null;
  277. Dictionary<string, object> execResults = null;
  278. try
  279. {
  280. // 新插件系统:通过 PluginLoader 创建实例
  281. var pluginDisplayName = node.ToolName ?? node.PluginId;
  282. var plugin = PluginLoader.Instance.CreateInstance(pluginDisplayName);
  283. if (plugin != null)
  284. {
  285. // 恢复模型数据
  286. if (node.PluginModel is Plugins.IFlowNodePlugin savedModel)
  287. plugin.GetModel = savedModel.GetModel;
  288. // 新实例需重新绑定所属流程的结果注册表
  289. plugin.Registry = _graph.Registry;
  290. #region 运行前休眠
  291. // 从节点读取运行前/后休眠时间
  292. int preDelayMs = node.PreDelayMs;
  293. int postDelayMs = node.PostDelayMs;
  294. // 运行前休眠
  295. if (preDelayMs > 0)
  296. {
  297. try { await Task.Delay(preDelayMs, _token); }
  298. catch (OperationCanceledException)
  299. {
  300. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  301. return;
  302. }
  303. }
  304. #endregion
  305. var status = await RunPluginAsync(plugin, node, node.TimeoutMs);
  306. result = status;
  307. execResults = plugin.LastResults ?? new Dictionary<string, object>();
  308. execResults["状态"] = status.ToString();
  309. execResults["结果"] = (status == NodeRunStatus.Success || status == NodeRunStatus.Skipped);
  310. execResults["模型"] = plugin;
  311. if (node.Category == NodeCategory.Decision)
  312. branchTargets = plugin.BranchTargets;
  313. #region 运行后休眠
  314. // 运行后休眠(在启动后继之前)
  315. if (postDelayMs > 0)
  316. {
  317. try { await Task.Delay(postDelayMs, _token); }
  318. catch (OperationCanceledException) { return; }
  319. }
  320. #endregion
  321. }
  322. else
  323. {
  324. AppLogger.Error($"未找到插件,节点判为失败:{pluginDisplayName}(节点 {node.NodeName} @ 流程 {_graph.GraphName})", nameof(FlowExecutor));
  325. result = NodeRunStatus.Failed;
  326. }
  327. }
  328. catch (Exception ex)
  329. {
  330. AppLogger.Error($"节点执行失败:{node.NodeName} @ 流程 {_graph.GraphName}", ex, nameof(FlowExecutor));
  331. result = NodeRunStatus.Failed;
  332. }
  333. sw.Stop();
  334. UpdateNodeStatus(node, result, (int)sw.ElapsedMilliseconds);
  335. node.CostTime = (int)sw.ElapsedMilliseconds;
  336. execResults["耗时"] = node.CostTime;
  337. // 存储执行结果到节点(UI线程更新)
  338. if (execResults != null && execResults.Count > 0)
  339. {
  340. _graph.Registry.SetResult(_graph.GraphId, node.NodeId, node.NodeName, execResults);
  341. Application.Current?.Dispatcher.BeginInvoke(
  342. System.Windows.Threading.DispatcherPriority.Normal,
  343. new Action(() =>
  344. {
  345. node.SetResults(_graph.GraphId, execResults);
  346. }));
  347. }
  348. // 执行失败:不启动常规后继,但显式触发 ExceptionBranch 类型的直接后继
  349. if (result == NodeRunStatus.Failed)
  350. {
  351. StartExceptionBranchSuccessors(node);
  352. return;
  353. }
  354. // 警告返回时 如果可跳过警告,则可继续后续节点 否则暂停
  355. if (result == NodeRunStatus.Warning && !node.IsSkipWarning) return;
  356. // End节点:不启动后继,触发结束事件
  357. if (node.Category == NodeCategory.End
  358. && execResults != null
  359. && execResults.TryGetValue("操作", out var opText)
  360. && opText?.ToString() == "结束整个流程")
  361. {
  362. EndNodeEncountered?.Invoke();
  363. return;
  364. }
  365. // 启动后继节点(fire-and-forget,不等待)
  366. if (!_singleNodeMode)
  367. StartSuccessors(node, branchTargets);
  368. }
  369. catch (Exception)
  370. {
  371. // 异常路径兜底:如果已置 Running,强制收尾为 Failed,防止 UI 永久卡 Running
  372. if (wasMarkedRunning && node.Status == NodeRunStatus.Running)
  373. {
  374. try { UpdateNodeStatus(node, NodeRunStatus.Failed, node.CostTime); } catch { }
  375. }
  376. throw; // 继续向上抛,由 Task.Run 的 catch 吞掉,_pendingCount 在 finally 减
  377. }
  378. }
  379. /// <summary>
  380. /// 运行插件并施加超时看门狗。timeoutMs<=0 时直接同步运行(保持原行为)。
  381. /// 超时后判为 Failed 并继续后续流程;阻塞式硬件调用无法强杀,仅保证流程不再无限等待。
  382. /// </summary>
  383. private async Task<NodeRunStatus> RunPluginAsync(IFlowNodePlugin plugin, FlowNode node, int timeoutMs)
  384. {
  385. if (timeoutMs <= 0)
  386. return plugin.Run(_token);
  387. var runTask = Task.Run(() => plugin.Run(_token));
  388. var timeoutTask = Task.Delay(timeoutMs, _token);
  389. // 观察两者潜在异常,避免未观察任务异常
  390. _ = runTask.ContinueWith(t => { var _e = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
  391. _ = timeoutTask.ContinueWith(t => { var _e = t.Exception; }, TaskContinuationOptions.OnlyOnFaulted);
  392. var completed = await Task.WhenAny(runTask, timeoutTask);
  393. if (completed == runTask)
  394. return await runTask; // 正常完成;插件抛异常则向上抛,由调用方 catch 记录
  395. if (_token.IsCancellationRequested)
  396. throw new OperationCanceledException(_token);
  397. AppLogger.Error($"节点执行超时({timeoutMs}ms):{node.NodeName} @ 流程 {_graph.GraphName};阻塞式硬件调用可能仍在后台线程运行,无法强制中断", nameof(FlowExecutor));
  398. return NodeRunStatus.Failed;
  399. }
  400. /// <summary>
  401. /// 启动后继节点(每个后继作为独立线程,不等待)
  402. /// </summary>
  403. private void StartSuccessors(FlowNode node, List<string> branchTargets)
  404. {
  405. var outgoing = _graph.Connections
  406. .Where(c => c.SourceNodeId == node.NodeId)
  407. .ToList();
  408. // 过滤掉 ExceptionBranch 后继:仅由前驱 Failed 路径显式触发,
  409. // 避免 Success/Skipped/Decision 分支误启动异常分支节点
  410. outgoing = outgoing
  411. .Where(c =>
  412. {
  413. var t = _graph.GetNode(c.TargetNodeId);
  414. return t == null || t.Category != NodeCategory.ExceptionBranch;
  415. })
  416. .ToList();
  417. // Decision节点:按NodeName筛选后继,非选中分支级联跳过
  418. if (node.Category == NodeCategory.Decision && branchTargets != null && branchTargets.Count > 0)
  419. {
  420. var selectedConns = new List<FlowConnection>();
  421. var skippedConns = new List<FlowConnection>();
  422. foreach (var conn in outgoing)
  423. {
  424. var target = _graph.GetNode(conn.TargetNodeId);
  425. if (target != null && branchTargets.Contains(target.NodeName))
  426. selectedConns.Add(conn);
  427. else
  428. skippedConns.Add(conn);
  429. }
  430. // 非选中分支:标记Skipped并级联启动其后继
  431. foreach (var conn in skippedConns)
  432. {
  433. var target = _graph.GetNode(conn.TargetNodeId);
  434. if (target != null)
  435. SkipNode(target);
  436. }
  437. outgoing = selectedConns;
  438. }
  439. foreach (var conn in outgoing)
  440. {
  441. if (_token.IsCancellationRequested) break;
  442. var target = _graph.GetNode(conn.TargetNodeId);
  443. if (target != null)
  444. {
  445. StartNode(target);
  446. }
  447. }
  448. }
  449. /// <summary>
  450. /// 启动失败节点的异常分支后继(仅 Category==ExceptionBranch 的直接后继)。
  451. /// 与 StartSuccessors 互斥:常规后继由 StartSuccessors 处理,异常分支后继由此处显式触发。
  452. /// </summary>
  453. private void StartExceptionBranchSuccessors(FlowNode failedNode)
  454. {
  455. if (_singleNodeMode) return;
  456. if (_token.IsCancellationRequested) return;
  457. var exceptionTargets = _graph.Connections
  458. .Where(c => c.SourceNodeId == failedNode.NodeId)
  459. .Select(c => _graph.GetNode(c.TargetNodeId))
  460. .Where(t => t != null && t.Category == NodeCategory.ExceptionBranch)
  461. .Distinct()
  462. .ToList();
  463. foreach (var exNode in exceptionTargets)
  464. {
  465. if (_token.IsCancellationRequested) break;
  466. StartExceptionBranchNode(exNode);
  467. }
  468. }
  469. /// <summary>
  470. /// 触发异常分支节点:原子 +1 触发计数,并尝试启动串行消费 Task。
  471. /// 多次触发会排队(计数累积),由运行中的 Task 在下一轮迭代消费。
  472. /// </summary>
  473. private void StartExceptionBranchNode(FlowNode node)
  474. {
  475. if (!node.IsEnabled)
  476. {
  477. SkipNode(node);
  478. return;
  479. }
  480. node.IncrementExceptionTrigger();
  481. TryStartExceptionBranchQueue(node);
  482. }
  483. /// <summary>
  484. /// 尝试获取运行权并启动队列消费 Task。运行权用 CAS 保证全局唯一。
  485. /// </summary>
  486. private void TryStartExceptionBranchQueue(FlowNode node)
  487. {
  488. if (!node.TryAcquireExceptionRun()) return; // 已有 Task 在跑,触发已排队,直接返回
  489. lock (_pendingLock) { _pendingCount++; }
  490. var exceptionTask = Task.Run(async () =>
  491. {
  492. try
  493. {
  494. await RunExceptionBranchAsync(node);
  495. }
  496. catch (Exception ex) { AppLogger.Error($"异常分支任务异常:{node.NodeName} @ 流程 {_graph.GraphName}", ex, nameof(FlowExecutor)); }
  497. finally
  498. {
  499. node.ReleaseExceptionRun();
  500. lock (_pendingLock)
  501. {
  502. _pendingCount--;
  503. Monitor.Pulse(_pendingLock);
  504. }
  505. // 防漏触发:在 Release 之前到达的新触发不会被本 Task 消费,再尝试启动一次
  506. if (node.ExceptionTriggers > 0 && !_token.IsCancellationRequested)
  507. TryStartExceptionBranchQueue(node);
  508. }
  509. });
  510. _nodeTasks.Add(exceptionTask);
  511. }
  512. /// <summary>
  513. /// 异常分支节点执行循环:串行消费触发队列,每次执行完检查是否还有排队触发。
  514. /// 不等待前驱(前驱已 Failed 才会到达此处)。
  515. /// </summary>
  516. private async Task RunExceptionBranchAsync(FlowNode node)
  517. {
  518. while (node.ExceptionTriggers > 0)
  519. {
  520. node.DecrementExceptionTrigger();
  521. if (_token.IsCancellationRequested)
  522. {
  523. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  524. break;
  525. }
  526. await RunExceptionBranchOnceAsync(node);
  527. }
  528. }
  529. /// <summary>
  530. /// 异常分支节点单次执行:跳过前驱等待,直接运行插件并启动常规后继。
  531. /// 逻辑与 RunNodeAsync 的"执行+结果+后继"段对齐,但不进入前驱等待循环。
  532. /// </summary>
  533. private async Task RunExceptionBranchOnceAsync(FlowNode node)
  534. {
  535. bool wasMarkedRunning = false;
  536. try
  537. {
  538. if (_token.IsCancellationRequested)
  539. {
  540. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  541. return;
  542. }
  543. UpdateNodeStatus(node, NodeRunStatus.Running, 0);
  544. wasMarkedRunning = true;
  545. Thread.Sleep(50);
  546. var sw = Stopwatch.StartNew();
  547. NodeRunStatus result;
  548. Dictionary<string, object> execResults = null;
  549. int preDelayMs = node.PreDelayMs;
  550. int postDelayMs = node.PostDelayMs;
  551. if (preDelayMs > 0)
  552. {
  553. try { await Task.Delay(preDelayMs, _token); }
  554. catch (OperationCanceledException)
  555. {
  556. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  557. return;
  558. }
  559. }
  560. try
  561. {
  562. var pluginDisplayName = node.ToolName ?? node.PluginId;
  563. var plugin = PluginLoader.Instance.CreateInstance(pluginDisplayName);
  564. if (plugin != null)
  565. {
  566. if (node.PluginModel is IFlowNodePlugin savedModel)
  567. plugin.GetModel = savedModel.GetModel;
  568. plugin.Registry = _graph.Registry;
  569. var status = await RunPluginAsync(plugin, node, node.TimeoutMs);
  570. result = status;
  571. execResults = plugin.LastResults ?? new Dictionary<string, object>();
  572. execResults["状态"] = status.ToString();
  573. execResults["结果"] = (status == NodeRunStatus.Success || status == NodeRunStatus.Skipped);
  574. execResults["耗时"] = plugin.CostTime;
  575. execResults["模型"] = plugin;
  576. }
  577. else
  578. {
  579. AppLogger.Error($"未找到插件,异常分支节点判为失败:{pluginDisplayName}(节点 {node.NodeName} @ 流程 {_graph.GraphName})", nameof(FlowExecutor));
  580. result = NodeRunStatus.Failed;
  581. }
  582. }
  583. catch (Exception ex)
  584. {
  585. AppLogger.Error($"异常分支节点执行失败:{node.NodeName} @ 流程 {_graph.GraphName}", ex, nameof(FlowExecutor));
  586. result = NodeRunStatus.Failed;
  587. }
  588. if (postDelayMs > 0)
  589. {
  590. try { await Task.Delay(postDelayMs, _token); }
  591. catch (OperationCanceledException) { return; }
  592. }
  593. sw.Stop();
  594. UpdateNodeStatus(node, result, (int)sw.ElapsedMilliseconds);
  595. node.CostTime = (int)sw.ElapsedMilliseconds;
  596. execResults["耗时"] = node.CostTime;
  597. if (execResults != null && execResults.Count > 0)
  598. {
  599. _graph.Registry.SetResult(_graph.GraphId, node.NodeId, node.NodeName, execResults);
  600. Application.Current?.Dispatcher.BeginInvoke(
  601. System.Windows.Threading.DispatcherPriority.Normal,
  602. new Action(() =>
  603. {
  604. node.SetResults(_graph.GraphId, execResults);
  605. }));
  606. }
  607. if (!_singleNodeMode)
  608. StartSuccessors(node, null);
  609. if (result == NodeRunStatus.Failed)
  610. StartExceptionBranchSuccessors(node);
  611. }
  612. catch (Exception)
  613. {
  614. if (wasMarkedRunning && node.Status == NodeRunStatus.Running)
  615. {
  616. try { UpdateNodeStatus(node, NodeRunStatus.Failed, node.CostTime); } catch { }
  617. }
  618. throw;
  619. }
  620. }
  621. /// <summary>
  622. /// 跳过节点:标记Skipped + 设置结果 + 启动后继(防止下游死等)
  623. /// </summary>
  624. private void SkipNode(FlowNode node)
  625. {
  626. lock (_startLock)
  627. {
  628. if (_startedNodes.Contains(node.NodeId)) return;
  629. _startedNodes.Add(node.NodeId);
  630. }
  631. lock (_pendingLock) { _pendingCount++; }
  632. var skipTask = Task.Run(() =>
  633. {
  634. try
  635. {
  636. UpdateNodeStatus(node, NodeRunStatus.Skipped, 0);
  637. var skipResults = new Dictionary<string, object>
  638. {
  639. ["状态"] = NodeRunStatus.Skipped.ToString(),
  640. ["耗时"] = 0
  641. };
  642. _graph.Registry.SetResult(_graph.GraphId, node.NodeId, node.NodeName, skipResults);
  643. Application.Current?.Dispatcher.BeginInvoke(
  644. System.Windows.Threading.DispatcherPriority.Normal,
  645. new Action(() =>
  646. {
  647. node.SetResults(_graph.GraphId, skipResults);
  648. }));
  649. if (!_singleNodeMode)
  650. StartSuccessors(node, null);
  651. }
  652. finally
  653. {
  654. lock (_pendingLock)
  655. {
  656. _pendingCount--;
  657. Monitor.Pulse(_pendingLock);
  658. }
  659. }
  660. });
  661. _nodeTasks.Add(skipTask);
  662. }
  663. /// <summary>
  664. /// 获取前驱节点
  665. /// </summary>
  666. private List<FlowNode> GetPredecessors(FlowNode node)
  667. {
  668. return _graph.Connections
  669. .Where(c => c.TargetNodeId == node.NodeId)
  670. .Select(c => _graph.GetNode(c.SourceNodeId))
  671. .Where(n => n != null)
  672. .ToList();
  673. }
  674. /// <summary>
  675. /// 获取根节点(没有输入连线的节点)
  676. /// </summary>
  677. private List<FlowNode> GetRootNodes()
  678. {
  679. var targetIds = new HashSet<string>(
  680. _graph.Connections.Select(c => c.TargetNodeId)
  681. );
  682. return _graph.Nodes
  683. .Where(n => !targetIds.Contains(n.NodeId)
  684. && n.Category != NodeCategory.ExceptionBranch)
  685. .ToList();
  686. }
  687. /// <summary>
  688. /// 更新节点状态。所有赋值与 UI 通知都切到 UI 线程,避免后台线程触发 PropertyChanged 引发 WPF 绑定异常。
  689. /// 用 Dispatcher.BeginInvoke(异步、非阻塞)而非 Invoke(同步阻塞):
  690. /// 后台每个节点线程都会并发更新状态,若用同步 Invoke,UI 线程繁忙(模态窗体泵消息、画布/结果表重绘)时
  691. /// 会把大量更新挤在一起——前后的 Running 与完成态被同一渲染周期"合并",导致看不到闪灯/耗时跳动,
  692. /// 且最后的 ExecutionCompleted(IsRunning 复位)也会被拖后,表现为"要过段时间才恢复"。
  693. /// </summary>
  694. private void UpdateNodeStatus(FlowNode node, NodeRunStatus status, int costTime)
  695. {
  696. Application.Current?.Dispatcher.BeginInvoke(
  697. System.Windows.Threading.DispatcherPriority.Normal,
  698. new Action(() =>
  699. {
  700. node.Status = status;
  701. node.CostTime = costTime;
  702. node.NotifyStatusChanged();
  703. NodeStatusChanged?.Invoke(node);
  704. }));
  705. }
  706. /// <summary>
  707. /// 重置所有节点状态
  708. /// </summary>
  709. private void ResetAllNodes()
  710. {
  711. Application.Current?.Dispatcher.Invoke(() =>
  712. {
  713. foreach (var node in _graph.Nodes)
  714. {
  715. node.Status = NodeRunStatus.NotStarted;
  716. node.CostTime = 0;
  717. node.ResultItems?.Clear();
  718. node.NotifyStatusChanged();
  719. if (node.Category == NodeCategory.ExceptionBranch)
  720. node.ResetExceptionState();
  721. }
  722. });
  723. // 清空当前结果(历史记录保留,跨多次执行累积)
  724. _graph.Registry.ClearFlow(_graph.GraphId);
  725. }
  726. }
  727. }