From 992adae9f6589985ba9f6b8d1c989e9850d19f04 Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Fri, 4 Dec 2026 09:35:13 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E7=BB=9F=E4=B8=80=E5=A4=9A?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E6=93=8D=E4=BD=9C=E8=80=85=E7=BD=91=E5=85=B3?= =?UTF-8?q?=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FlowOperatorGateway 与 IRepositoryHolder 改用 OperatorKey 查询,移除静默丢弃身份的默认重载;脚本解析器与流程树改为一次批量回查完整参与人列表,并同步缓存、示例和集成文档。 Closes #315 --- docs/Integration/operator-identity.md | 34 ++-- docs/Integration/user-integration.md | 66 ++++--- .../flow-engine-framework/gateway-context.md | 50 ++--- .../com/codingapi/example/entity/User.java | 4 +- .../gateway/impl/FlowOperatorGatewayImpl.java | 62 +++---- .../flow/action/actions/PassAction.java | 9 +- .../cache/FlowOperatorLocalThreadCache.java | 144 ++++++--------- .../flow/context/GatewayContext.java | 90 ++++----- .../flow/context/RepositoryHolderContext.java | 35 +--- .../diagnostic/OperatorIdentityWarnLog.java | 8 +- .../flow/gateway/FlowOperatorGateway.java | 55 +++--- .../flow/mock/MockRepositoryHolder.java | 36 +--- .../codingapi/flow/node/nodes/StartNode.java | 3 +- .../OperatorScriptResultResolver.java | 2 +- .../script/operator/PendingOperators.java | 36 ++-- .../flow/script/runtime/IBeanFactory.java | 3 +- .../flow/service/impl/FlowActionService.java | 7 +- .../flow/service/impl/FlowCreateService.java | 4 +- .../service/impl/FlowDelayTriggerService.java | 7 +- .../flow/service/impl/FlowDetailService.java | 12 +- .../service/impl/FlowForceSyncService.java | 4 +- .../service/impl/FlowProcessNodeService.java | 83 ++++----- .../flow/service/impl/FlowReissueService.java | 6 +- .../impl/FlowSubProcessResetService.java | 3 +- .../flow/service/impl/FlowUrgeService.java | 2 +- .../impl/SubProcessSessionFactory.java | 13 +- .../flow/session/IRepositoryHolder.java | 42 ++--- .../strategy/node/OperatorLoadStrategy.java | 2 +- .../cache/FlowOperatorBulkIdentityTest.java | 118 +++--------- .../FlowOperatorLocalThreadCacheTest.java | 25 +-- .../gateway/FlowOperatorKeyGatewayTest.java | 173 ++++++++++++++++++ .../flow/gateway/impl/UserGateway.java | 47 ++--- .../OperatorScriptResultResolverTest.java | 12 +- ...FlowIssue210SubProcessPerformanceTest.java | 11 +- 34 files changed, 602 insertions(+), 606 deletions(-) create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/gateway/FlowOperatorKeyGatewayTest.java diff --git a/docs/Integration/operator-identity.md b/docs/Integration/operator-identity.md index 5df26680..ed4cd81e 100644 --- a/docs/Integration/operator-identity.md +++ b/docs/Integration/operator-identity.md @@ -71,32 +71,30 @@ public class User implements IFlowOperator { ### 3.2 让网关按身份返回操作者(关键) +`FlowOperatorGateway` 以 `OperatorKey` 作为参与人查询契约,业务方必须实现: + +- `get(OperatorKey key)`:按人员与身份获取一个操作者; +- `findByKeys(List keys)`:按完整参与人列表批量获取,允许同一人员对应多个身份。 + +默认身份的 `get(long)` / `findByIds(List)` 是便捷方法,内部统一转换为 `OperatorKey.ofDefault(...)`。 + ```java @Override -public IFlowOperator get(long id, String identity) { - User user = userRepository.getUserById(id); - if (user == null || OperatorIdentity.of(identity).isDefault()) { +public IFlowOperator get(OperatorKey key) { + User user = userRepository.getUserById(key.operatorId()); + if (user == null || OperatorIdentity.of(key.identity()).isDefault()) { return user; } // 必须复制:直接改写实体会污染持久化上下文 / 线程缓存,导致同一 id 的两个身份互相覆盖 - return user.withIdentity(identity); + return user.withIdentity(key.identity()); } ``` -> `get(long, String)` 在接口上是 `default` 方法,默认退化为 `get(id)`(忽略身份)。**不实现它时,请求里声明的身份不会被写入记录** —— 引擎的身份来源是操作者对象本身,而不是请求参数。多身份场景必须实现此方法。 - -批量取人同样提供了两个 `default` 重载,用于流程树与人员设定场景(建议一并覆盖,避免同一批人按身份回查时退化为默认身份): - -| 接口 | 新增方法 | 未覆盖时的行为 | -|------|----------|----------------| -| `FlowOperatorGateway` | `findByIds(List, String)` | 退化为 `findByIds(ids)` | -| `IRepositoryHolder` | `findOperatorByIds(List, String)` | 退化为 `findOperatorByIds(ids)` | -| `IRepositoryHolder` | `getOperatorById(long, String)` | 退化为 `getOperatorById(id)` | +批量实现必须返回与请求身份一致的操作者,并按入参顺序返回;查不到的参与人跳过。`IRepositoryHolder` 同步使用 `getOperatorByKey(OperatorKey)` / `findOperatorsByKeys(List)`,不再提供拆分身份参数的默认重载。 -> 引擎做了两层兜底,保证「没覆盖」不会静默丢身份: +> 身份不一致时不会静默降级:单条读取按 `(人员id, 身份)` 去重输出 WARN;显式非默认身份的批量结果不会登记线程缓存,也不会作为该参与人的查询结果返回。默认身份读取保留历史兼容行为。 > -> 1. **单条路径**:`GatewayContext#getFlowOperator(id, identity)`、发起(`FlowCreateService`)与审批(`FlowActionService`)三个入口都会做运行期检查——请求声明了非默认身份、但回查到的操作者身份为空时,按 `(人员id, 身份)` 去重输出一条 WARN; -> 2. **批量路径**:`GatewayContext#findByIds(ids, identity)` 发现批量结果身份不符时,逐条回退到单条按身份取人(正确实现会返回带身份的副本,未实现则触发上面的 WARN),同时不把身份不符的对象登记进线程缓存,避免污染后续按身份的读取。 +> **升级提示**:自行实现 `FlowOperatorGateway` 的下游需要把 `get(long, String)` 迁移为 `get(OperatorKey)`,把 `findByIds(List, String)` 迁移为 `findByKeys(List)`。这是有意的源码不兼容调整,避免“编译通过但身份被丢弃”。 ### 3.3 请求声明身份 @@ -432,8 +430,8 @@ codingapi.flow.identity.match-mode=USER_ONLY `identityScope=LOCKED`,此时步骤 4 才会变成「只显示当前身份下的记录」,跨身份办理也会被拒绝 (`state.operator.notMatch`)。 -示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(id, identity)` / -`findByIds(ids, identity)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 +示例的 `User.identity` 是 `@Transient`(运行期身份,不落库),由 `FlowOperatorGateway#get(OperatorKey)` / +`findByKeys(List)` 返回带身份的副本。真实项目把身份选项换成自己的组织模型即可。 ### 5.3 常见疑问:为什么「审批人是 admin」却在自己的待办里找不到 diff --git a/docs/Integration/user-integration.md b/docs/Integration/user-integration.md index 46987443..a9bcbc45 100644 --- a/docs/Integration/user-integration.md +++ b/docs/Integration/user-integration.md @@ -13,27 +13,24 @@ package com.codingapi.flow.gateway; /** 流程操作者防腐层 */ public interface FlowOperatorGateway { - IFlowOperator get(long id); + IFlowOperator get(OperatorKey key); - /** 按 (id, identity) 取用户,default 退化为 get(id);多身份场景需覆盖(见「多身份参与」) */ - default IFlowOperator get(long id, String identity) { - return get(id); - } + List findByKeys(List keys); - List findByIds(List ids); + default IFlowOperator get(long id) { + return get(OperatorKey.ofDefault(id)); + } - /** 按 (ids, identity) 批量取用户,default 退化为 findByIds(ids);多身份场景需一并覆盖 */ - default List findByIds(List ids, String identity) { - return findByIds(ids); + default List findByIds(List ids) { + return findByKeys(ids.stream().map(OperatorKey::ofDefault).toList()); } } ``` 引擎所有「按 id 取用户 / 批量取用户」的请求都汇聚到这个接口。**框架不提供默认实现**(`flow-engine-starter-infra` 也不提供),必须由业务方提供一个 Spring Bean。 -> 同一人员以多个身份参与流程时(例如同时隶属两个部门),需要覆盖 `get(long, String)`; -> 流程树、人员设定等批量路径还需要覆盖 `findByIds(List, String)`,只覆盖单条会让批量路径退化为默认身份。 -> 详见 [多身份参与](./operator-identity.md) 3.2。 +> 同一人员以多个身份参与流程时(例如同时隶属两个部门),`get(OperatorKey)` 与 `findByKeys(List)` 必须返回身份匹配的操作者。 +> 接口不再提供忽略身份的默认重载,避免下游编译通过但运行期丢失身份。迁移说明见 [多身份参与](./operator-identity.md) 3.2。 ### 1.2 `IFlowOperator`(流程操作人) @@ -76,17 +73,24 @@ public class GatewayContext { @Setter @Getter private FlowOperatorGateway flowOperatorGateway; public IFlowOperator getFlowOperator(long userId) { - return FlowOperatorLocalThreadCache.getInstance().get(userId, () -> flowOperatorGateway.get(userId)); + return getFlowOperator(OperatorKey.ofDefault(userId)); + } + public IFlowOperator getFlowOperator(OperatorKey key) { + return FlowOperatorLocalThreadCache.getInstance().get(key, () -> flowOperatorGateway.get(key)); } public List findByIds(List ids) { - return FlowOperatorLocalThreadCache.getInstance().find(ids, (idList) -> flowOperatorGateway.findByIds(idList)); + return findByKeys(ids.stream().map(OperatorKey::ofDefault).toList()); + } + public List findByKeys(List keys) { + return FlowOperatorLocalThreadCache.getInstance().find(keys, + missingKeys -> flowOperatorGateway.findByKeys(missingKeys)); } } ``` - **注入方式**:`GatewayContext.getInstance().setFlowOperatorGateway(bean)`,由 starter 的 `GatewayContextRegister`(`InitializingBean`)在启动时执行。 - **线程缓存** `FlowOperatorLocalThreadCache`(`flow-engine-framework/.../cache/FlowOperatorLocalThreadCache.java`):`ThreadLocal>`,未命中时调用网关并回写;`find` 会过滤 null/<=0 的 id、去重、保序返回(保证多人审批顺序稳定)。缓存键由 `OperatorKey#key()` 生成,**含身份**。`FlowService` 每个操作入口都会 `clear()` 该缓存。 -- **带身份的读取**:`GatewayContext.getFlowOperator(userId, identity)` / `findByIds(ids, identity)` 是新增重载;批量结果身份不符时会逐条回退单条按身份回查(见 [多身份参与](./operator-identity.md) 3.2)。 +- **带身份的读取**:统一使用 `GatewayContext.getFlowOperator(OperatorKey)` / `findByKeys(List)`;批量查询支持同一人员多个身份,显式非默认身份不一致的结果不会入库缓存(见 [多身份参与](./operator-identity.md) 3.2)。 ## 3. 集成示例(完整可运行) @@ -161,10 +165,16 @@ package com.codingapi.example.gateway.impl; import com.codingapi.example.repository.UserRepository; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.AllArgsConstructor; import org.springframework.stereotype.Repository; +import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; @Repository @AllArgsConstructor @@ -173,15 +183,29 @@ public class FlowOperatorGatewayImpl implements FlowOperatorGateway { private final UserRepository userRepository; @Override - public IFlowOperator get(long id) { - return userRepository.getUserById(id); + public IFlowOperator get(OperatorKey key) { + User user = userRepository.getUserById(key.operatorId()); + if (user == null || OperatorIdentity.of(key.identity()).isDefault()) { + return user; + } + return user.withIdentity(key.identity()); } @Override - public List findByIds(List ids) { - return userRepository.findUserByIdIn(ids).stream() - .map(user -> (IFlowOperator) user) - .toList(); + public List findByKeys(List keys) { + List ids = keys.stream().map(OperatorKey::operatorId).distinct().toList(); + Map users = userRepository.findUserByIdIn(ids).stream() + .collect(Collectors.toMap(User::getUserId, Function.identity())); + List operators = new ArrayList<>(); + for (OperatorKey key : keys) { + User user = users.get(key.operatorId()); + if (user == null) { + continue; + } + operators.add(OperatorIdentity.of(key.identity()).isDefault() + ? user : user.withIdentity(key.identity())); + } + return operators; } } ``` diff --git a/docs/capabilities/flow-engine-framework/gateway-context.md b/docs/capabilities/flow-engine-framework/gateway-context.md index 365ad028..ea22deea 100644 --- a/docs/capabilities/flow-engine-framework/gateway-context.md +++ b/docs/capabilities/flow-engine-framework/gateway-context.md @@ -27,7 +27,7 @@ content_hash: 9a35fe960766c3a944ad60043ea71ccd5915e14add45650eed22e6771b95473b | 组件 | 职责 | |------|------| -| `FlowOperatorGateway` | 网关接口,定义 `get(userId)` 和 `findByIds(ids)` 方法 | +| `FlowOperatorGateway` | 网关接口,定义 `get(OperatorKey)` 和 `findByKeys(keys)` 方法;默认身份便捷方法由它们派生 | | `GatewayContext` | 单例上下文,持有 `FlowOperatorGateway` 实现 | | `FlowOperatorLocalThreadCache` | ThreadLocal 缓存,同请求内缓存操作者信息 | @@ -37,48 +37,32 @@ content_hash: 9a35fe960766c3a944ad60043ea71ccd5915e14add45650eed22e6771b95473b ```java public interface FlowOperatorGateway { - IFlowOperator get(long userId); - List findByIds(List ids); + IFlowOperator get(OperatorKey key); + List findByKeys(List keys); } ``` -> 多身份场景还需覆盖两个 `default` 重载 `get(long, String)` 与 `findByIds(List, String)`; -> 不覆盖时它们退化为忽略身份的上面两个方法,请求里声明的身份不会写入记录。 +> 参与人统一由 `OperatorKey` 表达,批量查询允许同一人员对应多个身份。接口不提供忽略身份的重载; +> 默认身份便捷方法 `get(long)` / `findByIds(List)` 内部转换为 `OperatorKey.ofDefault(...)`。 > 详见 [多身份参与](../../Integration/operator-identity.md) 3.2。 ### 缓存机制 - 每次 `FlowService` 操作前调用 `FlowOperatorLocalThreadCache.clear()` 清理缓存 -- 同一请求内,通过 `GatewayContext.getFlowOperator(userId)` 获取操作者时自动缓存 -- 批量查询通过 `GatewayContext.findByIds(ids)` 获取,同样走缓存 +- 同一请求内,通过 `GatewayContext.getFlowOperator(OperatorKey)` 获取操作者时自动缓存 +- 批量查询通过 `GatewayContext.findByKeys(keys)` 获取,同样走缓存;显式非默认身份不一致的结果不会缓存 ## 使用实例 -```java -// 1. 实现网关接口(在业务项目中) -@Component -public class FlowOperatorGatewayImpl implements FlowOperatorGateway { - - @Autowired - private UserRepository userRepository; - - @Override - public IFlowOperator get(long userId) { - User user = userRepository.findById(userId); - return new FlowOperator(user.getId(), user.getName(), user.getDepartment()); - } - - @Override - public List findByIds(List ids) { - return userRepository.findAllById(ids).stream() - .map(u -> new FlowOperator(u.getId(), u.getName(), u.getDepartment())) - .toList(); - } -} +完整可运行的网关实现见 `flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java`。 -// 2. 通过 GatewayContext 获取操作者(自动缓存) -IFlowOperator operator = GatewayContext.getInstance().getFlowOperator(userId); - -// 3. 批量获取 -List operators = GatewayContext.getInstance().findByIds(userIds); +```java +// 按参与人获取(自动缓存) +IFlowOperator operator = GatewayContext.getInstance().getFlowOperator( + OperatorKey.of(userId, "department1")); + +// 混合身份批量获取(自动缓存,按入参顺序返回) +List operators = GatewayContext.getInstance().findByKeys(List.of( + OperatorKey.ofDefault(userId), + OperatorKey.of(userId, "department1"))); ``` diff --git a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java index 0cbc7e5b..11828028 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/entity/User.java @@ -42,8 +42,8 @@ public class User implements IFlowOperator { * 当前身份标识(issue #288)。 * *

