F2-14: 服务名解析运行时——默认搜索流合成,修 76% 页面取数链路

- 根因:1,141/1,493 页面取数 api=/api/flow/{表}_SEARCH 引用老引擎按实体运行时
  合成的默认服务(不在 sys_serviceflow 表);原 FlowController 仅按 PK 查→全部 500,
  被前端空态静默掩盖,渲染验证/API 扫描均未暴露
- FlowNameResolver 三级解析:UUID→sys_serviceflow PK / <TABLE>_SEARCH 且实体存在
  →DefaultFlowHelper.getDefaultSearch 合成(保真层原样,listSelect 行级权限) /
  命名服务→contentxml flow id 索引;孤儿 404 带日志,_SAVE/_UPDATE/_DELETE 拒绝
  (写路径走 /api/entity/{x}/save 单轨)
- 实测:SYS_ROLE_SEARCH 200 返回真实数据(合成+行级权限全通);599/673 个 _SEARCH
  目标库内可解析(89%),余 74 个缺 PG 对象(44 个 VIEW_ 视图+30 表)属数据完整性
  问题另行处理;单测 128 全绿(+14);e2e 34/34
- 教训(手册):默认服务是运行时合成不在表里;「渲染通过/接口200」≠「取数通」,
  验收必须断言数据非空

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 00:14:58 +08:00
parent b412022f4b
commit bed42685bb
6 changed files with 695 additions and 47 deletions

View File

@@ -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}。
*
* <p>解析顺序:
* <ol>
* <li><b>UUID</b>:36 位标准 UUID 格式 → 直接返回 null,由调用方按 PK 查 sys_serviceflow(现状逻辑不变)。</li>
* <li><b>默认搜索</b>:形如 {@code <TABLE>_SEARCH},且 TABLE 存在于 SYS_ENTITY →
* 调用 {@link DefaultFlowHelper#getDefaultSearch} 运行时合成 FlowDefinition。
* 合成结果走 Caffeine 缓存(maxSize 2000);{@link #evict(String)} 与
* {@code /api/meta/evict} 钩子对齐。</li>
* <li><b>其余命名</b>:按 sys_serviceflow_id 列精确查(主键查,O(1),无需 XML 扫描)→
* 命中返回哨兵 {@link ResolvedFlow#NAMED_HIT}(调用方用原始名按 PK 直接执行);
* 不命中返回 {@link ResolvedFlow#ORPHAN}(调用方应返回 404)。</li>
* </ol>
*
* <p>写操作后缀拒绝:{@code _SAVE/_UPDATE/_DELETE} 结尾的名字(非 UUID 且无法按 _SEARCH 路径处理)
* 返回 {@link ResolvedFlow#WRITE_REDIRECT},调用方应引导使用 /api/entity/{x}/save 端点。
*
* <p><b>零改 com.dsasp 文件</b>: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<String, FlowDefinition<?>> 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<Map<String, Object>> 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_\\-]", "?");
}
}

View File

@@ -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。
*
* <p>加 {@code @Primary} 使 {@link com.dsasp.server.core.service.FlowExcuteServiceImpl}
* 的 {@code @Autowired FlowService} 注入本类而非 FlowServiceImpl,
* 从而在不改任何保真层文件的前提下插入合成流查找逻辑。
*
* <p>其余 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);
}
}

View File

@@ -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} 查库的逻辑。
*
* <p>线程安全:ConcurrentHashMap,不需要额外同步。
* 合成流的生命周期由 {@link FlowNameResolver} 的 Caffeine 缓存管理(evict 对齐),
* 本注册表作为执行时临时路由层,put 后不主动 remove(同一 key 重复 put 幂等)。
*/
@Component
public class SynthesizedFlowRegistry {
private final ConcurrentHashMap<String, FlowDefinition<?>> 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();
}
}

View File

@@ -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;
* </ul>
* 这正是报表方案 D 节 echart.jsp 第 25 行 {@code flowService.excute(map, UserSession.get(), flowid)} 的 REST 化。
*
* <p><b>F2-14 服务名解析</b>:{@link FlowNameResolver} 在引擎调用前三级解析服务名:
* UUID → 原样走引擎 PK 查;{@code <TABLE>_SEARCH} 且 TABLE 在 SYS_ENTITY →
* 运行时合成默认搜索流;其余命名服务 → 按 sys_serviceflow_id 精确查;孤儿 → 404。
*
* <p><b>读写时机判断(REST 入口仅放行查询类服务流):</b>当前服务流引擎本身不区分读写——
* 一个流既可挂 {@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<String, Object> executeGet(@PathVariable String id,
@RequestParam Map<String, String> allParams) {
public ResponseEntity<Map<String, Object>> executeGet(@PathVariable String id,
@RequestParam Map<String, String> allParams) {
Map<String, Object> 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<String, Object> executePost(@PathVariable String id,
@RequestBody(required = false) Map<String, Object> body) {
public ResponseEntity<Map<String, Object>> executePost(@PathVariable String id,
@RequestBody(required = false) Map<String, Object> body) {
Map<String, Object> 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 三级解析)。
*
* <ol>
* <li>UUID → 原样传给引擎,按 PK 查 sys_serviceflow(现状逻辑)。</li>
* <li>{@code <TABLE>_SEARCH} 且 TABLE 在 SYS_ENTITY → 运行时合成搜索流并直接执行。</li>
* <li>其余命名服务存在于 sys_serviceflow → 用原名传给引擎(PK 即名字)。</li>
* <li>写操作后缀 (_SAVE/_UPDATE/_DELETE) → 404 + 引导提示。</li>
* <li>孤儿 → 404 + 明确错误体。</li>
* </ol>
*/
private Map<String, Object> run(String id, Map<String, Object> map) {
Properties ctx = UserSession.getAdmin();
Object output = flowExcuteService.excute(map, ctx, id);
private ResponseEntity<Map<String, Object>> run(String id, Map<String, Object> map) {
ResolvedFlow resolved = flowNameResolver.resolve(id);
Map<String, Object> 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<String, Object> err = new LinkedHashMap<>();
err.put("status", 1);
err.put("msg", resolved.message());
yield ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
}
case ORPHAN -> {
Map<String, Object> err = new LinkedHashMap<>();
err.put("status", 1);
err.put("msg", "服务不存在: " + sanitize(id));
yield ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
}
};
}
private ResponseEntity<Map<String, Object>> ok(Object output) {
Map<String, Object> 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,需手工展平)。 */