NodeInputResolver.java 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package com.agent.management.engine;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import lombok.extern.slf4j.Slf4j;
  5. import java.util.*;
  6. /**
  7. * 节点输入变量解析器。
  8. *
  9. * <p>对节点 data.inputs[] 中的每个字段:
  10. * <ol>
  11. * <li>优先使用显式 mapping(sourceNodeId/sourceField/sourcePath)</li>
  12. * <li>若未配置或来源不可达,进入四级隐式关联 fallback:
  13. * 精确同名 → 忽略分隔符/大小写同名 → JSON 嵌套路径精确匹配 → JSON 嵌套路径模糊匹配</li>
  14. * <li>按目标 type 做类型转换</li>
  15. * </ol>
  16. */
  17. @Slf4j
  18. public class NodeInputResolver {
  19. private static final ObjectMapper MAPPER = new ObjectMapper();
  20. /**
  21. * 解析后的输入结果。
  22. */
  23. public static class ResolvedInputs {
  24. private final Map<String, Object> values = new LinkedHashMap<>();
  25. private final List<String> missing = new ArrayList<>();
  26. private final List<String> warnings = new ArrayList<>();
  27. public Map<String, Object> getValues() {
  28. return values;
  29. }
  30. public List<String> getMissing() {
  31. return missing;
  32. }
  33. public List<String> getWarnings() {
  34. return warnings;
  35. }
  36. public boolean hasMissing() {
  37. return !missing.isEmpty();
  38. }
  39. }
  40. /**
  41. * 解析节点输入。
  42. *
  43. * @param nodeData 节点 data(JSON)
  44. * @param workspace 当前节点工作区
  45. * @return 解析结果(值、缺失项、警告)
  46. */
  47. public static ResolvedInputs resolveInputs(JsonNode nodeData, NodeWorkspace workspace) {
  48. ResolvedInputs result = new ResolvedInputs();
  49. JsonNode inputsNode = nodeData.path("inputs");
  50. if (!inputsNode.isArray() || inputsNode.isEmpty()) {
  51. return result;
  52. }
  53. for (JsonNode field : inputsNode) {
  54. String name = field.path("name").asText("");
  55. if (name.isEmpty()) {
  56. continue;
  57. }
  58. String type = field.path("type").asText("string");
  59. boolean required = field.path("required").asBoolean(false);
  60. Object value = resolveInputValue(name, type, field.path("mapping"), workspace, result);
  61. if (value == null) {
  62. if (required) {
  63. result.missing.add(name);
  64. }
  65. } else {
  66. result.values.put(name, value);
  67. }
  68. }
  69. return result;
  70. }
  71. private static Object resolveInputValue(String name, String type, JsonNode mappingNode,
  72. NodeWorkspace workspace, ResolvedInputs result) {
  73. // 1. 显式 mapping
  74. if (mappingNode != null && !mappingNode.isMissingNode()) {
  75. String sourceNodeId = mappingNode.path("sourceNodeId").asText("");
  76. String sourceField = mappingNode.path("sourceField").asText("");
  77. String sourcePath = mappingNode.path("sourcePath").asText(null);
  78. if (!sourceNodeId.isEmpty()) {
  79. if (workspace.getScopedOutputs().containsKey(sourceNodeId)) {
  80. if (sourceField.isEmpty()) {
  81. sourceField = name;
  82. }
  83. Object value = workspace.getScopedOutput(sourceNodeId, sourceField);
  84. if (value != null && sourcePath != null && !sourcePath.isBlank()) {
  85. value = JsonPathExtractor.extract(value, sourcePath);
  86. }
  87. if (value != null) {
  88. return VariableConverter.convert(value, type);
  89. }
  90. result.warnings.add(name + " 显式映射到 " + sourceNodeId + "." + sourceField
  91. + (sourcePath != null ? "/" + sourcePath : "") + " 但值为空");
  92. } else {
  93. result.warnings.add(name + " 显式映射来源 " + sourceNodeId + " 不可达,已忽略");
  94. }
  95. }
  96. }
  97. // 2. 直接变量表(覆盖初始输入与向后兼容的扁平变量)
  98. Object direct = workspace.getVariable(name);
  99. if (direct != null) {
  100. return VariableConverter.convert(direct, type);
  101. }
  102. // 3. 隐式关联 fallback:按拓扑逆序(最近前驱优先)
  103. List<String> ordered = new ArrayList<>(workspace.getScopedOutputs().keySet());
  104. Collections.reverse(ordered);
  105. // 3.1 精确同名
  106. for (String nodeId : ordered) {
  107. Object value = workspace.getScopedOutput(nodeId, name);
  108. if (value != null) {
  109. return VariableConverter.convert(value, type);
  110. }
  111. }
  112. // 3.2 忽略 [-_] 与大小写同名
  113. String normName = normalizeForMatch(name);
  114. for (String nodeId : ordered) {
  115. Map<String, Object> scoped = workspace.getScopedOutputs().get(nodeId);
  116. if (scoped == null) continue;
  117. for (Map.Entry<String, Object> e : scoped.entrySet()) {
  118. if (normalizeForMatch(e.getKey()).equals(normName)) {
  119. return VariableConverter.convert(e.getValue(), type);
  120. }
  121. }
  122. }
  123. // 3.3 JSON 嵌套路径精确同名:以整个节点输出 map 为根
  124. for (String nodeId : ordered) {
  125. Map<String, Object> scoped = workspace.getScopedOutputs().get(nodeId);
  126. if (scoped == null) continue;
  127. Object extracted = JsonPathExtractor.extract(scoped, name);
  128. if (extracted != null) {
  129. return VariableConverter.convert(extracted, type);
  130. }
  131. }
  132. // 3.4 JSON 嵌套路径模糊同名:以整个节点输出 map 为根,忽略 [-_] 与大小写
  133. for (String nodeId : ordered) {
  134. Map<String, Object> scoped = workspace.getScopedOutputs().get(nodeId);
  135. if (scoped == null) continue;
  136. Object extracted = extractByNormalizedPath(scoped, name);
  137. if (extracted != null) {
  138. return VariableConverter.convert(extracted, type);
  139. }
  140. }
  141. return null;
  142. }
  143. /**
  144. * 忽略 [-_] 与大小写的归一化,用于模糊匹配。
  145. */
  146. static String normalizeForMatch(String s) {
  147. if (s == null) return "";
  148. return s.replaceAll("[-_]", "").toLowerCase(Locale.ROOT);
  149. }
  150. /**
  151. * 按归一化路径从对象中取值:路径每一节都忽略 [-_] 与大小写匹配键名。
  152. */
  153. private static Object extractByNormalizedPath(Object root, String path) {
  154. if (path == null || path.isBlank()) {
  155. return root;
  156. }
  157. Object current = root;
  158. String[] segments = path.split("\\.");
  159. for (String segment : segments) {
  160. if (segment.isEmpty()) {
  161. continue;
  162. }
  163. current = stepFuzzy(current, segment);
  164. if (current == null) {
  165. return null;
  166. }
  167. }
  168. return current;
  169. }
  170. private static Object stepFuzzy(Object current, String segment) {
  171. String normSeg = normalizeForMatch(segment);
  172. if (current instanceof Map<?, ?> map) {
  173. // 先精确匹配,再模糊匹配
  174. if (map.containsKey(segment)) {
  175. return map.get(segment);
  176. }
  177. for (Map.Entry<?, ?> e : map.entrySet()) {
  178. Object key = e.getKey();
  179. if (key instanceof String k && normalizeForMatch(k).equals(normSeg)) {
  180. return e.getValue();
  181. }
  182. }
  183. return null;
  184. }
  185. if (current instanceof JsonNode node) {
  186. if (node.isArray()) {
  187. Integer idx = parseIndex(segment);
  188. return idx != null && idx >= 0 && idx < node.size()
  189. ? jsonNodeToValue(node.get(idx)) : null;
  190. }
  191. JsonNode child = node.get(segment);
  192. if (child != null) {
  193. return jsonNodeToValue(child);
  194. }
  195. for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
  196. String field = it.next();
  197. if (normalizeForMatch(field).equals(normSeg)) {
  198. return jsonNodeToValue(node.get(field));
  199. }
  200. }
  201. return null;
  202. }
  203. if (current instanceof Collection<?> collection) {
  204. Integer idx = parseIndex(segment);
  205. if (idx == null || idx < 0) {
  206. return null;
  207. }
  208. int i = 0;
  209. for (Object item : collection) {
  210. if (i == idx) {
  211. return item;
  212. }
  213. i++;
  214. }
  215. return null;
  216. }
  217. // POJO:先转 JsonNode 再递归
  218. try {
  219. JsonNode node = MAPPER.valueToTree(current);
  220. return stepFuzzy(node, segment);
  221. } catch (Exception e) {
  222. return null;
  223. }
  224. }
  225. private static Integer parseIndex(String segment) {
  226. try {
  227. return Integer.parseInt(segment);
  228. } catch (NumberFormatException e) {
  229. return null;
  230. }
  231. }
  232. private static Object jsonNodeToValue(JsonNode node) {
  233. if (node == null || node.isNull()) {
  234. return null;
  235. }
  236. if (node.isTextual()) {
  237. return node.asText();
  238. }
  239. if (node.isNumber()) {
  240. return node.numberValue();
  241. }
  242. if (node.isBoolean()) {
  243. return node.booleanValue();
  244. }
  245. try {
  246. return MAPPER.treeToValue(node, Object.class);
  247. } catch (Exception e) {
  248. return node.toString();
  249. }
  250. }
  251. }