同一个人员可能隶属多个部门/岗位,以不同身份参与流程。身份是**运行期选择**而非用户主数据, - * 因此不落库({@link Transient});由 {@code FlowOperatorGateway#get(id, identity)} 按身份返回 - * 携带该标识的用户副本,示例前端通过请求参数 {@code operatorIdentity} 声明当前身份。 + * 因此不落库({@link Transient});由 {@code FlowOperatorGateway#get(OperatorKey)} 按身份返回 + * 携带该标识的用户副本,示例前端通过请求头 {@code X-Operator-Identity} 声明当前身份。 * 不参与 {@code equals/hashCode},避免同一 id 的两个身份副本被判定为不同用户。 */ @Transient diff --git a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java index 0e595a31..5159afba 100644 --- a/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java +++ b/flow-engine-example/src/main/java/com/codingapi/example/gateway/impl/FlowOperatorGatewayImpl.java @@ -5,10 +5,15 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import lombok.AllArgsConstructor; import org.springframework.stereotype.Repository; +import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; @Repository @AllArgsConstructor @@ -16,51 +21,34 @@ public class FlowOperatorGatewayImpl implements FlowOperatorGateway { private final UserRepository userRepository; - @Override - public IFlowOperator get(long id) { - return userRepository.getUserById(id); - } - /** - * 按身份获取操作者(issue #288)。 - * - *

示例组织模型里身份就是「以哪个部门/岗位的身份参与流程」,不属于用户主数据, - * 因此这里返回携带身份标识的**用户副本**,而不改写持久化上下文中的实体实例。 - * 真实项目应把身份替换为自己的组织模型(例如按部门 id 查询岗位任职关系)。 + * 身份不属于用户主数据,因此返回携带身份的副本,不改写持久化实体。 */ @Override - public IFlowOperator get(long id, String identity) { - if (OperatorIdentity.of(identity).isDefault()) { - return get(id); - } - User user = userRepository.getUserById(id); - return user == null ? null : user.withIdentity(OperatorIdentity.of(identity).value()); + public IFlowOperator get(OperatorKey key) { + User user = userRepository.getUserById(key.operatorId()); + return withIdentity(user, key.identity()); } @Override - public List findByIds(List ids) { - return userRepository.findUserByIdIn(ids) - .stream() - .map(user -> (IFlowOperator) user) - .toList(); + public List findByKeys(List keys) { + List ids = keys.stream().map(OperatorKey::operatorId).distinct().toList(); + Map usersById = userRepository.findUserByIdIn(ids).stream() + .collect(Collectors.toMap(User::getUserId, Function.identity())); + List operators = new ArrayList<>(); + for (OperatorKey key : keys) { + IFlowOperator operator = withIdentity(usersById.get(key.operatorId()), key.identity()); + if (operator != null) { + operators.add(operator); + } + } + return operators; } - /** - * 按统一身份批量获取操作者(issue #288 衍生 / #293)。 - * - *

批量重载同样必须返回携带身份的副本:只覆盖单条 {@code get(id, identity)} 时, - * 流程树、人员设定等批量路径会把身份退化为默认身份。 - */ - @Override - public List findByIds(List ids, String identity) { - if (OperatorIdentity.of(identity).isDefault()) { - return findByIds(ids); + private IFlowOperator withIdentity(User user, String identity) { + if (user == null) { + return null; } - String normalized = OperatorIdentity.of(identity).value(); - return userRepository.findUserByIdIn(ids) - .stream() - .map(user -> (IFlowOperator) user.withIdentity(normalized)) - .toList(); + return OperatorIdentity.of(identity).isDefault() ? user : user.withIdentity(identity); } - } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java index 5a4b5194..b052940f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/PassAction.java @@ -17,6 +17,7 @@ import com.codingapi.flow.node.nodes.ManualNode; import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.response.ActionResponse; import com.codingapi.flow.pojo.response.NodeOption; import com.codingapi.flow.record.FlowRecord; @@ -205,8 +206,8 @@ public void run(FlowSession flowSession) { // 是否转交审批人的流程 if (isFinish && currentRecord.isForward()) { - IFlowOperator forwardOperator = repositoryHolder.getOperatorById( - currentRecord.getForwardOperatorId(), currentRecord.getForwardOperatorIdentity()); + IFlowOperator forwardOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + currentRecord.getForwardOperatorId(), currentRecord.getForwardOperatorIdentity())); FlowRecord notifyRecord = currentRecord.create(flowSession.updateSession(forwardOperator)); notifyRecord.notifyRecord(flowSession.updateSession(forwardOperator)); // 如果不存储这个记录,若下一流程是结束流程时,无法更新流程状态为结束状态。 @@ -218,8 +219,8 @@ public void run(FlowSession flowSession) { // 多人审批时其他待办可能尚未完成,若只在 isFinish 时返回,委派记录会永久滞留(issue #239) if (currentRecord.isDelegate()) { FlowRecord delegateRecord = repositoryHolder.getRecordById(currentRecord.getDelegateId()); - IFlowOperator delegateOperator = repositoryHolder.getOperatorById( - delegateRecord.getCurrentOperatorId(), delegateRecord.getCurrentOperatorIdentity()); + IFlowOperator delegateOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + delegateRecord.getCurrentOperatorId(), delegateRecord.getCurrentOperatorIdentity())); FlowRecord rebackRecord = delegateRecord.create(flowSession.updateSession(delegateOperator)); // 返回记录同样归属原委托记录的节点实例与审批槽位(issue #239) rebackRecord.inheritNodeInstance(delegateRecord); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java index 84c32cf8..a3ca8075 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCache.java @@ -10,15 +10,12 @@ import java.util.List; import java.util.Map; import java.util.function.Supplier; +import java.util.stream.Collectors; /** * 流程操作者线程缓存。 * - *

同一个人员可以以不同「身份」参与流程(issue #288),因此缓存键必须是 - * {@code (userId, identity)} 二元组而不是 userId:以身份为维度隔离后,同一 id 的 - * 两个身份各自缓存各自的 {@link IFlowOperator} 实例,不会互相串味。 - * - *

身份为 {@code null}/{@code ""}(默认身份)时与历史行为等价,等同于只按 userId 缓存。 + *

缓存键由 {@link OperatorKey#key()} 产生,同一人员的不同身份各自缓存,互不覆盖。 */ public class FlowOperatorLocalThreadCache { @@ -31,16 +28,6 @@ private FlowOperatorLocalThreadCache() { @Getter private final static FlowOperatorLocalThreadCache instance = new FlowOperatorLocalThreadCache(); - /** - * 拼装缓存键。 - * - *

键格式由 {@link OperatorKey#key()} 唯一定义:缓存键就是参与人键, - * 本类不再自己声明分隔符,也不自己做归一化。 - */ - private static String cacheKey(long userId, String identity) { - return OperatorKey.of(userId, identity).key(); - } - public void clear() { this.cache.remove(); } @@ -58,132 +45,117 @@ private Map getCache() { */ public void sync(IFlowOperator flowOperator) { Map operatorCaches = this.getCache(); - operatorCaches.put(cacheKey(flowOperator.getUserId(), OperatorIdentity.of(flowOperator).value()), flowOperator); + operatorCaches.put(OperatorKey.of(flowOperator).key(), flowOperator); this.cache.set(operatorCaches); } /** - * 读取操作者(默认身份)。 + * 读取默认身份操作者。 */ public IFlowOperator get(long id, Supplier operatorLoader) { - return this.get(id, OperatorIdentity.DEFAULT.value(), operatorLoader); + return this.get(OperatorKey.ofDefault(id), operatorLoader); } /** - * 按身份读取操作者,未命中时通过 {@code operatorLoader} 加载并回填缓存。 - * - * @param id 人员 id - * @param identity 身份标识,{@code null} 与空串等价 - * @param operatorLoader 缓存未命中时的加载器 - * @return 操作者,加载不到时返回 {@code null} + * 按参与人标识读取操作者,未命中时加载并回填缓存。 */ - public IFlowOperator get(long id, String identity, Supplier operatorLoader) { + public IFlowOperator get(OperatorKey key, Supplier operatorLoader) { Map operatorCaches = this.getCache(); - String key = cacheKey(id, identity); - IFlowOperator operator = operatorCaches.get(key); + IFlowOperator operator = operatorCaches.get(key.key()); if (operator != null) { return operator; } operator = operatorLoader.get(); - // 非默认身份且下游未按身份返回副本时,加载结果的身份与缓存键不一致。 - // 此时不能登记,否则同线程后续按该身份的读取都会命中这个错误身份的对象(issue #288 评审修复)。 - if (operator != null && isIdentityMatched(operator, identity)) { - operatorCaches.put(key, operator); + if (operator != null && isIdentityMatched(operator, key)) { + operatorCaches.put(key.key(), operator); this.cache.set(operatorCaches); } return operator; } /** - * 判断加载结果的身份是否与请求的身份一致。 - * - *

默认身份的读取保持历史行为(批量路径与单条路径都以默认身份为标识无关入口), - * 只有「请求了非默认身份、但拿回的却是另一个身份」才视为不一致。 + * 默认身份保持历史兼容;显式非默认身份必须拿回身份一致的对象才可缓存。 */ - private static boolean isIdentityMatched(IFlowOperator operator, String requestedIdentity) { - if (OperatorIdentity.of(requestedIdentity).isDefault()) { + private static boolean isIdentityMatched(IFlowOperator operator, OperatorKey requestedKey) { + if (OperatorIdentity.of(requestedKey.identity()).isDefault()) { return true; } - return OperatorKey.of(operator).identityEquals(requestedIdentity); + return OperatorKey.of(operator).identityEquals(requestedKey.identity()); } /** - * 批量读取操作者(默认身份)。 - * - *

批量加载没有身份维度(下游网关的 {@code findByIds} 只按 id 查询), - * 因此这里固定使用默认身份作为缓存键,与历史行为一致。 + * 批量读取默认身份操作者。 */ - public List find(List ids, IFlowOperatorFinder flowOperatorFinder) { - return this.find(ids, OperatorIdentity.DEFAULT.value(), flowOperatorFinder); + public List find(List ids, IFlowOperatorFinder operatorFinder) { + return this.find(ids.stream().map(OperatorKey::ofDefault).toList(), + keys -> operatorFinder.find(keys.stream().map(OperatorKey::operatorId).toList())); } /** - * 按身份批量读取操作者(issue #288 衍生 / #293)。 - * - *

用于「一批人员以同一个身份参与流程」的场景(例如同一部门下的多个审批人): - * 结果登记在 {@code (id, identity)} 键下,按同一身份读取时可直接命中, - * 避免同一批人员被逐条回查。 + * 按参与人标识批量读取,支持同一人员对应多个身份。 * - * @param ids 人员 id 列表 - * @param identity 身份标识,{@code null} 与空串等价 - * @param operatorFinder 缓存未命中时的批量加载器 - * @return 操作者列表(按入参 ids 顺序,加载不到的 id 会被跳过) + * @param keys 参与人标识列表 + * @param operatorFinder 缓存未命中时的批量加载器 + * @return 操作者列表,按入参去重后的顺序返回,查不到的参与人跳过 */ - public List find(List ids, String identity, IFlowOperatorFinder operatorFinder) { - if (ids == null || ids.isEmpty()) { - return null; + public List find(List keys, IFlowOperatorKeyFinder operatorFinder) { + if (keys == null || keys.isEmpty()) { + return List.of(); } - - ids = ids.stream() - .filter(id -> id != null && id > 0) + List requestedKeys = keys.stream() + .filter(key -> key != null && key.operatorId() > 0) .distinct() .toList(); - if (ids.isEmpty()) { - return null; + if (requestedKeys.isEmpty()) { + return List.of(); } - String normalizedIdentity = OperatorIdentity.of(identity).value(); - - Map operatorCaches = this.getCache(); - - List queryIds = ids.stream() - .filter((id) -> !operatorCaches.containsKey(cacheKey(id, normalizedIdentity))) + Map operatorCaches = getCache(); + List queryKeys = requestedKeys.stream() + .filter(key -> !operatorCaches.containsKey(key.key())) .toList(); - if (!queryIds.isEmpty()) { - List newOperatorList = operatorFinder.find(queryIds); - if (newOperatorList != null && !newOperatorList.isEmpty()) { - for (IFlowOperator operator : newOperatorList) { - // 结果按「请求身份」登记,而不是操作者对象自带身份: - // 调用方是按该身份发起查询的,登记键必须与读取键一致,否则读取时必然落空。 - // 但「请求了非默认身份、对象却是另一个身份」时不能登记——否则该身份键被错误对象污染, - // 同线程后续按身份的单条读取会直接命中它,身份被静默替换(issue #288 评审修复)。 - if (!isIdentityMatched(operator, normalizedIdentity)) { - continue; + if (!queryKeys.isEmpty()) { + List loaded = operatorFinder.findByKeys(queryKeys); + if (loaded != null) { + Map> operatorsByUser = loaded.stream() + .collect(Collectors.groupingBy(IFlowOperator::getUserId)); + for (OperatorKey requestedKey : queryKeys) { + List candidates = operatorsByUser.getOrDefault(requestedKey.operatorId(), List.of()); + IFlowOperator matched = candidates.stream() + .filter(operator -> OperatorKey.of(operator).identityEquals(requestedKey.identity())) + .findFirst() + .orElse(null); + if (matched == null && OperatorIdentity.of(requestedKey.identity()).isDefault() + && !candidates.isEmpty()) { + matched = candidates.get(0); + } + if (matched != null) { + operatorCaches.put(requestedKey.key(), matched); } - operatorCaches.put(cacheKey(operator.getUserId(), normalizedIdentity), operator); } this.cache.set(operatorCaches); } } - // 按入参 ids 顺序返回,避免缓存命中情况影响结果顺序,保证多人审批顺序稳定 - List operatorList = new ArrayList<>(); - for (long id : ids) { - IFlowOperator operator = operatorCaches.get(cacheKey(id, normalizedIdentity)); + List result = new ArrayList<>(); + for (OperatorKey key : requestedKeys) { + IFlowOperator operator = operatorCaches.get(key.key()); if (operator != null) { - operatorList.add(operator); + result.add(operator); } } - return operatorList; + return result; } - public interface IFlowOperatorFinder { List find(List ids); - } + public interface IFlowOperatorKeyFinder { + + List findByKeys(List keys); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java index 7e112be0..7df59193 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/GatewayContext.java @@ -1,18 +1,16 @@ package com.codingapi.flow.context; import com.codingapi.flow.cache.FlowOperatorLocalThreadCache; +import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; -import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; +import com.codingapi.flow.operator.OperatorKey; import lombok.Getter; import lombok.Setter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; public class GatewayContext { @@ -27,73 +25,53 @@ private GatewayContext() { private FlowOperatorGateway flowOperatorGateway; /** - * 按人员 id 获取操作者(默认身份)。 - * - * @param userId 人员 id - * @return 操作者 + * 获取默认身份操作者。 */ public IFlowOperator getFlowOperator(long userId) { - return this.getFlowOperator(userId, OperatorIdentity.DEFAULT.value()); + return getFlowOperator(OperatorKey.ofDefault(userId)); } /** - * 按人员 id 与身份获取操作者(issue #288)。 - * - *

身份为空({@code null}/空串)时与 {@link #getFlowOperator(long)} 完全等价, - * 保证存量调用链行为不变。 - * - * @param userId 人员 id - * @param identity 身份标识 - * @return 操作者 + * 按参与人标识获取操作者。 */ - public IFlowOperator getFlowOperator(long userId, String identity) { + public IFlowOperator getFlowOperator(OperatorKey key) { IFlowOperator operator = FlowOperatorLocalThreadCache.getInstance() - .get(userId, identity, () -> flowOperatorGateway.get(userId, identity)); - // 下游未覆盖带身份的取人方法时身份会被静默丢弃,这里补一条去重告警(issue #288 衍生 / #294) - OperatorIdentityWarnLog.getInstance().warnOnce(userId, identity, operator); + .get(key, () -> flowOperatorGateway.get(key)); + OperatorIdentityWarnLog.getInstance().warnOnce(key.operatorId(), key.identity(), operator); return operator; } + /** + * 批量获取默认身份操作者。 + */ public List findByIds(List ids) { - return FlowOperatorLocalThreadCache.getInstance().find(ids,(idList)-> flowOperatorGateway.findByIds(idList)); + return findByKeys(ids.stream().map(OperatorKey::ofDefault).toList()); } /** - * 按身份批量获取操作者(issue #288 衍生 / #293)。 - * - *

整批人员使用同一个身份,结果按 {@code (id, identity)} 缓存, - * 避免多身份场景下同一批人员被逐条回查。 - * - * @param ids 人员 id 列表 - * @param identity 身份标识,{@code null} 与空串等价(默认身份) - * @return 操作者列表 + * 按参与人标识批量获取操作者,允许同一人员对应多个身份。 */ - public List findByIds(List ids, String identity) { - List operators = FlowOperatorLocalThreadCache.getInstance() - .find(ids, identity, (idList) -> flowOperatorGateway.findByIds(idList, identity)); - if (OperatorIdentity.of(identity).isDefault()) { - return operators; - } - // 下游未覆盖带身份的批量重载时,批量结果会退化为默认身份(findByIds(ids) 的返回), - // 这里逐条回退到单条按身份取人:正确实现会返回带身份的副本,未实现则由 OperatorIdentityWarnLog 告警。 - // 不做这一层兜底时,批量路径会把身份静默丢弃,且不会产生任何日志(issue #288 评审修复)。 - Map operatorById = new HashMap<>(); - if (operators != null) { - for (IFlowOperator operator : operators) { - operatorById.put(operator.getUserId(), operator); - } + public List findByKeys(List keys) { + return FlowOperatorLocalThreadCache.getInstance().find(keys, missingKeys -> { + List loaded = flowOperatorGateway.findByKeys(missingKeys); + warnMismatchedIdentities(missingKeys, loaded); + return loaded; + }); + } + + private void warnMismatchedIdentities(List keys, List operators) { + if (operators == null || operators.isEmpty()) { + return; } - List result = new ArrayList<>(); - for (Long id : new LinkedHashSet<>(ids)) { - IFlowOperator operator = operatorById.get(id); - if (operator == null || !OperatorIdentity.of(operator).same(OperatorIdentity.of(identity))) { - operator = this.getFlowOperator(id, identity); - } - if (operator != null) { - result.add(operator); - } + Map> operatorsByUser = operators.stream() + .collect(Collectors.groupingBy(IFlowOperator::getUserId)); + for (OperatorKey key : keys) { + List candidates = operatorsByUser.getOrDefault(key.operatorId(), List.of()); + IFlowOperator resolved = candidates.stream() + .filter(operator -> OperatorKey.of(operator).identityEquals(key.identity())) + .findFirst() + .orElse(candidates.isEmpty() ? null : candidates.get(0)); + OperatorIdentityWarnLog.getInstance().warnOnce(key.operatorId(), key.identity(), resolved); } - return result; } - } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java index 45a74067..5ded6ee8 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/context/RepositoryHolderContext.java @@ -130,46 +130,27 @@ public FlowRecord getRecordById(long id) { return flowRecordService.getFlowRecord(id); } - public List findOperatorByIds(List ids) { - return GatewayContext.getInstance().findByIds(ids); - } - @Override - public List findOperatorByIds(List ids, String identity) { - return GatewayContext.getInstance().findByIds(ids, identity); - } - - - public IFlowOperator getOperatorById(long id) { - return GatewayContext.getInstance().getFlowOperator(id); + public List findOperatorsByKeys(List keys) { + return GatewayContext.getInstance().findByKeys(keys); } @Override - public IFlowOperator getOperatorById(long id, String identity) { - return GatewayContext.getInstance().getFlowOperator(id, identity); + public IFlowOperator getOperatorByKey(OperatorKey key) { + return GatewayContext.getInstance().getFlowOperator(key); } @Override public FlowOperatorGateway getFlowOperatorGateway() { return new FlowOperatorGateway() { @Override - public IFlowOperator get(long id) { - return GatewayContext.getInstance().getFlowOperator(id); - } - - @Override - public IFlowOperator get(long id, String identity) { - return GatewayContext.getInstance().getFlowOperator(id, identity); - } - - @Override - public List findByIds(List ids) { - return GatewayContext.getInstance().findByIds(ids); + public IFlowOperator get(OperatorKey key) { + return GatewayContext.getInstance().getFlowOperator(key); } @Override - public List findByIds(List ids, String identity) { - return GatewayContext.getInstance().findByIds(ids, identity); + public List findByKeys(List keys) { + return GatewayContext.getInstance().findByKeys(keys); } }; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java index 3f60c7e2..747df0d2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/diagnostic/OperatorIdentityWarnLog.java @@ -11,9 +11,9 @@ /** * 身份透传效果告警(issue #288 衍生 / #294 / #311 P5)。 * - *

框架通过 {@code default} 方法为身份能力提供向后兼容的退化实现,当下游没有覆盖带身份的取人方法时, - * 身份会被静默丢弃:请求里带的是「部门A」,落库却变成默认身份,前端按身份查待办会得到空列表, - * 且没有任何异常或日志。这类问题在集成阶段极难定位,因此补一条运行期告警。 + *

网关按 {@code OperatorKey} 查询时,如果下游返回了身份不一致的操作者,身份会被静默丢弃: + * 请求里带的是「部门A」,落库却变成默认身份,前端按身份查待办会得到空列表。 + * 这类问题在集成阶段极难定位,因此补一条运行期告警。 * *

它是可观测性组件,不是领域类型,因此位于 {@code diagnostic} 包,不参与任何业务判定。 * @@ -61,7 +61,7 @@ public boolean warnOnce(long operatorId, String requestedIdentity, IFlowOperator return false; } log.warn("流程操作者身份未生效:人员[{}] 请求身份[{}],但回查到的操作者身份为空。" - + "请确认下游已覆盖 FlowOperatorGateway#get(id, identity) 与 IRepositoryHolder#getOperatorById(id, identity)," + + "请确认下游 FlowOperatorGateway#get(OperatorKey) / findByKeys(List) 返回了身份匹配的操作者," + "否则同一人员的多身份将全部退化为默认身份(issue #288)。", operatorId, OperatorIdentity.of(requestedIdentity).value()); return true; diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java index 5fba066f..9c15d809 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/gateway/FlowOperatorGateway.java @@ -1,59 +1,52 @@ package com.codingapi.flow.gateway; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import java.util.List; /** - * 流程操作者防腐层 + * 流程操作者防腐层。 + * + *

参与人统一由 {@link OperatorKey} 表达,避免人员 id 与身份拆分后丢失身份语义。 */ public interface FlowOperatorGateway { /** - * 按人员 id 获取操作者(默认身份)。 + * 按参与人标识获取操作者。 * - * @param id 人员 id - * @return 操作者 + * @param key 参与人标识(人员 id + 身份) + * @return 操作者,查不到时返回 {@code null} */ - IFlowOperator get(long id); + IFlowOperator get(OperatorKey key); /** - * 按人员 id 与身份获取操作者(issue #288)。 + * 按参与人标识批量获取操作者,允许同一人员对应多个身份。 * - *

同一个人员可能以多个身份参与流程(例如同时隶属两个部门),身份由下游自行定义语义, - * 框架只透传。该方法提供 {@code default} 实现:下游存量实现无需改动即可编译, - * 行为退化为忽略身份、等同于 {@link #get(long)}。需要支持多身份时再覆盖此方法。 + *

实现必须返回与入参身份一致的操作者;结果顺序按入参顺序,查不到的参与人跳过。 * - * @param id 人员 id - * @param identity 身份标识,{@code null} 与空串等价(默认身份) - * @return 操作者 + * @param keys 参与人标识列表 + * @return 操作者列表 */ - default IFlowOperator get(long id, String identity) { - return get(id); - } + List findByKeys(List keys); /** - * 按人员 id 批量获取操作者(默认身份)。 + * 按人员 id 获取默认身份操作者。 * - * @param ids 人员 id 列表 - * @return 操作者列表 + * @param id 人员 id + * @return 操作者,查不到时返回 {@code null} */ - List findByIds(List ids); + default IFlowOperator get(long id) { + return get(OperatorKey.ofDefault(id)); + } /** - * 按人员 id 与统一身份批量获取操作者(issue #288 衍生 / #293)。 - * - *

适用于「同一批人员以同一个身份参与流程」的场景(如同一部门下的多个审批人), - * 避免逐条调用 {@link #get(long, String)} 造成 N+1 回查。 - * 默认实现忽略身份、退化为 {@link #findByIds(List)},下游存量实现无需改动即可编译; - * 需要支持多身份时再覆盖此方法。 + * 按人员 id 批量获取默认身份操作者。 * - * @param ids 人员 id 列表 - * @param identity 身份标识,{@code null} 与空串等价(默认身份) - * @return 操作者列表 + * @param ids 人员 id 列表 + * @return 操作者列表,顺序按入参顺序 */ - default List findByIds(List ids, String identity) { - return findByIds(ids); + default List findByIds(List ids) { + return findByKeys(ids.stream().map(OperatorKey::ofDefault).toList()); } - } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java index 3ae48e11..010931b6 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/mock/MockRepositoryHolder.java @@ -74,23 +74,13 @@ public FlowRecordService getFlowRecordService() { public FlowOperatorGateway getFlowOperatorGateway() { return new FlowOperatorGateway() { @Override - public IFlowOperator get(long id) { - return GatewayContext.getInstance().getFlowOperator(id); + public IFlowOperator get(OperatorKey key) { + return GatewayContext.getInstance().getFlowOperator(key); } @Override - public IFlowOperator get(long id, String identity) { - return GatewayContext.getInstance().getFlowOperator(id, identity); - } - - @Override - public List findByIds(List ids) { - return GatewayContext.getInstance().findByIds(ids); - } - - @Override - public List findByIds(List ids, String identity) { - return GatewayContext.getInstance().findByIds(ids, identity); + public List findByKeys(List keys) { + return GatewayContext.getInstance().findByKeys(keys); } }; } @@ -116,23 +106,13 @@ public FlowRecord getRecordById(long recordId) { } @Override - public List findOperatorByIds(List ids) { - return this.flowOperatorGateway.findByIds(ids); - } - - @Override - public List findOperatorByIds(List ids, String identity) { - return this.flowOperatorGateway.findByIds(ids, identity); - } - - @Override - public IFlowOperator getOperatorById(long id) { - return this.flowOperatorGateway.get(id); + public List findOperatorsByKeys(List keys) { + return this.flowOperatorGateway.findByKeys(keys); } @Override - public IFlowOperator getOperatorById(long id, String identity) { - return this.flowOperatorGateway.get(id, identity); + public IFlowOperator getOperatorByKey(OperatorKey key) { + return this.flowOperatorGateway.get(key); } @Override diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java index cb827bb9..1675b4d5 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/StartNode.java @@ -12,6 +12,7 @@ import com.codingapi.flow.node.IDisplayNode; import com.codingapi.flow.node.NodeType; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.FormFieldPermissionStrategy; @@ -89,7 +90,7 @@ public List generateCurrentRecords(FlowSession session) { } else { // 获取流程创建者(按记录中的身份回查,issue #288) IFlowOperator creatorOperator = GatewayContext.getInstance() - .getFlowOperator(currentRecord.getCreateOperatorId(), currentRecord.getCreateOperatorIdentity()); + .getFlowOperator(OperatorKey.of(currentRecord.getCreateOperatorId(), currentRecord.getCreateOperatorIdentity())); FlowRecord flowRecord = new FlowRecord(session.updateSession(creatorOperator), 0); // 异常跳转或退回到开始节点时生成的是一条新的待办,尚未执行任何审批动作, // 不能继承触发该跳转的上游审批意见、签名及 PASS/RETURN 等动作信息。 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java index 5d9ac9cb..df456207 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/OperatorScriptResultResolver.java @@ -28,7 +28,7 @@ *

  • 归一化:集合 / 数组 / 单值 / {@code null} 统一为元素列表;
  • *
  • 元素化:每个元素判定为 {@link OperatorScriptElement.Direct}(直接采用) * 或 {@link OperatorScriptElement.Pending}(按身份回查);
  • - *
  • 批量回查:{@link PendingOperators} 按身份分组一次查完,再按脚本返回顺序还原。
  • + *
  • 批量回查:{@link PendingOperators} 一次提交完整的参与人标识列表,再按脚本返回顺序还原。
  • * * 允许同一列表内混用三种形态;输出顺序与脚本返回一致,保证多人审批的执行顺序稳定。 * diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java index 9e6dc06b..c8f52800 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/operator/PendingOperators.java @@ -1,22 +1,22 @@ package com.codingapi.flow.script.operator; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorIdentity; import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.session.IRepositoryHolder; -import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; /** * 待回查的参与人集合(issue #303 / #311 P4)。 * *

    负责「一批 {@link OperatorKey} → 一批 {@link IFlowOperator}」的回查: - * 先按身份分组,再一次批量查询,避免逐个回查造成 N+1;回查结果以 + * 将完整列表一次性批量查询,避免逐个回查造成 N+1;回查结果以 * {@link OperatorKey#key()} 为键建立索引,供调用方按原顺序还原。 * *

    它替代了原先散在解析器里的 {@code batchResolve(...)} 私有函数: @@ -45,7 +45,7 @@ void collect(OperatorKey key) { } /** - * 按身份分组批量回查。 + * 一次性批量回查完整的参与人标识列表。 * * @return 参与人索引,键为 {@link OperatorKey#key()} */ @@ -53,22 +53,26 @@ Map load() { if (keys.isEmpty()) { return Map.of(); } - Map> operatorIdsByIdentity = new LinkedHashMap<>(); - for (OperatorKey key : keys) { - operatorIdsByIdentity - .computeIfAbsent(key.identity(), identity -> new ArrayList<>()) - .add(key.operatorId()); + List operators = repositoryHolder.findOperatorsByKeys(List.copyOf(keys)); + if (operators == null) { + return Map.of(); } + Map> operatorsByUser = operators.stream() + .collect(Collectors.groupingBy(IFlowOperator::getUserId)); Map resolved = new HashMap<>(); - operatorIdsByIdentity.forEach((identity, operatorIds) -> { - List operators = repositoryHolder.findOperatorByIds(operatorIds, identity); - if (operators == null) { - return; + for (OperatorKey requestedKey : keys) { + List candidates = operatorsByUser.getOrDefault(requestedKey.operatorId(), List.of()); + IFlowOperator matched = candidates.stream() + .filter(operator -> OperatorKey.of(operator).identityEquals(requestedKey.identity())) + .findFirst() + .orElse(null); + if (matched == null && OperatorIdentity.of(requestedKey.identity()).isDefault() && !candidates.isEmpty()) { + matched = candidates.get(0); } - for (IFlowOperator operator : operators) { - resolved.put(OperatorKey.of(operator.getUserId(), identity).key(), operator); + if (matched != null) { + resolved.put(requestedKey.key(), matched); } - }); + } return resolved; } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java index bd072789..8ba1f644 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/script/runtime/IBeanFactory.java @@ -2,6 +2,7 @@ import com.codingapi.flow.context.GatewayContext; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import java.util.List; @@ -39,7 +40,7 @@ default IFlowOperator getOperatorById(long userId) { * @return 操作者 */ default IFlowOperator getOperatorById(long userId, String identity) { - return GatewayContext.getInstance().getFlowOperator(userId, identity); + return GatewayContext.getInstance().getFlowOperator(OperatorKey.of(userId, identity)); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java index e04d2ef2..7601c747 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowActionService.java @@ -12,6 +12,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.response.ActionResponse; @@ -56,8 +57,8 @@ public ActionResponse action() { request.verify(); // 验证当前用户(按请求声明的身份加载,issue #288) - IFlowOperator currentOperator = flowOperatorGateway.get( - request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity()); + IFlowOperator currentOperator = flowOperatorGateway.get(OperatorKey.of( + request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity())); // 审批入口同样检查身份是否真的生效,避免下游未覆盖带身份的取人方法时静默降级(issue #288 评审修复) OperatorIdentityWarnLog.getInstance().warnOnce(request.getAdvice().getOperatorId(), request.getAdvice().getOperatorIdentity(), currentOperator); if (currentOperator == null) { @@ -73,7 +74,7 @@ public ActionResponse action() { // 发起人按记录中的身份回查,避免同一 id 的不同身份拿到同一个操作者实例 IFlowOperator createdOperator = flowOperatorGateway.get( - flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + OperatorKey.of(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity())); OperatorIdentityWarnLog.getInstance().warnOnce(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity(), createdOperator); WorkflowRuntime workflowRuntime = workflowService.getWorkflowRuntime(flowRecord.getWorkRuntimeId()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java index 9392363c..769fa986 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowCreateService.java @@ -15,6 +15,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.diagnostic.OperatorIdentityWarnLog; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.operator.OperatorSelections; import com.codingapi.flow.pojo.request.FlowCreateRequest; import com.codingapi.flow.record.FlowRecord; @@ -60,7 +61,8 @@ public long create() { WorkflowRuntime workflowRuntime = workflowService.getOrCreateWorkflowRuntime(workflow); FlowRuntimeScriptLocalCache.getInstance().set(workflowRuntime.getScripts()); // 验证当前用户(按请求声明的身份加载,同一人不同身份是不同参与人) - IFlowOperator currentOperator = flowOperatorGateway.get(request.getOperatorId(), request.getOperatorIdentity()); + IFlowOperator currentOperator = flowOperatorGateway.get( + OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); // 发起入口同样要检查身份是否真的生效:下游未覆盖带身份的取人方法时身份会被静默丢弃(issue #288 评审修复) OperatorIdentityWarnLog.getInstance().warnOnce(request.getOperatorId(), request.getOperatorIdentity(), currentOperator); if (!workflow.matchCreatedOperator(currentOperator)) { diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java index 3d7ec688..0847433b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDelayTriggerService.java @@ -11,6 +11,7 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.service.WorkflowService; @@ -61,11 +62,11 @@ public void trigger() { IFlowNode currentNode = workflow.getFlowNode(flowRecord.getNodeId()); IFlowOperator createdOperator = flowOperatorGateway.get( - flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + OperatorKey.of(flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity())); IFlowOperator submitOperator = flowOperatorGateway.get( - flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity()); + OperatorKey.of(flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity())); IFlowOperator currentOperator = flowOperatorGateway.get( - flowRecord.getCurrentOperatorId(), flowRecord.getCurrentOperatorIdentity()); + OperatorKey.of(flowRecord.getCurrentOperatorId(), flowRecord.getCurrentOperatorIdentity())); IFlowAction flowAction = currentNode.actionManager().getActionById(flowRecord.getActionId()); // 延迟任务固化的前驱记录可能为相同人员自动通过的留痕记录(无审批动作,actionId=null,issue #226): // 以该记录所在审批节点的通过动作兜底恢复流转,避免 NPE 使流程永久停滞在延迟节点 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java index 086aa8c9..6674cee0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDetailService.java @@ -8,6 +8,7 @@ import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.node.helper.BackNodeHelper; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowDetailRequest; import com.codingapi.flow.pojo.response.FlowContent; import com.codingapi.flow.pojo.response.NodeOption; @@ -37,7 +38,8 @@ public class FlowDetailService { public FlowDetailService(FlowDetailRequest request, IRepositoryHolder repositoryHolder) { this.request = request; - this.currentOperator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); + this.currentOperator = repositoryHolder.getOperatorByKey( + OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); this.flowRecordService = repositoryHolder.getFlowRecordService(); this.workflowService = repositoryHolder.getWorkflowService(); this.repositoryHolder = repositoryHolder; @@ -74,11 +76,11 @@ public FlowContent detail() { repositoryHolder.saveRecord(flowRecord); } - IFlowOperator createOperator = repositoryHolder.getOperatorById( - flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity()); + IFlowOperator createOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + flowRecord.getCreateOperatorId(), flowRecord.getCreateOperatorIdentity())); - IFlowOperator submitOperator = repositoryHolder.getOperatorById( - flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity()); + IFlowOperator submitOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + flowRecord.getSubmitOperatorId(), flowRecord.getSubmitOperatorIdentity())); FlowForm flowForm = workflow.getForm(); FormData formData = new FormData(flowForm); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java index 610ccdd8..c23db711 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowForceSyncService.java @@ -7,6 +7,7 @@ import com.codingapi.flow.exception.FlowStateException; import com.codingapi.flow.mock.MockRepositoryHolder; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowForceSyncRequest; import com.codingapi.flow.pojo.response.FlowForceSyncResult; import com.codingapi.flow.record.FlowRecord; @@ -62,7 +63,8 @@ public FlowForceSyncResult sync() { // 最新设计必须通过校验,避免把不合法的设计同步给运行实例 latestWorkflow.verify(); - IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); + IFlowOperator operator = repositoryHolder.getOperatorByKey( + OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); if (operator == null) { throw FlowNotFoundException.operator(request.getOperatorId()); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java index b42ef942..8a963e49 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowProcessNodeService.java @@ -19,6 +19,7 @@ import com.codingapi.flow.node.nodes.SubProcessNode; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.request.FlowProcessNodeRequest; import com.codingapi.flow.pojo.response.ProcessNode; import com.codingapi.flow.record.FlowRecord; @@ -104,23 +105,19 @@ private boolean isCreateWorkflow() { return !id.matches("^[0-9]+$"); } - /** - * 操作者缓存键:同一人员的不同身份必须区分缓存,避免身份串味(issue #288) - */ - private static String recordOperatorKey(long operatorId, String identity) { - return operatorId + "\u0001" + OperatorIdentity.of(identity).value(); + private IFlowOperator loadRecordOperator(long operatorId, String identity) { + return loadRecordOperator(OperatorKey.of(operatorId, identity)); } - private IFlowOperator loadRecordOperator(long operatorId, String identity) { - String cacheKey = recordOperatorKey(operatorId, identity); - IFlowOperator flowOperator = this.recordOperatorMap.get(cacheKey); + private IFlowOperator loadRecordOperator(OperatorKey key) { + IFlowOperator flowOperator = this.recordOperatorMap.get(key.key()); if (flowOperator != null) { return flowOperator; } - flowOperator = this.repositoryHolder.getOperatorById(operatorId, identity); + flowOperator = this.repositoryHolder.getOperatorByKey(key); if (flowOperator != null) { - this.recordOperatorMap.put(cacheKey, flowOperator); + this.recordOperatorMap.put(key.key(), flowOperator); } return flowOperator; } @@ -130,46 +127,50 @@ private void fetchFlowRecordOperatorList() { } /** - * 按 {@code (人员id, 记录中的身份)} 分组批量加载操作者(issue #288 衍生 / #293)。 - * - *

    登记缓存时使用的身份必须与读取端 {@link #loadRecordOperator(long, String)} 一致(都取记录里的身份), - * 否则批量结果读不到,会退化成逐条回查网关。按身份分组后,每个身份只发一次批量请求, - * 多身份流程树不会产生 N+1。 + * 一次批量加载记录中的全部参与人,同一人员的不同身份分别保留(issue #315)。 */ private void preloadRecordOperators(List records) { if (records == null || records.isEmpty()) { return; } - Map> operatorIdsByIdentity = new LinkedHashMap<>(); + Set operatorKeys = new LinkedHashSet<>(); for (FlowRecord record : records) { - addOperatorRef(operatorIdsByIdentity, record.getCreateOperatorId(), record.getCreateOperatorIdentity()); - addOperatorRef(operatorIdsByIdentity, record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()); - addOperatorRef(operatorIdsByIdentity, record.getSubmitOperatorId(), record.getSubmitOperatorIdentity()); + addOperatorRef(operatorKeys, record.getCreateOperatorId(), record.getCreateOperatorIdentity()); + addOperatorRef(operatorKeys, record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()); + addOperatorRef(operatorKeys, record.getSubmitOperatorId(), record.getSubmitOperatorIdentity()); } - operatorIdsByIdentity.forEach((identity, operatorIds) -> { - List queryIds = operatorIds.stream() - .filter(operatorId -> !this.recordOperatorMap.containsKey(recordOperatorKey(operatorId, identity))) - .toList(); - if (queryIds.isEmpty()) { - return; - } - List operatorList = this.repositoryHolder.findOperatorByIds(queryIds, identity); - if (operatorList == null || operatorList.isEmpty()) { - return; + List queryKeys = operatorKeys.stream() + .filter(key -> !this.recordOperatorMap.containsKey(key.key())) + .toList(); + if (queryKeys.isEmpty()) { + return; + } + List operatorList = this.repositoryHolder.findOperatorsByKeys(queryKeys); + if (operatorList == null || operatorList.isEmpty()) { + return; + } + Map> operatorsByUser = operatorList.stream() + .collect(java.util.stream.Collectors.groupingBy(IFlowOperator::getUserId)); + for (OperatorKey key : queryKeys) { + List candidates = operatorsByUser.getOrDefault(key.operatorId(), List.of()); + IFlowOperator matched = candidates.stream() + .filter(operator -> OperatorKey.of(operator).identityEquals(key.identity())) + .findFirst() + .orElse(null); + if (matched == null && OperatorIdentity.of(key.identity()).isDefault() + && !candidates.isEmpty()) { + matched = candidates.get(0); } - for (IFlowOperator operator : operatorList) { - this.recordOperatorMap.put(recordOperatorKey(operator.getUserId(), identity), operator); + if (matched != null) { + this.recordOperatorMap.put(key.key(), matched); } - }); + } } - private static void addOperatorRef(Map> operatorIdsByIdentity, long operatorId, String identity) { - if (operatorId <= 0) { - return; + private static void addOperatorRef(Set operatorKeys, long operatorId, String identity) { + if (operatorId > 0) { + operatorKeys.add(OperatorKey.of(operatorId, identity)); } - operatorIdsByIdentity - .computeIfAbsent(OperatorIdentity.of(identity).value(), key -> new LinkedHashSet<>()) - .add(operatorId); } public List processNodes() { @@ -715,7 +716,7 @@ private interface IFlowOperatorGateway { /** * 按 (userId, identity) 加载操作者,同一人的不同身份需要返回不同实例(issue #288) */ - IFlowOperator getFlowOperator(long operatorId, String identity); + IFlowOperator getFlowOperator(OperatorKey key); } private static class FlowRecordOrderService { @@ -784,8 +785,8 @@ public void fetch(long formId) { for (List group : groupList.values()) { this.consumer.accept(group.stream() .map(record -> new ProcessNode.FlowRecordOperator( - record, flowOperatorGateway.getFlowOperator( - record.getCurrentOperatorId(), record.getCurrentOperatorIdentity()))) + record, flowOperatorGateway.getFlowOperator(OperatorKey.of( + record.getCurrentOperatorId(), record.getCurrentOperatorIdentity())))) .toList()); for (FlowRecord item : group) { this.fetch(item.getId()); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java index 214edf6f..87bbccf0 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowReissueService.java @@ -85,7 +85,8 @@ public long reissue() { throw FlowNotFoundException.record(request.getSourceRecordId()); } - IFlowOperator operator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); + IFlowOperator operator = repositoryHolder.getOperatorByKey( + OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); if (operator == null) { throw FlowNotFoundException.operator(request.getOperatorId()); } @@ -105,7 +106,8 @@ public long reissue() { // 新流程沿用源流程的发起人,二次发起后的待办回到发起人,由发起人调整数据后重新提交 long initiatorId = sourceRecord.getCreateOperatorId(); - if (repositoryHolder.getOperatorById(initiatorId, sourceRecord.getCreateOperatorIdentity()) == null) { + if (repositoryHolder.getOperatorByKey( + OperatorKey.of(initiatorId, sourceRecord.getCreateOperatorIdentity())) == null) { throw FlowNotFoundException.operator(initiatorId); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java index 70fcbb5c..66993c57 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResetService.java @@ -181,7 +181,8 @@ public void reset() { } boolean mock = repositoryHolder instanceof MockRepositoryHolder; - IFlowOperator resetOperator = repositoryHolder.getOperatorById(request.getOperatorId(), request.getOperatorIdentity()); + IFlowOperator resetOperator = repositoryHolder.getOperatorByKey( + OperatorKey.of(request.getOperatorId(), request.getOperatorIdentity())); for (FlowRecord invalidatedRecord : invalidatedRecords) { FlowEventPublisher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java index 5297747a..a264d426 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowUrgeService.java @@ -79,7 +79,7 @@ public void urge() { } IFlowOperator currentOperator = flowOperatorGateway.get( - currentRecord.getCurrentOperatorId(), request.getOperatorIdentity()); + OperatorKey.of(currentRecord.getCurrentOperatorId(), request.getOperatorIdentity())); List todoRecords = flowRecordService.findFlowRecordTodoRecords(currentRecord.getProcessId()); // 保存催办记录 diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java index 5b28a547..6794e5ce 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/SubProcessSessionFactory.java @@ -8,6 +8,7 @@ import com.codingapi.flow.form.FormData; import com.codingapi.flow.node.IFlowNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.WorkflowService; import com.codingapi.flow.session.FlowAdvice; @@ -60,12 +61,12 @@ public static FlowSession createParentSession(SubProcessRecord subProcessRecord, if (action == null && parentRecord.isAutoDone()) { action = sourceNode.actionManager().getAction(PassAction.class); } - IFlowOperator currentOperator = repositoryHolder.getOperatorById( - parentRecord.getCurrentOperatorId(), parentRecord.getCurrentOperatorIdentity()); - IFlowOperator createdOperator = repositoryHolder.getOperatorById( - parentRecord.getCreateOperatorId(), parentRecord.getCreateOperatorIdentity()); - IFlowOperator submitOperator = repositoryHolder.getOperatorById( - parentRecord.getSubmitOperatorId(), parentRecord.getSubmitOperatorIdentity()); + IFlowOperator currentOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + parentRecord.getCurrentOperatorId(), parentRecord.getCurrentOperatorIdentity())); + IFlowOperator createdOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + parentRecord.getCreateOperatorId(), parentRecord.getCreateOperatorIdentity())); + IFlowOperator submitOperator = repositoryHolder.getOperatorByKey(OperatorKey.of( + parentRecord.getSubmitOperatorId(), parentRecord.getSubmitOperatorIdentity())); FormData formData = new FormData(workflow.getForm()); formData.reset(parentRecord.getFormData()); FlowAdvice advice = parentRecord.toAdvice(workflow); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java b/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java index dd86e508..d5b85c7e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/session/IRepositoryHolder.java @@ -80,49 +80,33 @@ public interface IRepositoryHolder { FlowRecord getRecordById(long recordId); /** - * 获取流程操作人 + * 按参与人标识获取流程操作人。 * - * @param ids 流程人Id + * @param key 参与人标识 * @return 流程操作人 */ - List findOperatorByIds(List ids); - + IFlowOperator getOperatorByKey(OperatorKey key); /** - * 获取流程操作人(默认身份) + * 按参与人标识批量获取流程操作人,允许同一人员对应多个身份。 * - * @param id 人员id - * @return 流程操作人 + * @param keys 参与人标识列表 + * @return 流程操作人列表 */ - IFlowOperator getOperatorById(long id); + List findOperatorsByKeys(List keys); /** - * 按身份获取流程操作人(issue #288) - * - *

    同一个人员可能以不同身份参与流程,按记录回查操作者时必须带上记录里的身份, - * 否则同一 id 的不同身份会拿到同一个操作者实例。 - * 默认实现忽略身份、退化为 {@link #getOperatorById(long)},下游存量实现无需改动。 - * - * @param id 人员id - * @param identity 身份标识,{@code null} 与空串等价(默认身份) - * @return 流程操作人 + * 获取默认身份流程操作人。 */ - default IFlowOperator getOperatorById(long id, String identity) { - return getOperatorById(id); + default IFlowOperator getOperatorById(long id) { + return getOperatorByKey(OperatorKey.ofDefault(id)); } /** - * 按统一身份批量获取流程操作人(issue #288 衍生 / #293)。 - * - *

    用于一批人员以同一身份参与流程的场景,避免逐条回查。 - * 默认实现忽略身份、退化为 {@link #findOperatorByIds(List)},下游存量实现无需改动。 - * - * @param ids 人员 id 列表 - * @param identity 身份标识,{@code null} 与空串等价(默认身份) - * @return 流程操作人列表 + * 批量获取默认身份流程操作人。 */ - default List findOperatorByIds(List ids, String identity) { - return findOperatorByIds(ids); + default List findOperatorByIds(List ids) { + return findOperatorsByKeys(ids.stream().map(OperatorKey::ofDefault).toList()); } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java index f45b25c8..b065db24 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/strategy/node/OperatorLoadStrategy.java @@ -77,7 +77,7 @@ public OperatorManager loadOperators(FlowSession flowSession) { /** * 按 {@code (人员id, 身份)} 加载已分配的操作人(issue #288 衍生 / #292)。 * - *

    回查逻辑统一由 {@link OperatorScriptResultResolver} 提供:按身份分组批量回查, + *

    回查逻辑统一由 {@link OperatorScriptResultResolver} 提供:完整参与人列表一次批量回查, * 返回顺序与分配顺序一致,保证多人审批的执行顺序稳定。 */ private List loadAssignedOperators(IRepositoryHolder repositoryHolder, diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java index fae6ed5a..23b54588 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorBulkIdentityTest.java @@ -3,7 +3,7 @@ import com.codingapi.flow.context.GatewayContext; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; -import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.user.User; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -15,17 +15,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** - * 按身份批量取人的缓存与网关契约测试(issue #288 衍生 / #293、#295)。 - * - *

    批量加载必须按 {@code (id, identity)} 隔离缓存,否则同一批人以不同身份参与时 - * 会命中同一个对象,身份串味;同时验证未覆盖新方法的存量网关能安全退化为按 id 批量查询。 + * 按 OperatorKey 批量取人的缓存与网关契约测试(issue #315)。 */ class FlowOperatorBulkIdentityTest { private FlowOperatorLocalThreadCache cache; - private FlowOperatorGateway previousGateway; @BeforeEach @@ -37,141 +34,80 @@ void setUp() { @AfterEach void tearDown() { - // GatewayContext 是全局单例,用例结束后必须还原,避免影响其他用例 GatewayContext.getInstance().setFlowOperatorGateway(previousGateway); cache.clear(); } - /** - * 测试目标:两个身份分别回源、分别命中缓存,互不覆盖。 - * 前置条件:缓存为空,人员 1 有两个身份副本。 - * 执行步骤:以两个身份各批量加载一次,再重复加载第一个身份。 - * 期望断言:返回各自的操作者;重复加载命中缓存不回源,回源次数为 2。 - */ @Test - void should_isolate_bulk_load_by_identity() { + void should_isolate_bulk_load_by_operator_key() { User department1 = User.withIdentity(1, "user1", "department1"); User department2 = User.withIdentity(1, "user1", "department2"); AtomicInteger loads = new AtomicInteger(); + OperatorKey firstKey = OperatorKey.of(1, "department1"); + OperatorKey secondKey = OperatorKey.of(1, "department2"); - List first = cache.find(List.of(1L), "department1", ids -> { + List first = cache.find(List.of(firstKey), keys -> { loads.incrementAndGet(); return List.of(department1); }); - List second = cache.find(List.of(1L), "department2", ids -> { + List second = cache.find(List.of(secondKey), keys -> { loads.incrementAndGet(); return List.of(department2); }); - List again = cache.find(List.of(1L), "department1", ids -> { + List again = cache.find(List.of(firstKey), keys -> { loads.incrementAndGet(); return List.of(); }); - assertEquals(1, first.size()); - assertEquals(1, second.size()); assertSame(department1, first.get(0)); assertSame(department2, second.get(0)); assertSame(department1, again.get(0)); - assertEquals(2, loads.get(), "同一身份重复加载应命中缓存"); + assertEquals(2, loads.get(), "同一参与人重复加载应命中缓存"); } - /** - * 测试目标:默认身份的批量加载与历史单参 {@code find} 等价。 - * 前置条件:缓存为空。 - * 执行步骤:用三参重载、identity 传空串加载。 - * 期望断言:结果与默认身份键下的缓存一致。 - */ @Test void should_share_cache_with_legacy_bulk_load_for_default_identity() { User user = new User(3, "user3"); - List loaded = cache.find(List.of(3L), OperatorIdentity.DEFAULT.value(), - ids -> List.of(user)); + List loaded = cache.find(List.of(3L), ids -> List.of(user)); - assertEquals(1, loaded.size()); + assertSame(user, loaded.get(0)); assertSame(user, cache.get(3, () -> null)); } - /** - * 测试目标:下游未覆盖身份重载时安全退化为按 id 批量查询(向后兼容硬约束)。 - * 前置条件:网关只实现两个抽象方法。 - * 执行步骤:调用带身份的默认方法。 - * 期望断言:返回按 id 查询的结果,编译与行为均不破坏。 - */ - @Test - void should_degrade_to_plain_find_by_ids_when_gateway_not_overridden() { - FlowOperatorGateway legacyGateway = new FlowOperatorGateway() { - @Override - public IFlowOperator get(long id) { - return new User(id, "user" + id); - } - - @Override - public List findByIds(List ids) { - return ids.stream().map(id -> (IFlowOperator) new User(id, "user" + id)).toList(); - } - }; - - List operators = legacyGateway.findByIds(List.of(1L, 2L), "department1"); - - assertEquals(2, operators.size()); - assertEquals("", OperatorIdentity.of(operators.get(0)).value()); - } - - /** - * 测试目标:下游只覆盖单条按身份取人、未覆盖批量重载时,批量路径必须回退到单条取人拿回正确身份。 - * 前置条件:网关实现 {@code get(id, identity)}(返回带身份的副本)但复用默认的批量重载。 - * 执行步骤:经 GatewayContext 批量按身份取人,再按同一身份单条取人。 - * 期望断言:批量结果携带请求身份(不是被静默降级为默认身份),且缓存没有被错误对象污染。 - */ @Test - void should_fall_back_to_single_load_when_gateway_has_no_bulk_identity_override() { - FlowOperatorGateway partialGateway = new FlowOperatorGateway() { + void should_not_return_or_cache_operator_with_mismatched_identity() { + FlowOperatorGateway gateway = new FlowOperatorGateway() { @Override - public IFlowOperator get(long id) { - return new User(id, "user" + id); + public IFlowOperator get(OperatorKey key) { + return new User(key.operatorId(), "user" + key.operatorId()); } @Override - public IFlowOperator get(long id, String identity) { - return User.withIdentity(id, "user" + id, identity); - } - - @Override - public List findByIds(List ids) { - return ids.stream().map(id -> (IFlowOperator) new User(id, "user" + id)).toList(); + public List findByKeys(List keys) { + return keys.stream().map(key -> (IFlowOperator) new User(key.operatorId(), "user" + key.operatorId())).toList(); } }; + GatewayContext.getInstance().setFlowOperatorGateway(gateway); - GatewayContext.getInstance().setFlowOperatorGateway(partialGateway); - - List operators = GatewayContext.getInstance().findByIds(List.of(1L), "department1"); + List operators = GatewayContext.getInstance().findByKeys(List.of(OperatorKey.of(1, "department1"))); - assertEquals(1, operators.size()); - assertEquals("department1", OperatorIdentity.of(operators.get(0)).value(), - "批量路径不能把请求身份静默降级为默认身份"); - // 单条读取必须命中同一个带身份的对象,说明缓存未被默认身份的对象污染 - assertEquals("department1", - OperatorIdentity.of(FlowOperatorLocalThreadCache.getInstance().get(1, "department1", () -> null)).value()); + assertTrue(operators.isEmpty(), "身份不一致的结果不能作为 requested key 的查询结果返回"); + assertNull(cache.get(OperatorKey.of(1, "department1"), () -> null), "错误身份对象不能污染缓存"); } - /** - * 测试目标:单条加载拿回身份不一致的对象时不登记缓存(避免污染身份键)。 - * 前置条件:缓存为空,加载器返回默认身份对象。 - * 执行步骤:以非默认身份读取一次,再用正确身份的加载器读一次。 - * 期望断言:第一次返回默认身份对象但不缓存,第二次能拿到正确的身份对象。 - */ @Test void should_not_cache_single_load_result_with_mismatched_identity() { User defaultUser = new User(7, "user7"); User identityUser = User.withIdentity(7, "user7", "department1"); + OperatorKey key = OperatorKey.of(7, "department1"); - IFlowOperator first = cache.get(7, "department1", () -> defaultUser); + IFlowOperator first = cache.get(key, () -> defaultUser); assertSame(defaultUser, first); - assertNull(cache.get(7, "department1", () -> null), "身份不一致的加载结果不能登记缓存"); + assertNull(cache.get(key, () -> null), "身份不一致的加载结果不能登记缓存"); - IFlowOperator second = cache.get(7, "department1", () -> identityUser); + IFlowOperator second = cache.get(key, () -> identityUser); assertSame(identityUser, second); - assertSame(identityUser, cache.get(7, "department1", () -> null)); + assertSame(identityUser, cache.get(key, () -> null)); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java index 4cb9dfee..809d52a2 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/cache/FlowOperatorLocalThreadCacheTest.java @@ -1,6 +1,7 @@ package com.codingapi.flow.cache; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.user.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,9 +38,9 @@ void should_isolate_cache_by_identity() { cache.sync(department1); cache.sync(department2); - assertSame(department1, cache.get(1, "department1", () -> null)); - assertSame(department2, cache.get(1, "department2", () -> null)); - assertNotSame(cache.get(1, "department1", () -> null), cache.get(1, "department2", () -> null)); + assertSame(department1, cache.get(OperatorKey.of(1, "department1"), () -> null)); + assertSame(department2, cache.get(OperatorKey.of(1, "department2"), () -> null)); + assertNotSame(cache.get(OperatorKey.of(1, "department1"), () -> null), cache.get(OperatorKey.of(1, "department2"), () -> null)); } /** @@ -50,8 +51,8 @@ void should_treat_null_and_empty_identity_as_same_key() { User defaultUser = new User(1, "user1"); cache.sync(defaultUser); - assertSame(defaultUser, cache.get(1, null, () -> null)); - assertSame(defaultUser, cache.get(1, "", () -> null)); + assertSame(defaultUser, cache.get(OperatorKey.of(1, null), () -> null)); + assertSame(defaultUser, cache.get(OperatorKey.of(1, ""), () -> null)); assertSame(defaultUser, cache.get(1, () -> null)); } @@ -62,24 +63,26 @@ void should_treat_null_and_empty_identity_as_same_key() { void should_load_and_cache_by_requested_identity() { User loaded = User.withIdentity(2, "user2", "department9"); - IFlowOperator operator = cache.get(2, "department9", () -> loaded); + IFlowOperator operator = cache.get(OperatorKey.of(2, "department9"), () -> loaded); assertSame(loaded, operator); - assertSame(loaded, cache.get(2, "department9", () -> null)); + assertSame(loaded, cache.get(OperatorKey.of(2, "department9"), () -> null)); // 另一个身份不会命中该缓存 - assertNull(cache.get(2, "department1", () -> null)); + assertNull(cache.get(OperatorKey.of(2, "department1"), () -> null)); } /** - * 批量加载是标识无关路径:结果登记在默认身份键下,避免「审批人为空」。 + * 默认身份批量结果只能登记默认身份键,不能误用同人员的其他身份对象。 */ @Test void should_cache_bulk_load_result_under_default_identity() { + User defaultUser = new User(3, "user3"); User identityUser = User.withIdentity(3, "user3", "department1"); - var list = cache.find(java.util.List.of(3L), ids -> java.util.List.of(identityUser)); + var list = cache.find(java.util.List.of(3L), ids -> java.util.List.of(identityUser, defaultUser)); assertEquals(1, list.size()); - assertSame(identityUser, cache.get(3, () -> null)); + assertSame(defaultUser, list.get(0)); + assertSame(defaultUser, cache.get(3, () -> null)); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/FlowOperatorKeyGatewayTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/FlowOperatorKeyGatewayTest.java new file mode 100644 index 00000000..d1985ad9 --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/FlowOperatorKeyGatewayTest.java @@ -0,0 +1,173 @@ +package com.codingapi.flow.gateway; + +import com.codingapi.flow.cache.FlowOperatorLocalThreadCache; +import com.codingapi.flow.context.GatewayContext; +import com.codingapi.flow.mock.MockRepositoryHolder; +import com.codingapi.flow.factory.MyFlowServiceFactory; +import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; +import com.codingapi.flow.script.operator.OperatorScriptResultResolver; +import com.codingapi.flow.session.IRepositoryHolder; +import com.codingapi.flow.user.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * OperatorKey 网关契约测试(issue #315)。 + */ +class FlowOperatorKeyGatewayTest { + + private FlowOperatorLocalThreadCache cache; + private FlowOperatorGateway previousGateway; + + @BeforeEach + void setUp() { + cache = FlowOperatorLocalThreadCache.getInstance(); + cache.clear(); + previousGateway = GatewayContext.getInstance().getFlowOperatorGateway(); + } + + @AfterEach + void tearDown() { + GatewayContext.getInstance().setFlowOperatorGateway(previousGateway); + cache.clear(); + } + + @Test + void should_load_mixed_identities_in_one_batch_and_keep_request_order() { + RecordingGateway gateway = new RecordingGateway(); + GatewayContext.getInstance().setFlowOperatorGateway(gateway); + List keys = List.of( + OperatorKey.of(2, "department1"), + OperatorKey.ofDefault(1), + OperatorKey.of(1, "department2"), + OperatorKey.of(2, "department1")); + + List operators = GatewayContext.getInstance().findByKeys(keys); + + assertEquals(3, operators.size()); + assertEquals(2, operators.get(0).getUserId()); + assertEquals("department1", operators.get(0).getIdentity()); + assertEquals(1, operators.get(1).getUserId()); + assertEquals("", operators.get(1).getIdentity()); + assertEquals(1, operators.get(2).getUserId()); + assertEquals("department2", operators.get(2).getIdentity()); + assertEquals(1, gateway.batchCalls); + assertEquals(3, gateway.lastKeys.size(), "重复参与人只应查询一次"); + assertEquals(0, gateway.singleCalls); + } + + @Test + void should_cache_each_operator_key_independently() { + RecordingGateway gateway = new RecordingGateway(); + GatewayContext.getInstance().setFlowOperatorGateway(gateway); + OperatorKey first = OperatorKey.of(1, "department1"); + OperatorKey second = OperatorKey.of(1, "department2"); + + IFlowOperator firstOperator = GatewayContext.getInstance().getFlowOperator(first); + IFlowOperator secondOperator = GatewayContext.getInstance().getFlowOperator(second); + IFlowOperator cached = GatewayContext.getInstance().getFlowOperator(first); + + assertSame(firstOperator, cached); + assertEquals("department1", firstOperator.getIdentity()); + assertEquals("department2", secondOperator.getIdentity()); + assertEquals(2, gateway.singleCalls); + } + + @Test + void should_derive_default_identity_queries_from_operator_key_contract() { + RecordingGateway gateway = new RecordingGateway(); + GatewayContext.getInstance().setFlowOperatorGateway(gateway); + + IFlowOperator operator = gateway.get(1); + List operators = gateway.findByIds(List.of(2L, 1L)); + + assertEquals("", operator.getIdentity()); + assertEquals(List.of(OperatorKey.ofDefault(1)), gateway.lastSingleKeys); + assertEquals(List.of(OperatorKey.ofDefault(2), OperatorKey.ofDefault(1)), gateway.lastKeys); + assertEquals(2, operators.size()); + } + + @Test + void should_resolve_script_keys_with_one_mixed_identity_batch() { + RecordingGateway gateway = new RecordingGateway(); + MyFlowServiceFactory factory = new MyFlowServiceFactory(); + MockRepositoryHolder holder = new MockRepositoryHolder(gateway, factory.workflowRepository); + List keys = List.of( + OperatorKey.of(2, "department1"), + OperatorKey.ofDefault(1), + OperatorKey.of(1, "department2"), + OperatorKey.of(2, "department1")); + + List operators = new OperatorScriptResultResolver(holder, "operatorLoad").resolve(keys); + + assertEquals(4, operators.size(), "解析结果应保留脚本返回顺序与重复项"); + assertEquals("department1", operators.get(0).getIdentity()); + assertEquals("", operators.get(1).getIdentity()); + assertEquals("department2", operators.get(2).getIdentity()); + assertSame(operators.get(0), operators.get(3)); + assertEquals(1, gateway.batchCalls); + assertEquals(3, gateway.lastKeys.size()); + assertEquals(0, gateway.singleCalls); + } + + @Test + void should_not_expose_silent_identity_split_overloads() throws NoSuchMethodException { + assertThrows(NoSuchMethodException.class, + () -> FlowOperatorGateway.class.getMethod("get", long.class, String.class)); + assertThrows(NoSuchMethodException.class, + () -> FlowOperatorGateway.class.getMethod("findByIds", List.class, String.class)); + assertThrows(NoSuchMethodException.class, + () -> IRepositoryHolder.class.getMethod("getOperatorById", long.class, String.class)); + assertThrows(NoSuchMethodException.class, + () -> IRepositoryHolder.class.getMethod("findOperatorByIds", List.class, String.class)); + } + + private static final class RecordingGateway implements FlowOperatorGateway { + + private final Map operators = new LinkedHashMap<>(); + private int singleCalls; + private int batchCalls; + private List lastSingleKeys; + private List lastKeys; + + private RecordingGateway() { + operators.put(OperatorKey.ofDefault(1), new User(1, "user1")); + operators.put(OperatorKey.ofDefault(2), new User(2, "user2")); + operators.put(OperatorKey.of(1, "department1"), User.withIdentity(1, "user1", "department1")); + operators.put(OperatorKey.of(1, "department2"), User.withIdentity(1, "user1", "department2")); + operators.put(OperatorKey.of(2, "department1"), User.withIdentity(2, "user2", "department1")); + } + + @Override + public IFlowOperator get(OperatorKey key) { + singleCalls++; + lastSingleKeys = List.of(key); + return operators.get(key); + } + + @Override + public List findByKeys(List keys) { + batchCalls++; + lastKeys = new ArrayList<>(keys); + List result = new ArrayList<>(); + for (OperatorKey key : keys) { + IFlowOperator operator = operators.get(key); + if (operator != null) { + result.add(operator); + } + } + return result; + } + } +} diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java index e83e9f2f..499b4a19 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/gateway/impl/UserGateway.java @@ -3,8 +3,10 @@ import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.operator.IFlowOperator; import com.codingapi.flow.operator.OperatorIdentity; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.user.User; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,48 +15,27 @@ public class UserGateway implements FlowOperatorGateway { private final Map cache = new HashMap<>(); - - @Override - public IFlowOperator get(long id) { - return cache.get(id); - } - - /** - * 按身份返回用户副本,模拟下游「同一人员以不同身份参与流程」的组织模型(issue #288)。 - *

    未声明身份时返回缓存中的用户本身,保持 P1 用例「用户自带默认身份」的行为。 - */ @Override - public IFlowOperator get(long id, String identity) { - User user = cache.get(id); - if (user == null || OperatorIdentity.of(identity).isDefault()) { + public IFlowOperator get(OperatorKey key) { + User user = cache.get(key.operatorId()); + if (user == null || OperatorIdentity.of(key.identity()).isDefault()) { return user; } - return user.asIdentity(identity); + return user.asIdentity(key.identity()); } @Override - public List findByIds(List ids) { - return cache.values().stream().filter(user -> ids.contains(user.getUserId())) - .map(user -> (IFlowOperator) user) - .toList(); - } - - /** - * 按统一身份批量返回用户副本,与 {@link #get(long, String)} 口径一致(issue #288 衍生 / #293)。 - */ - @Override - public List findByIds(List ids, String identity) { - List operators = this.findByIds(ids); - if (OperatorIdentity.of(identity).isDefault()) { - return operators; + public List findByKeys(List keys) { + List operators = new ArrayList<>(); + for (OperatorKey key : keys) { + IFlowOperator operator = get(key); + if (operator != null) { + operators.add(operator); + } } - return operators.stream() - .map(operator -> operator instanceof User user - ? (IFlowOperator) user.asIdentity(identity) : operator) - .toList(); + return operators; } - public void save(User user) { cache.put(user.getUserId(), user); } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java index 8440d2c6..7545b9eb 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/script/operator/OperatorScriptResultResolverTest.java @@ -196,17 +196,17 @@ void should_skip_non_positive_user_id() { } /** - * 批量回查按身份分组执行,避免逐个回查(N+1) + * 混合身份的一次解析只发一次批量回查,避免逐个回查(N+1) */ @Test - void should_query_in_batches_grouped_by_identity() { + void should_query_mixed_identities_in_one_batch() { resolve(countingHolder.proxy(), List.of( OperatorKey.of(1, "department1"), OperatorKey.of(2, "department1"), OperatorKey.of(1, "department2"), 2L)); - assertEquals(3, countingHolder.batchQueryCount); + assertEquals(1, countingHolder.batchQueryCount); assertEquals(0, countingHolder.singleQueryCount); } @@ -218,7 +218,7 @@ private static List resolve(IRepositoryHolder repositoryHolder, O } /** - * 统计回查次数的仓储代理,用于断言「对象形态不回查」与「按身份分组批量回查」 + * 统计回查次数的仓储代理,用于断言「对象形态不回查」与「混合身份一次批量回查」 */ private static final class CountingRepositoryHolder { @@ -236,8 +236,8 @@ private IRepositoryHolder proxy() { new Class[]{IRepositoryHolder.class}, (proxy, method, args) -> { switch (method.getName()) { - case "findOperatorByIds" -> batchQueryCount++; - case "getOperatorById" -> singleQueryCount++; + case "findOperatorsByKeys" -> batchQueryCount++; + case "getOperatorByKey" -> singleQueryCount++; default -> { } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue210SubProcessPerformanceTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue210SubProcessPerformanceTest.java index 497d918d..0a5cab01 100644 --- a/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue210SubProcessPerformanceTest.java +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/service/FlowIssue210SubProcessPerformanceTest.java @@ -16,6 +16,7 @@ import com.codingapi.flow.node.nodes.StartNode; import com.codingapi.flow.node.nodes.SubProcessNode; import com.codingapi.flow.operator.IFlowOperator; +import com.codingapi.flow.operator.OperatorKey; import com.codingapi.flow.pojo.body.FlowAdviceBody; import com.codingapi.flow.pojo.request.FlowActionRequest; import com.codingapi.flow.pojo.request.FlowCreateRequest; @@ -167,18 +168,18 @@ private static class DelayedGateway implements FlowOperatorGateway { } @Override - public IFlowOperator get(long id) { + public IFlowOperator get(OperatorKey key) { sleep(); getCalls++; - return delegate.get(id); + return delegate.get(key); } @Override - public List findByIds(List ids) { + public List findByKeys(List keys) { sleep(); findCalls++; - totalIds += ids.size(); - return delegate.findByIds(ids); + totalIds += keys.size(); + return delegate.findByKeys(keys); } private void sleep() {