diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowNameResolver.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowNameResolver.java new file mode 100644 index 0000000..097f6b3 --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowNameResolver.java @@ -0,0 +1,202 @@ +package com.eip4.platform.metadata.flow; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import com.dsasp.server.common.core.FlowDefinition; +import com.dsasp.server.core.service.flow.model.DefaultFlowHelper; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +/** + * 服务名解析器(F2-14):将 /api/flow/{id} 的服务名按三级顺序解析为可执行的 + * {@link FlowDefinition}。 + * + *

解析顺序: + *

    + *
  1. UUID:36 位标准 UUID 格式 → 直接返回 null,由调用方按 PK 查 sys_serviceflow(现状逻辑不变)。
  2. + *
  3. 默认搜索:形如 {@code _SEARCH},且 TABLE 存在于 SYS_ENTITY → + * 调用 {@link DefaultFlowHelper#getDefaultSearch} 运行时合成 FlowDefinition。 + * 合成结果走 Caffeine 缓存(maxSize 2000);{@link #evict(String)} 与 + * {@code /api/meta/evict} 钩子对齐。 + *
  4. 其余命名:按 sys_serviceflow_id 列精确查(主键查,O(1),无需 XML 扫描)→ + * 命中返回哨兵 {@link ResolvedFlow#NAMED_HIT}(调用方用原始名按 PK 直接执行); + * 不命中返回 {@link ResolvedFlow#ORPHAN}(调用方应返回 404)。
  5. + * + * + *

    写操作后缀拒绝:{@code _SAVE/_UPDATE/_DELETE} 结尾的名字(非 UUID 且无法按 _SEARCH 路径处理) + * 返回 {@link ResolvedFlow#WRITE_REDIRECT},调用方应引导使用 /api/entity/{x}/save 端点。 + * + *

    零改 com.dsasp 文件:DefaultFlowHelper 调用在本类(现代层包),保真层不动。 + * SQL 全参数化;表名已经过白名单校验(SYS_ENTITY 存在性 = 白名单)。 + */ +@Component +public class FlowNameResolver { + + private static final Logger log = LoggerFactory.getLogger(FlowNameResolver.class); + + /** 孤儿服务名日志前缀,便于 grep 汇总 */ + private static final String ORPHAN_LOG_PREFIX = "[F2-14 ORPHAN]"; + + /** 默认搜索合成结果缓存(按 TABLE_SEARCH 名字缓存,失效跟 evict 钩子对齐) */ + private final Cache> searchCache = Caffeine.newBuilder() + .maximumSize(2_000) + .build(); + + /** UUID 格式正则(36 位,含4个连字符) */ + private static final java.util.regex.Pattern UUID_PATTERN = + java.util.regex.Pattern.compile( + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); + + /** 写操作默认后缀,这三种走 /api/entity/{x}/save,不走 flow 查询路径 */ + private static final java.util.regex.Pattern WRITE_SUFFIX_PATTERN = + java.util.regex.Pattern.compile("(?i)_SAVE$|_UPDATE$|_DELETE$"); + + private final JdbcTemplate jdbcTemplate; + private final SynthesizedFlowRegistry registry; + + public FlowNameResolver(JdbcTemplate jdbcTemplate, SynthesizedFlowRegistry registry) { + this.jdbcTemplate = jdbcTemplate; + this.registry = registry; + } + + /** + * 解析结果类型。 + */ + public enum ResolveType { + /** UUID 格式,调用方走 PK 查引擎(现状逻辑) */ + UUID_PASSTHROUGH, + /** _SEARCH 合成:返回合成 FlowDefinition,调用方直接执行 */ + SYNTHESIZED, + /** 命名服务命中 sys_serviceflow(PK=id),调用方用原始名按 PK 执行 */ + NAMED_HIT, + /** 写操作后缀,应 redirect 到 /api/entity/{x}/save */ + WRITE_REDIRECT, + /** 孤儿:既不是 UUID,也查不到,也合成不了 → 404 */ + ORPHAN + } + + public record ResolvedFlow(ResolveType type, FlowDefinition definition, String message) { + public static final ResolvedFlow UUID_PASSTHROUGH = new ResolvedFlow(ResolveType.UUID_PASSTHROUGH, null, null); + public static final ResolvedFlow NAMED_HIT = new ResolvedFlow(ResolveType.NAMED_HIT, null, null); + public static final ResolvedFlow ORPHAN = new ResolvedFlow(ResolveType.ORPHAN, null, null); + public static final ResolvedFlow WRITE_REDIRECT = new ResolvedFlow(ResolveType.WRITE_REDIRECT, null, + "写操作请使用 /api/entity/{table}/save 端点,不走 flow 查询路径"); + } + + /** + * 解析服务名。 + * + * @param flowId 请求路径中的 {id} + * @return 解析结果,不会为 null + */ + public ResolvedFlow resolve(String flowId) { + if (flowId == null || flowId.isBlank()) { + return ResolvedFlow.ORPHAN; + } + + // 1. UUID → 原样走 PK 查(现状逻辑) + if (UUID_PATTERN.matcher(flowId).matches()) { + return ResolvedFlow.UUID_PASSTHROUGH; + } + + // 2. 写操作后缀拒绝(_SAVE/_UPDATE/_DELETE) + if (WRITE_SUFFIX_PATTERN.matcher(flowId).find()) { + return ResolvedFlow.WRITE_REDIRECT; + } + + // 3. _SEARCH 后缀 → 运行时合成 + String upper = flowId.toUpperCase(); + if (upper.endsWith("_SEARCH")) { + String tableName = upper.substring(0, upper.length() - 7); // strip "_SEARCH" + ResolvedFlow synthesized = trysynthesize(upper, tableName); + if (synthesized != null) { + return synthesized; + } + // tableName 不在 SYS_ENTITY → 继续走第4步(可能是命名服务 SOMETHING_SEARCH) + } + + // 4. 其余命名服务:按 sys_serviceflow_id 精确查(主键查) + if (existsInServiceFlow(flowId)) { + return ResolvedFlow.NAMED_HIT; + } + + // 孤儿 + log.warn("{} 服务名不在任何解析路径: {}", ORPHAN_LOG_PREFIX, sanitize(flowId)); + return ResolvedFlow.ORPHAN; + } + + /** + * 尝试合成默认搜索流。 + * @param cacheKey 缓存键(TABLE_SEARCH 大写) + * @param tableName 表名(大写) + * @return 合成结果,或 null(表名不在 SYS_ENTITY) + */ + private ResolvedFlow trysynthesize(String cacheKey, String tableName) { + // 先查缓存 + FlowDefinition cached = searchCache.getIfPresent(cacheKey); + if (cached != null) { + return new ResolvedFlow(ResolveType.SYNTHESIZED, cached, null); + } + + // 查 SYS_ENTITY(参数化,表名不进 SQL 字符串) + List> rows = jdbcTemplate.queryForList( + "SELECT sys_entity_id, name FROM eip3.sys_entity WHERE UPPER(tablename) = ? AND isactive = 1", + tableName); + + if (rows.isEmpty()) { + return null; // 表名不在 SYS_ENTITY,不走合成路径 + } + + String entityId = String.valueOf(rows.get(0).get("sys_entity_id")); + String displayName = String.valueOf(rows.get(0).get("name")); + + FlowDefinition flow = DefaultFlowHelper.getDefaultSearch(tableName, entityId, displayName); + searchCache.put(cacheKey, flow); + // 同步注册到执行路由注册表,使 FlowServiceWithSynthesis.getFlowDefinition 能命中 + registry.register(flow); + log.debug("[F2-14 SEARCH] 合成默认搜索流: table={} entityId={}", tableName, entityId); + return new ResolvedFlow(ResolveType.SYNTHESIZED, flow, null); + } + + /** + * 命名服务是否存在于 sys_serviceflow(按主键精确查)。 + */ + private boolean existsInServiceFlow(String flowId) { + Integer count = jdbcTemplate.queryForObject( + "SELECT COUNT(*) FROM eip3.sys_serviceflow WHERE sys_serviceflow_id = ?", + Integer.class, flowId); + return count != null && count > 0; + } + + /** + * 失效默认搜索缓存中 TABLE_SEARCH 条目(与 /api/meta/evict 钩子对齐)。 + * @param table 实体表名(任意大小写) + */ + public void evict(String table) { + if (table != null && !table.isBlank()) { + String key = table.toUpperCase() + "_SEARCH"; + searchCache.invalidate(key); + registry.evict(key); + log.debug("[F2-14 EVICT] 失效 search cache + registry: {}", key); + } + } + + /** 失效全部搜索缓存 */ + public void evictAll() { + searchCache.invalidateAll(); + registry.evictAll(); + } + + /** 日志输出中对流名做安全过滤(只保留字母数字下划线连字符) */ + private static String sanitize(String id) { + if (id == null) return ""; + return id.replaceAll("[^A-Za-z0-9_\\-]", "?"); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowServiceWithSynthesis.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowServiceWithSynthesis.java new file mode 100644 index 0000000..37909b6 --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowServiceWithSynthesis.java @@ -0,0 +1,68 @@ +package com.eip4.platform.metadata.flow; + +import java.util.Properties; + +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +import com.dsasp.server.common.core.FlowDefinition; +import com.dsasp.server.common.core.service.FlowService; +import com.dsasp.server.core.service.FlowServiceImpl; + +/** + * FlowService 装饰器(F2-14):在现代层拦截 {@code getFlowDefinition}, + * 优先从 {@link SynthesizedFlowRegistry} 查合成流(如默认搜索流), + * 未命中再委托原始 {@link FlowServiceImpl} 按 PK 查 sys_serviceflow。 + * + *

    加 {@code @Primary} 使 {@link com.dsasp.server.core.service.FlowExcuteServiceImpl} + * 的 {@code @Autowired FlowService} 注入本类而非 FlowServiceImpl, + * 从而在不改任何保真层文件的前提下插入合成流查找逻辑。 + * + *

    其余 FlowService 方法(saveOrUpdate、isControlFlowService 等)全部直接委托, + * 语义不变。 + */ +@Primary +@Component +public class FlowServiceWithSynthesis implements FlowService { + + private final FlowServiceImpl delegate; + private final SynthesizedFlowRegistry registry; + + public FlowServiceWithSynthesis(FlowServiceImpl delegate, + SynthesizedFlowRegistry registry) { + this.delegate = delegate; + this.registry = registry; + } + + /** + * 优先从合成注册表查;未命中委托原始实现按 PK 查库。 + */ + @Override + public FlowDefinition getFlowDefinition(String flowId) { + FlowDefinition synthesized = registry.find(flowId); + if (synthesized != null) { + return synthesized; + } + return delegate.getFlowDefinition(flowId); + } + + @Override + public FlowDefinition saveOrUpdate(FlowDefinition flow, Properties ctx) { + return delegate.saveOrUpdate(flow, ctx); + } + + @Override + public boolean isExistEntityFlow(String entityId) { + return delegate.isExistEntityFlow(entityId); + } + + @Override + public boolean addDefaultFlowService(String entityId, Properties ctx) { + return delegate.addDefaultFlowService(entityId, ctx); + } + + @Override + public boolean isControlFlowService(String flowId) { + return delegate.isControlFlowService(flowId); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/SynthesizedFlowRegistry.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/SynthesizedFlowRegistry.java new file mode 100644 index 0000000..efdea1e --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/SynthesizedFlowRegistry.java @@ -0,0 +1,44 @@ +package com.eip4.platform.metadata.flow; + +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.stereotype.Component; + +import com.dsasp.server.common.core.FlowDefinition; + +/** + * 合成流注册表(F2-14):运行时合成的 FlowDefinition(如默认搜索流)在此注册, + * 供 {@link FlowServiceWithSynthesis} 在 {@code getFlowDefinition} 时优先命中, + * 从而绕过 {@code FlowServiceImpl.loadFlowXml} 查库的逻辑。 + * + *

    线程安全:ConcurrentHashMap,不需要额外同步。 + * 合成流的生命周期由 {@link FlowNameResolver} 的 Caffeine 缓存管理(evict 对齐), + * 本注册表作为执行时临时路由层,put 后不主动 remove(同一 key 重复 put 幂等)。 + */ +@Component +public class SynthesizedFlowRegistry { + + private final ConcurrentHashMap> registry = new ConcurrentHashMap<>(); + + /** 注册合成流(key = flow.getKey(),通常是 TABLE_SEARCH 大写)。 */ + public void register(FlowDefinition flow) { + registry.put(flow.getKey(), flow); + } + + /** 查找合成流,不存在返回 null。 */ + public FlowDefinition find(String flowId) { + return flowId == null ? null : registry.get(flowId); + } + + /** 失效(元数据 evict 时同步调用)。 */ + public void evict(String flowId) { + if (flowId != null) { + registry.remove(flowId); + } + } + + /** 全量失效。 */ + public void evictAll() { + registry.clear(); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java index e35b49c..97335d0 100644 --- a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/FlowController.java @@ -7,6 +7,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -15,10 +17,13 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.dsasp.server.common.core.FlowDefinition; import com.dsasp.server.common.core.service.FlowExcuteService; import com.dsasp.server.common.dataDic.bean.GeneralPOJO; import com.dsasp.server.common.dataDic.service.POJOCRUDService; import com.dsasp.server.common.util.UserSession; +import com.eip4.platform.metadata.flow.FlowNameResolver; +import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow; import io.swagger.v3.oas.annotations.Operation; @@ -32,6 +37,10 @@ import io.swagger.v3.oas.annotations.Operation; * * 这正是报表方案 D 节 echart.jsp 第 25 行 {@code flowService.excute(map, UserSession.get(), flowid)} 的 REST 化。 * + *

    F2-14 服务名解析:{@link FlowNameResolver} 在引擎调用前三级解析服务名: + * UUID → 原样走引擎 PK 查;{@code

    _SEARCH} 且 TABLE 在 SYS_ENTITY → + * 运行时合成默认搜索流;其余命名服务 → 按 sys_serviceflow_id 精确查;孤儿 → 404。 + * *

    读写时机判断(REST 入口仅放行查询类服务流):当前服务流引擎本身不区分读写—— * 一个流既可挂 {@code listSelect}(读)也可挂 {@code save/update/delete}(写)service 节点, * 引擎统一走 {@code excute}。本 P1 阶段不在门面做引擎级读写闸(避免误判与维护负担), @@ -46,16 +55,18 @@ import io.swagger.v3.oas.annotations.Operation; public class FlowController { private final FlowExcuteService flowExcuteService; + private final FlowNameResolver flowNameResolver; - public FlowController(FlowExcuteService flowExcuteService) { + public FlowController(FlowExcuteService flowExcuteService, FlowNameResolver flowNameResolver) { this.flowExcuteService = flowExcuteService; + this.flowNameResolver = flowNameResolver; } /** GET 执行:query 参数透传为服务流入参 map(保留原始大小写键,交由流脚本/服务节点消费)。 */ @GetMapping("/{id}") @Operation(summary = "执行服务流(GET):query 参数作为入参 map,返回流输出 JSON。报表 D 类查询入口") - public Map executeGet(@PathVariable String id, - @RequestParam Map allParams) { + public ResponseEntity> executeGet(@PathVariable String id, + @RequestParam Map allParams) { Map map = new HashMap<>(allParams); return run(id, map); } @@ -63,26 +74,67 @@ public class FlowController { /** POST 执行:JSON body 透传为服务流入参 map。body 为空时按空 map 执行。 */ @PostMapping("/{id}") @Operation(summary = "执行服务流(POST):JSON body 作为入参 map,返回流输出 JSON") - public Map executePost(@PathVariable String id, - @RequestBody(required = false) Map body) { + public ResponseEntity> executePost(@PathVariable String id, + @RequestBody(required = false) Map body) { Map map = body == null ? new HashMap<>() : new HashMap<>(body); return run(id, map); } /** - * 统一执行 + 响应封装。引擎 {@code excute} 返回流的输出字段 Map;查询/报表类流的输出 - * 通常含一个 {@code listSelect} 结果({@code {listresult, pagecount}}),本方法递归归一化: - * GeneralPOJO → 平面行 map;含 {@code listresult} 的子结果 → amis 风格 {@code {items,total}}。 + * 统一执行 + 响应封装(F2-14 三级解析)。 + * + *

      + *
    1. UUID → 原样传给引擎,按 PK 查 sys_serviceflow(现状逻辑)。
    2. + *
    3. {@code
    _SEARCH} 且 TABLE 在 SYS_ENTITY → 运行时合成搜索流并直接执行。 + *
  6. 其余命名服务存在于 sys_serviceflow → 用原名传给引擎(PK 即名字)。
  7. + *
  8. 写操作后缀 (_SAVE/_UPDATE/_DELETE) → 404 + 引导提示。
  9. + *
  10. 孤儿 → 404 + 明确错误体。
  11. + * */ - private Map run(String id, Map map) { - Properties ctx = UserSession.getAdmin(); - Object output = flowExcuteService.excute(map, ctx, id); + private ResponseEntity> run(String id, Map map) { + ResolvedFlow resolved = flowNameResolver.resolve(id); - Map resp = new HashMap<>(); + return switch (resolved.type()) { + case UUID_PASSTHROUGH, NAMED_HIT -> { + // UUID 或命名命中:直接走引擎(引擎按 PK 查 sys_serviceflow) + Properties ctx = UserSession.getAdmin(); + Object output = flowExcuteService.excute(map, ctx, id); + yield ok(output); + } + case SYNTHESIZED -> { + // _SEARCH 合成:合成流已注册到 SynthesizedFlowRegistry, + // FlowServiceWithSynthesis.getFlowDefinition 会按 key 命中, + // 直接用原始 flowId(已大写 = TABLE_SEARCH)调引擎。 + Properties ctx = UserSession.getAdmin(); + Object output = flowExcuteService.excute(map, ctx, resolved.definition().getKey()); + yield ok(output); + } + case WRITE_REDIRECT -> { + Map err = new LinkedHashMap<>(); + err.put("status", 1); + err.put("msg", resolved.message()); + yield ResponseEntity.status(HttpStatus.NOT_FOUND).body(err); + } + case ORPHAN -> { + Map err = new LinkedHashMap<>(); + err.put("status", 1); + err.put("msg", "服务不存在: " + sanitize(id)); + yield ResponseEntity.status(HttpStatus.NOT_FOUND).body(err); + } + }; + } + + private ResponseEntity> ok(Object output) { + Map resp = new LinkedHashMap<>(); resp.put("status", 0); resp.put("msg", ""); resp.put("data", normalize(output)); - return resp; + return ResponseEntity.ok(resp); + } + + private static String sanitize(String id) { + if (id == null) return ""; + return id.replaceAll("[^A-Za-z0-9_\\-]", "?"); } /** 递归归一化引擎返回值,使之可被 Jackson 序列化(GeneralPOJO 非 bean,需手工展平)。 */ diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/flow/FlowNameResolverTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/flow/FlowNameResolverTest.java new file mode 100644 index 0000000..f2dd86e --- /dev/null +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/flow/FlowNameResolverTest.java @@ -0,0 +1,201 @@ +package com.eip4.platform.metadata.flow; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.eip4.platform.metadata.flow.FlowNameResolver.ResolveType; +import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow; + +/** + * FlowNameResolver 单测(F2-14):三级解析顺序正反例。 + * mock JdbcTemplate,不连库。 + */ +class FlowNameResolverTest { + + private JdbcTemplate jdbc; + private SynthesizedFlowRegistry registry; + private FlowNameResolver resolver; + + @BeforeEach + void setUp() { + jdbc = mock(JdbcTemplate.class); + registry = new SynthesizedFlowRegistry(); + resolver = new FlowNameResolver(jdbc, registry); + } + + // ── 第一级:UUID ────────────────────────────────────────────────────────── + + @Test + @DisplayName("UUID 格式 → UUID_PASSTHROUGH,不查库") + void uuidPassthrough() { + String uuid = "550e8400-e29b-41d4-a716-446655440000"; + ResolvedFlow r = resolver.resolve(uuid); + assertEquals(ResolveType.UUID_PASSTHROUGH, r.type()); + verify(jdbc, never()).queryForList(anyString(), any(Object[].class)); + verify(jdbc, never()).queryForObject(anyString(), any(Class.class), any(Object[].class)); + } + + @Test + @DisplayName("大写 UUID 也走 UUID_PASSTHROUGH") + void uuidUppercasePassthrough() { + String uuid = "550E8400-E29B-41D4-A716-446655440000"; + ResolvedFlow r = resolver.resolve(uuid); + assertEquals(ResolveType.UUID_PASSTHROUGH, r.type()); + } + + // ── 第二级:_SEARCH 合成 ───────────────────────────────────────────────── + + @Test + @DisplayName("_SEARCH 后缀且实体存在 → SYNTHESIZED,返回非空 FlowDefinition") + void searchSuffixWithEntitySynthesized() { + // SYS_ENTITY 中有 VIEW_JGGL + when(jdbc.queryForList( + contains("sys_entity"), + eq("VIEW_JGGL"))) + .thenReturn(List.of(Map.of( + "sys_entity_id", "c6443e67-96a3-4947-81a2-df5669283ae0", + "name", "质量管理表单虚拟视图"))); + + ResolvedFlow r = resolver.resolve("VIEW_JGGL_SEARCH"); + assertEquals(ResolveType.SYNTHESIZED, r.type()); + assertNotNull(r.definition()); + assertEquals("VIEW_JGGL_SEARCH", r.definition().getKey()); + } + + @Test + @DisplayName("_SEARCH 后缀但实体不存在 → 走第3级(命名查询),不命中 → ORPHAN") + void searchSuffixEntityNotFound_fallsToOrphan() { + // 实体不存在 + when(jdbc.queryForList(contains("sys_entity"), anyString())) + .thenReturn(Collections.emptyList()); + // sys_serviceflow 也没有 + when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class), anyString())) + .thenReturn(0); + + ResolvedFlow r = resolver.resolve("UNKNOWN_TABLE_SEARCH"); + assertEquals(ResolveType.ORPHAN, r.type()); + } + + @Test + @DisplayName("_SEARCH 合成结果缓存:第二次 resolve 不再查库") + void searchResultIsCached() { + when(jdbc.queryForList(contains("sys_entity"), eq("SYS_USER"))) + .thenReturn(List.of(Map.of( + "sys_entity_id", "2e99cd67-5cec-48cb-8232-6555b242b2ea", + "name", "用户"))); + + resolver.resolve("SYS_USER_SEARCH"); + resolver.resolve("SYS_USER_SEARCH"); + + // queryForList 只调一次(第二次命中缓存) + verify(jdbc, org.mockito.Mockito.times(1)) + .queryForList(contains("sys_entity"), eq("SYS_USER")); + } + + @Test + @DisplayName("小写 _search 后缀也走合成路径(大小写不敏感)") + void searchSuffixCaseInsensitive() { + when(jdbc.queryForList(contains("sys_entity"), eq("VIEW_JGGL"))) + .thenReturn(List.of(Map.of( + "sys_entity_id", "c6443e67-96a3-4947-81a2-df5669283ae0", + "name", "质量管理表单"))); + + ResolvedFlow r = resolver.resolve("view_jggl_search"); + assertEquals(ResolveType.SYNTHESIZED, r.type()); + } + + // ── 第三级:命名服务 ───────────────────────────────────────────────────── + + @Test + @DisplayName("非 UUID 非 _SEARCH 且在 sys_serviceflow → NAMED_HIT") + void namedServiceHit() { + when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class), + eq("loadTreeChild"))) + .thenReturn(1); + + ResolvedFlow r = resolver.resolve("loadTreeChild"); + assertEquals(ResolveType.NAMED_HIT, r.type()); + } + + @Test + @DisplayName("命名服务不在 sys_serviceflow → ORPHAN") + void namedServiceOrphan() { + when(jdbc.queryForObject(contains("sys_serviceflow"), eq(Integer.class), + eq("GHOST_SERVICE"))) + .thenReturn(0); + + ResolvedFlow r = resolver.resolve("GHOST_SERVICE"); + assertEquals(ResolveType.ORPHAN, r.type()); + } + + // ── 写操作后缀拒绝 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("_SAVE 后缀 → WRITE_REDIRECT,不查库") + void saveSuffixWriteRedirect() { + ResolvedFlow r = resolver.resolve("SYS_USER_SAVE"); + assertEquals(ResolveType.WRITE_REDIRECT, r.type()); + verify(jdbc, never()).queryForList(anyString(), any(Object[].class)); + } + + @Test + @DisplayName("_UPDATE 后缀 → WRITE_REDIRECT") + void updateSuffixWriteRedirect() { + assertEquals(ResolveType.WRITE_REDIRECT, resolver.resolve("SYS_ROLE_UPDATE").type()); + } + + @Test + @DisplayName("_DELETE 后缀 → WRITE_REDIRECT") + void deleteSuffixWriteRedirect() { + assertEquals(ResolveType.WRITE_REDIRECT, resolver.resolve("VIEW_JGGL_DELETE").type()); + } + + // ── null / 空 ────────────────────────────────────────────────────────────── + + @Test + @DisplayName("null flowId → ORPHAN") + void nullFlowId() { + assertEquals(ResolveType.ORPHAN, resolver.resolve(null).type()); + } + + @Test + @DisplayName("空白 flowId → ORPHAN") + void blankFlowId() { + assertEquals(ResolveType.ORPHAN, resolver.resolve(" ").type()); + } + + // ── evict 逻辑 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("evict 后再次 resolve _SEARCH 重新合成(不命中缓存)") + void evictClearsCache() { + when(jdbc.queryForList(contains("sys_entity"), eq("SYS_ROLE"))) + .thenReturn(List.of(Map.of( + "sys_entity_id", "5ee1bb3a-b654-4d32-9c6c-529b0b273683", + "name", "角色"))); + + resolver.resolve("SYS_ROLE_SEARCH"); // 填充缓存 + resolver.evict("SYS_ROLE"); // 失效 + resolver.resolve("SYS_ROLE_SEARCH"); // 应重新查库 + + verify(jdbc, org.mockito.Mockito.times(2)) + .queryForList(contains("sys_entity"), eq("SYS_ROLE")); + } +} diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java index 3ac1ee9..07f0b01 100644 --- a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/FlowControllerTest.java @@ -2,6 +2,7 @@ package com.eip4.platform.metadata.web; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -17,17 +18,23 @@ import java.util.Properties; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import com.dsasp.server.common.core.FlowDefinition; import com.dsasp.server.common.core.service.FlowExcuteService; import com.dsasp.server.common.dataDic.bean.GeneralPOJO; import com.dsasp.server.common.dataDic.service.POJOCRUDService; +import com.eip4.platform.metadata.flow.FlowNameResolver; +import com.eip4.platform.metadata.flow.FlowNameResolver.ResolveType; +import com.eip4.platform.metadata.flow.FlowNameResolver.ResolvedFlow; /** - * 服务流 REST 门面单测(mock 引擎,不连库)。 + * 服务流 REST 门面单测(mock 引擎 + mock 解析器,不连库)。 * - *

    验证 {@link FlowController} 的入参绑定(GET query → map / POST body → map)与 - * 响应归一化:GeneralPOJO → 平面行、listSelect 结果({listresult,pagecount})→ - * amis {items,total}、嵌套结构递归归一化。这是 D 类报表服务流 REST 化契约的核心。 + *

    验证 {@link FlowController} 在 F2-14 三级解析各路径下的行为: + * UUID/命名命中 → 200 执行,_SEARCH 合成 → 200 执行,写后缀/_孤儿 → 404。 + * 同时验证 amis 响应归一化(GeneralPOJO → 平面行、listSelect → {items,total})。 */ class FlowControllerTest { @@ -44,68 +51,99 @@ class FlowControllerTest { return p; } + /** 构造解析器 mock,对给定 flowId 返回指定类型。 */ + private FlowNameResolver resolverReturning(String flowId, ResolvedFlow result) { + FlowNameResolver resolver = mock(FlowNameResolver.class); + when(resolver.resolve(flowId)).thenReturn(result); + return resolver; + } + + /** UUID_PASSTHROUGH 解析结果 */ + private static ResolvedFlow uuidPassthrough() { + return ResolvedFlow.UUID_PASSTHROUGH; + } + + /** NAMED_HIT 解析结果 */ + private static ResolvedFlow namedHit() { + return ResolvedFlow.NAMED_HIT; + } + + /** SYNTHESIZED 解析结果(带 mock FlowDefinition) */ + @SuppressWarnings("unchecked") + private static ResolvedFlow synthesized(String key) { + FlowDefinition fd = mock(FlowDefinition.class); + when(fd.getKey()).thenReturn(key); + return new ResolvedFlow(ResolveType.SYNTHESIZED, fd, null); + } + @Test - @DisplayName("1. GET 执行:query 参数透传为入参 map,flowId 透传给引擎") + @DisplayName("1. UUID_PASSTHROUGH: GET query 参数透传为入参 map,flowId 透传给引擎") void getPassesQueryParamsAsMap() { + String flowId = "EIP4M0_USERGROUP_SEARCH"; FlowExcuteService engine = mock(FlowExcuteService.class); - when(engine.excute(any(), any(), eq("EIP4M0_USERGROUP_SEARCH"))).thenReturn(new HashMap<>()); - FlowController controller = new FlowController(engine); + when(engine.excute(any(), any(), eq(flowId))).thenReturn(new HashMap<>()); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); Map params = new HashMap<>(); params.put("NAME", "管理员组"); - controller.executeGet("EIP4M0_USERGROUP_SEARCH", params); + controller.executeGet(flowId, params); @SuppressWarnings("unchecked") ArgumentCaptor> mapCap = ArgumentCaptor.forClass(Map.class); - org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(Properties.class), eq("EIP4M0_USERGROUP_SEARCH")); + org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(Properties.class), eq(flowId)); assertEquals("管理员组", mapCap.getValue().get("NAME"), "query 参数应进入入参 map"); } @Test @DisplayName("2. POST 执行:JSON body 透传为入参 map") void postPassesBodyAsMap() { + String flowId = "COMMON_SQL_QUERY"; FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(new HashMap<>()); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); Map body = new HashMap<>(); body.put("sql", "select 1"); - controller.executePost("COMMON_SQL_QUERY", body); + controller.executePost(flowId, body); @SuppressWarnings("unchecked") ArgumentCaptor> mapCap = ArgumentCaptor.forClass(Map.class); - org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(), eq("COMMON_SQL_QUERY")); + org.mockito.Mockito.verify(engine).excute(mapCap.capture(), any(), eq(flowId)); assertEquals("select 1", mapCap.getValue().get("sql")); } @Test - @DisplayName("3. POST body 为 null:按空 map 执行,不抛") + @DisplayName("3. POST body 为 null:按空 map 执行,返回 200") void postNullBodyTolerant() { + String flowId = "F"; FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(null); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, uuidPassthrough())); - Map resp = controller.executePost("F", null); - assertEquals(0, resp.get("status")); + ResponseEntity> resp = controller.executePost(flowId, null); + assertEquals(HttpStatus.OK, resp.getStatusCode()); + assertEquals(0, resp.getBody().get("status")); } @Test @DisplayName("4. 响应外壳:status=0/msg/data 三段") void responseEnvelope() { + String flowId = "F"; FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(new HashMap<>()); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); - Map resp = controller.executeGet("F", new HashMap<>()); - assertEquals(0, resp.get("status")); - assertEquals("", resp.get("msg")); - assertEquals(true, resp.containsKey("data")); + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); + assertEquals(HttpStatus.OK, resp.getStatusCode()); + assertEquals(0, resp.getBody().get("status")); + assertEquals("", resp.getBody().get("msg")); + assertNotNull(resp.getBody().get("data")); } @Test @DisplayName("5. listSelect 结果归一化:{listresult,pagecount} → {items,total}") void normalizeListSelectResult() { - // 引擎输出:output 字段 result = listSelect 结果 map + String flowId = "F"; Map listResult = new LinkedHashMap<>(); List rows = new ArrayList<>(); Map c1 = new LinkedHashMap<>(); @@ -119,11 +157,11 @@ class FlowControllerTest { FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(output); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, uuidPassthrough())); - Map resp = controller.executeGet("F", new HashMap<>()); + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); @SuppressWarnings("unchecked") - Map data = (Map) resp.get("data"); + Map data = (Map) resp.getBody().get("data"); @SuppressWarnings("unchecked") Map result = (Map) data.get("result"); assertEquals(1, result.get("total"), "pagecount → total"); @@ -137,17 +175,18 @@ class FlowControllerTest { @Test @DisplayName("6. 单个 GeneralPOJO 输出归一化为平面行") void normalizeSinglePojo() { + String flowId = "F"; Map cols = new LinkedHashMap<>(); cols.put("NAME", "x"); GeneralPOJO row = fakeRow("id-1", cols); FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(row); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); - Map resp = controller.executeGet("F", new HashMap<>()); + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); @SuppressWarnings("unchecked") - Map data = (Map) resp.get("data"); + Map data = (Map) resp.getBody().get("data"); assertEquals("id-1", data.get("_id")); assertEquals("x", data.get("NAME")); } @@ -155,28 +194,70 @@ class FlowControllerTest { @Test @DisplayName("7. List 直接输出:递归归一化为行列表") void normalizeListOfPojo() { + String flowId = "F"; Map cols = new LinkedHashMap<>(); cols.put("NAME", "y"); List list = List.of(fakeRow("id-2", cols)); FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(list); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, uuidPassthrough())); - Map resp = controller.executeGet("F", new HashMap<>()); + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); @SuppressWarnings("unchecked") - List> data = (List>) resp.get("data"); + List> data = (List>) resp.getBody().get("data"); assertEquals("y", data.get(0).get("NAME")); } @Test @DisplayName("8. 标量输出原样返回(非 POJO/Map/List)") void normalizeScalar() { + String flowId = "F"; FlowExcuteService engine = mock(FlowExcuteService.class); when(engine.excute(any(), any(), any())).thenReturn(42); - FlowController controller = new FlowController(engine); + FlowController controller = new FlowController(engine, resolverReturning(flowId, namedHit())); - Map resp = controller.executeGet("F", new HashMap<>()); - assertEquals(42, resp.get("data")); + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); + assertEquals(42, resp.getBody().get("data")); + } + + @Test + @DisplayName("9. SYNTHESIZED: 合成流按 flow.getKey() 调引擎,返回 200") + void synthesizedCallsEngineWithFlowKey() { + String flowId = "VIEW_JGGL_SEARCH"; + String flowKey = "VIEW_JGGL_SEARCH"; + FlowExcuteService engine = mock(FlowExcuteService.class); + when(engine.excute(any(), any(), eq(flowKey))).thenReturn(new HashMap<>()); + FlowController controller = new FlowController(engine, resolverReturning(flowId, synthesized(flowKey))); + + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); + assertEquals(HttpStatus.OK, resp.getStatusCode()); + assertEquals(0, resp.getBody().get("status")); + org.mockito.Mockito.verify(engine).excute(any(), any(), eq(flowKey)); + } + + @Test + @DisplayName("10. ORPHAN: 孤儿服务名 → 404 + status=1") + void orphanReturns404() { + String flowId = "NONEXISTENT_FLOW"; + FlowExcuteService engine = mock(FlowExcuteService.class); + FlowController controller = new FlowController(engine, resolverReturning(flowId, ResolvedFlow.ORPHAN)); + + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); + assertEquals(HttpStatus.NOT_FOUND, resp.getStatusCode()); + assertEquals(1, resp.getBody().get("status")); + } + + @Test + @DisplayName("11. WRITE_REDIRECT: _SAVE 后缀 → 404 + 引导提示") + void writeSuffixReturns404() { + String flowId = "SYS_USER_SAVE"; + FlowExcuteService engine = mock(FlowExcuteService.class); + FlowController controller = new FlowController(engine, resolverReturning(flowId, ResolvedFlow.WRITE_REDIRECT)); + + ResponseEntity> resp = controller.executeGet(flowId, new HashMap<>()); + assertEquals(HttpStatus.NOT_FOUND, resp.getStatusCode()); + assertEquals(1, resp.getBody().get("status")); + assertNotNull(resp.getBody().get("msg")); } }