From d5376c4d80f66445020a25d97a5d37fc780cf2ca Mon Sep 17 00:00:00 2001 From: lorne <1991wangliang@gmail.com> Date: Mon, 16 Nov 2026 22:48:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B5=81=E7=A8=8B=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E8=B5=B0=20FlowEventPublisher=EF=BC=8C?= =?UTF-8?q?=E4=BF=9D=E8=AF=81=E6=8F=90=E4=BA=A4=E5=90=8E=E6=8A=95=E9=80=92?= =?UTF-8?q?=E4=B8=8E=E6=8C=89=E6=B5=81=E7=A8=8B=E4=B8=B2=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 IFlowEventPublisher SPI 与 FlowEventPublisher 门面;IFlowEvent 增加 eventKey() 分区键(默认 processId) - 引擎内全部事件推送点由 EventPusher 收敛到 FlowEventPublisher,未注册实现时自动回退,行为不变 - starter 新增 SpringFlowEventPublisher:事务 afterCommit 投递(回滚不投递)、按 eventKey 分区单线程串行、 同步执行 handler 以获得确定顺序、单 handler 异常不影响后续事件 - 新增配置 codingapi.flow.event.ordered(默认开启) - 补充发布门面与发布器单元测试,更新事件集成文档与 AGENTS.md Closes #274 --- AGENTS.md | 2 +- docs/Integration/event-integration.md | 58 +++-- .../flow/action/actions/AddAuditAction.java | 4 +- .../flow/action/actions/DelegateAction.java | 4 +- .../flow/action/actions/PassAction.java | 4 +- .../action/actions/ReduceAuditAction.java | 4 +- .../flow/action/actions/RejectAction.java | 4 +- .../flow/action/actions/ReturnAction.java | 4 +- .../flow/action/actions/TransferAction.java | 4 +- .../flow/event/FlowEventPublisher.java | 56 +++++ .../flow/event/FlowRecordDeleteEvent.java | 8 + .../flow/event/FlowRecordDoneEvent.java | 8 +- .../flow/event/FlowRecordFinishEvent.java | 8 + .../event/FlowRecordReduceAuditEvent.java | 8 + .../flow/event/FlowRecordRevokeEvent.java | 8 + .../flow/event/FlowRecordStartEvent.java | 8 + .../flow/event/FlowRecordTodoEvent.java | 8 + .../flow/event/FlowRecordUrgeEvent.java | 8 + .../flow/event/FlowSubProcessResetEvent.java | 8 + .../com/codingapi/flow/event/IFlowEvent.java | 11 + .../flow/event/IFlowEventPublisher.java | 22 ++ .../codingapi/flow/node/BaseAuditNode.java | 4 +- .../codingapi/flow/node/nodes/EndNode.java | 4 +- .../flow/service/impl/FlowCreateService.java | 4 +- .../flow/service/impl/FlowDeleteService.java | 4 +- .../flow/service/impl/FlowRevokeService.java | 4 +- .../impl/FlowSubProcessResetService.java | 6 +- .../impl/FlowSubProcessResultService.java | 4 +- .../flow/service/impl/FlowUrgeService.java | 4 +- .../flow/event/FlowEventPublisherTest.java | 133 ++++++++++ .../com/codingapi/flow/AutoConfiguration.java | 15 ++ .../flow/event/SpringFlowEventPublisher.java | 140 +++++++++++ .../event/SpringFlowEventPublisherTest.java | 238 ++++++++++++++++++ 33 files changed, 761 insertions(+), 48 deletions(-) create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java create mode 100644 flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java create mode 100644 flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java create mode 100644 flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java create mode 100644 flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java diff --git a/AGENTS.md b/AGENTS.md index 3949a874..dd8895a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,7 +64,7 @@ REST 层通过请求参数 `mockKey` 分流到 Mock 实例(见 `FlowRecordCont ### 事件(IFlowEvent + EventPusher) -9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)。操作完成后用 `EventPusher.push(event)` 推送;记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 +9 种事件:开始 / 待办 / 已办 / 完成 / 催办 / 撤销(`FlowRecordRevokeEvent`)/ 删除(`FlowRecordDeleteEvent`)/ 子流程重置(`FlowSubProcessResetEvent`)/ 减签(`FlowRecordReduceAuditEvent`)。操作完成后用 `FlowEventPublisher.push(event)` 推送(**禁止**直接调用 `EventPusher`);引入 starter 时由 `SpringFlowEventPublisher` 保证「事务提交后投递 + 按 `eventKey()`(默认 processId)分区串行」,未注册实现时自动回退 `EventPusher`。记录类事件携带 `FlowRecord` + `mock` 标记,重置事件携带新旧聚合组快照。外部可用 Spring `@EventListener` 订阅。 ### API 模块划分 diff --git a/docs/Integration/event-integration.md b/docs/Integration/event-integration.md index 68a27679..ce9527a2 100644 --- a/docs/Integration/event-integration.md +++ b/docs/Integration/event-integration.md @@ -76,7 +76,23 @@ public class FlowRecordUrgeEvent implements IFlowEvent { - 并行:`getParallelId()`、`getParallelBranchNodeId()`、`getParallelBranchTotal()` - 时间:`getCreateTime()`、`getUpdateTime()`、`getFinishTime()`、`getTimeoutTime()` -## 2. 推送:`EventPusher` +## 2. 推送:`FlowEventPublisher`(引擎内统一入口) + +引擎内部**不再直接调用** `EventPusher`,统一走 `com.codingapi.flow.event.FlowEventPublisher`: + +```java +FlowEventPublisher.push(new FlowRecordStartEvent(flowRecord, session.isMock())); +``` + +`FlowEventPublisher` 是门面,行为取决于是否注册了发布器实现(`IFlowEventPublisher`): + +| 场景 | 行为 | +|---|---| +| 引入 `flow-engine-starter`(默认) | 由 `SpringFlowEventPublisher` 投递:**事务提交后**才投递、按 `IFlowEvent.eventKey()`(默认流程id)分区**串行**,见 4.5 | +| 仅使用 framework / 单元测试 | **回退**为 `EventPusher.push`,与旧版本行为一致 | +| 配置 `codingapi.flow.event.ordered=false` | 不注册实现,回退为 `EventPusher.push` | + +底层 `EventPusher`(回退路径)语义: ```java package com.codingapi.springboot.framework.event; @@ -96,12 +112,6 @@ public class EventPusher { } ``` -调用方式(引擎内部统一使用单参形式): - -```java -EventPusher.push(new FlowRecordStartEvent(flowRecord, session.isMock())); -``` - ### 引擎内推送事件的位置 | 位置 | 推送内容 | @@ -184,17 +194,22 @@ public class MyFlowRecordUrgeEventHandler implements IHandler ApplicationHandlerUtils.handler(event)) - 同步:内联执行 - → 按 order() 排序,按泛型匹配执行所有 IHandler +业务代码 → FlowEventPublisher.push(event) + → SpringFlowEventPublisher.push + → 有事务:登记 TransactionSynchronization#afterCommit(提交后才投递;回滚不投递) + → 无事务:立即投递 + → 按 eventKey(默认 processId)散列到单线程分区(同流程串行、跨流程并行) + → ApplicationContext.publishEvent(new DomainEvent(event, sync=true, traceId)) + → SpringDefaultEventHandler.dispatch(同步分支) + → 在分区线程内按 order() 排序,按泛型匹配执行所有 IHandler + → handler 异常仅记录日志,不阻塞同分区后续事件 ``` +回退路径(未注册发布器):`EventPusher.push → DomainEventContext.push → ...` 与旧版本一致。 + ### 4.1 循环事件检测 - 同一 traceId 内,同类事件再次 push 会抛 `EventLoopException`(防止事件→动作→事件的无限循环)。 @@ -214,6 +229,19 @@ public class MyFlowRecordUrgeEventHandler implements IHandler !isEndNodeTodoEvent(event)) - .forEach(EventPusher::push); + .forEach(FlowEventPublisher::push); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java index c2ecbec0..76cb04f2 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReduceAuditAction.java @@ -18,7 +18,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -155,7 +155,7 @@ public void run(FlowSession flowSession) { // 循序审批的链路由通过时的「最近一条更大 nodeOrder」激活保证,撤销中间记录不需要额外补链 repositoryHolder.saveRecords(saveRecords); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } /** diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java index b60cdfc7..ca7db511 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/RejectAction.java @@ -15,7 +15,7 @@ import com.codingapi.flow.script.action.ActionRejectScript; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import lombok.Getter; import java.util.ArrayList; @@ -129,7 +129,7 @@ public void run(FlowSession flowSession) { // 结束节点的虚拟记录不是真实业务待办,其 Todo 事件推送业务订阅方前需拦截 flowEvents.stream() .filter(event -> !isEndNodeTodoEvent(event)) - .forEach(EventPusher::push); + .forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java index e0096645..268cda80 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/ReturnAction.java @@ -12,7 +12,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -78,7 +78,7 @@ public void run(FlowSession flowSession) { repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java index 744ac54b..8d2a085b 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/action/actions/TransferAction.java @@ -15,7 +15,7 @@ import com.codingapi.flow.script.node.OperatorLoadScript; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -107,7 +107,7 @@ public void run(FlowSession flowSession) { } repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } @Override diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java new file mode 100644 index 00000000..fde0104e --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowEventPublisher.java @@ -0,0 +1,56 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.EventPusher; + +/** + * 流程事件发布门面。 + * + *

引擎内统一使用该门面推送事件(不再直接调用 {@code EventPusher.push}):

+ * + */ +public class FlowEventPublisher { + + private static volatile IFlowEventPublisher publisher; + + private FlowEventPublisher() { + } + + /** + * 注册事件发布器实现(由 starter 初始化时调用)。 + * + * @param eventPublisher 事件发布器 + */ + public static void register(IFlowEventPublisher eventPublisher) { + publisher = eventPublisher; + } + + /** + * 注销事件发布器实现,恢复为直接调用 {@code EventPusher}(测试或关闭能力时使用)。 + * + * @param eventPublisher 待注销的事件发布器,仅当其为当前实现时才生效 + */ + public static void unregister(IFlowEventPublisher eventPublisher) { + if (publisher == eventPublisher) { + publisher = null; + } + } + + /** + * 推送流程事件。 + * + * @param event 流程事件 + */ + public static void push(IFlowEvent event) { + IFlowEventPublisher eventPublisher = publisher; + if (eventPublisher == null) { + EventPusher.push(event); + return; + } + eventPublisher.push(event); + } +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java index cb6d1a6a..ba0bebf4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDeleteEvent.java @@ -16,4 +16,12 @@ public class FlowRecordDeleteEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java index 642d6ef1..f8ce2d34 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordDoneEvent.java @@ -15,6 +15,12 @@ public class FlowRecordDoneEvent implements IFlowEvent { private final boolean mock; - + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java index 6db604ce..b3fefa5d 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordFinishEvent.java @@ -14,4 +14,12 @@ public class FlowRecordFinishEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java index 0d989210..3a571d70 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordReduceAuditEvent.java @@ -28,4 +28,12 @@ public class FlowRecordReduceAuditEvent implements IFlowEvent { * 是否为模拟环境 */ private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java index c92aacc9..16bd0895 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordRevokeEvent.java @@ -22,4 +22,12 @@ public class FlowRecordRevokeEvent implements IFlowEvent { * 是否为模拟环境 */ private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return currentRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java index 0cf3ab4e..802f7ed4 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordStartEvent.java @@ -14,4 +14,12 @@ public class FlowRecordStartEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java index 553324ba..98b24067 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordTodoEvent.java @@ -14,4 +14,12 @@ public class FlowRecordTodoEvent implements IFlowEvent { private final FlowRecord flowRecord; private final boolean mock; + + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java index 892bb59a..e3e54ecb 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowRecordUrgeEvent.java @@ -18,4 +18,12 @@ public class FlowRecordUrgeEvent implements IFlowEvent { private final boolean mock; + /** + * 事件分区键:同一流程内的事件按顺序投递 + */ + @Override + public String eventKey() { + return flowRecord.getProcessId(); + } + } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java index 1b496667..dd55d716 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/FlowSubProcessResetEvent.java @@ -44,4 +44,12 @@ public class FlowSubProcessResetEvent implements IFlowEvent { * 是否模拟环境 */ private final boolean mock; + + /** + * 事件分区键:按主流程id串行投递 + */ + @Override + public String eventKey() { + return oldRecord == null ? null : oldRecord.getParentProcessId(); + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java index 343f9621..f1c99ce6 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEvent.java @@ -9,4 +9,15 @@ public interface IFlowEvent extends IAsyncEvent { boolean isMock(); + /** + * 事件分区键,用于保证同一流程内的事件按产生顺序投递。 + * + *

默认为流程id({@code processId}):同一流程的事件严格串行,不同流程可并行。 + * 无法确定流程id的事件返回 null,归入同一默认分区。

+ * + * @return 分区键 + */ + default String eventKey() { + return null; + } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java new file mode 100644 index 00000000..6fbaca0a --- /dev/null +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/event/IFlowEventPublisher.java @@ -0,0 +1,22 @@ +package com.codingapi.flow.event; + +/** + * 流程事件发布器(SPI)。 + * + *

引擎内部所有事件推送都经过 {@link FlowEventPublisher},由该接口的实现决定投递时机与顺序。 + * 由 starter 模块提供 Spring 实现(事务提交后投递、按流程串行);未注册实现时 + * {@link FlowEventPublisher} 回退为直接调用底层 {@code EventPusher},行为与旧版本一致。

+ */ +public interface IFlowEventPublisher { + + /** + * 发布流程事件。 + * + *

实现方须保证:有活动事务时在事务提交后才真正投递、同一 {@link IFlowEvent#eventKey()} + * 的事件按推送顺序投递。

+ * + * @param event 流程事件 + */ + void push(IFlowEvent event); + +} diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java index 2c19c6b9..9dd9bf2f 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/BaseAuditNode.java @@ -14,7 +14,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.strategy.node.MultiOperatorAuditStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -350,7 +350,7 @@ private List autoPassAndGenerateNextNodeRecords(FlowSession session, // 本记录作为后续节点记录的前驱,fromId 链经过当前节点 session.setCurrentRecord(autoPassRecord); records.addAll(this.generateNextNodeRecords(session)); - EventPusher.push(new FlowRecordDoneEvent(autoPassRecord, session.isMock())); + FlowEventPublisher.push(new FlowRecordDoneEvent(autoPassRecord, session.isMock())); return records; } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java index 3749bab2..14d5f771 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/node/nodes/EndNode.java @@ -12,7 +12,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.service.impl.FlowSubProcessResultService; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -72,7 +72,7 @@ public void fillNewRecord(FlowSession session, FlowRecord flowRecord) { // 子流程结束后同步执行主流程结果确认,保证 Mock 与生产环境行为一致。 new FlowSubProcessResultService(latestRecord, repositoryHolder).complete(); // 流程是否正常结束 - EventPusher.push(new FlowRecordFinishEvent(latestRecord, session.isMock())); + FlowEventPublisher.push(new FlowRecordFinishEvent(latestRecord, session.isMock())); } 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 db5a5621..7f0de567 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 @@ -21,7 +21,7 @@ import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import org.springframework.util.StringUtils; import java.util.ArrayList; @@ -108,7 +108,7 @@ public long create() { // 推送事件 for (IFlowEvent event : events) { - EventPusher.push(event); + FlowEventPublisher.push(event); } FlowRecord currentRecord = flowRecords.get(0); diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java index 66d32ebb..a0cfa86e 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowDeleteService.java @@ -10,7 +10,7 @@ import com.codingapi.flow.record.FlowRecord; import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.session.IRepositoryHolder; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.List; @@ -67,6 +67,6 @@ public void delete() { // 删除流程记录及其关联待办 flowRecordService.deleteFlowRecord(currentRecord); // 推送删除事件 - EventPusher.push(new FlowRecordDeleteEvent(currentRecord, repositoryHolder instanceof MockRepositoryHolder)); + FlowEventPublisher.push(new FlowRecordDeleteEvent(currentRecord, repositoryHolder instanceof MockRepositoryHolder)); } } diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java index c9e31db0..e9724c05 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowRevokeService.java @@ -19,7 +19,7 @@ import com.codingapi.flow.strategy.node.RevokeStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.HashSet; @@ -143,7 +143,7 @@ public void revoke() { } repositoryHolder.saveRecords(recordList); - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } 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 d913015d..93384453 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 @@ -25,7 +25,7 @@ import com.codingapi.flow.strategy.node.SubProcessStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.Comparator; @@ -183,9 +183,9 @@ public void reset() { boolean mock = repositoryHolder instanceof MockRepositoryHolder; IFlowOperator resetOperator = repositoryHolder.getOperatorById(request.getOperatorId()); for (FlowRecord invalidatedRecord : invalidatedRecords) { - EventPusher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); + FlowEventPublisher.push(new FlowRecordRevokeEvent(invalidatedRecord, mock)); } - EventPusher.push(new FlowSubProcessResetEvent( + FlowEventPublisher.push(new FlowSubProcessResetEvent( currentGroup.snapshot(), newGroup.snapshot(), currentRecord.getId(), diff --git a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java index b96fa8db..d8b22562 100644 --- a/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java +++ b/flow-engine-framework/src/main/java/com/codingapi/flow/service/impl/FlowSubProcessResultService.java @@ -16,7 +16,7 @@ import com.codingapi.flow.session.FlowSession; import com.codingapi.flow.session.IRepositoryHolder; import com.codingapi.flow.strategy.node.SubProcessStrategy; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -120,6 +120,6 @@ private void save(List records, List events) { if (!records.isEmpty()) { repositoryHolder.saveRecords(records); } - events.forEach(EventPusher::push); + events.forEach(FlowEventPublisher::push); } } 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 bbb2870e..ea07c009 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 @@ -19,7 +19,7 @@ import com.codingapi.flow.strategy.workflow.UrgeStrategy; import com.codingapi.flow.workflow.Workflow; import com.codingapi.flow.workflow.runtime.WorkflowRuntime; -import com.codingapi.springboot.framework.event.EventPusher; +import com.codingapi.flow.event.FlowEventPublisher; import java.util.ArrayList; import java.util.List; @@ -91,6 +91,6 @@ public void urge() { flowEvents.add(new FlowRecordUrgeEvent(todoRecord, currentOperator,repositoryHolder instanceof MockRepositoryHolder)); } - flowEvents.forEach(EventPusher::push); + flowEvents.forEach(FlowEventPublisher::push); } } diff --git a/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java b/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java new file mode 100644 index 00000000..6a4638ba --- /dev/null +++ b/flow-engine-framework/src/test/java/com/codingapi/flow/event/FlowEventPublisherTest.java @@ -0,0 +1,133 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import com.codingapi.springboot.framework.event.IEvent; +import com.codingapi.springboot.framework.event.SpringEventInitializer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FlowEventPublisherTest { + + private final List capturedEvents = new ArrayList<>(); + + private static class TestFlowEvent implements IFlowEvent { + + private final String eventKey; + private final boolean mock; + + private TestFlowEvent(String eventKey, boolean mock) { + this.eventKey = eventKey; + this.mock = mock; + } + + @Override + public boolean isMock() { + return mock; + } + + @Override + public String eventKey() { + return eventKey; + } + } + + private static class RecordPublisher implements IFlowEventPublisher { + + private final List events = new ArrayList<>(); + + @Override + public void push(IFlowEvent event) { + events.add(event); + } + } + + @AfterEach + void clearEventContext() throws Exception { + Class clazz = Class.forName("com.codingapi.springboot.framework.event.DomainEventContext"); + java.lang.reflect.Method getInstance = clazz.getDeclaredMethod("getInstance"); + getInstance.setAccessible(true); + Object instance = getInstance.invoke(null); + Field field = clazz.getDeclaredField("context"); + field.setAccessible(true); + field.set(instance, null); + } + + /** + * 测试目标:未注册发布器实现时,事件推送仍走底层 EventPusher,行为与旧版本一致。 + * 前置条件:未注册 IFlowEventPublisher。 + * 执行步骤:通过门面推送一个事件。 + * 期望断言:事件被发布到底层事件框架。 + */ + @Test + void shouldDelegateToEventPusherWhenNoPublisherRegistered() throws Exception { + initEventCapture(); + + TestFlowEvent event = new TestFlowEvent("process-1", false); + FlowEventPublisher.push(event); + + assertEquals(1, capturedEvents.size(), "未注册发布器时应回退到底层 EventPusher"); + assertTrue(capturedEvents.get(0) == event, "推送的应为同一个事件实例"); + } + + /** + * 测试目标:注册发布器实现后,事件由实现投递,不再直接进入底层事件框架。 + * 前置条件:调用 register 注册自定义发布器。 + * 执行步骤:通过门面推送事件。 + * 期望断言:实现收到事件,底层事件框架无感知。 + */ + @Test + void shouldDelegateToRegisteredPublisher() throws Exception { + initEventCapture(); + RecordPublisher publisher = new RecordPublisher(); + FlowEventPublisher.register(publisher); + try { + TestFlowEvent event = new TestFlowEvent("process-2", true); + FlowEventPublisher.push(event); + + assertEquals(1, publisher.events.size(), "应交由注册的实现投递"); + assertTrue(publisher.events.get(0) == event); + assertTrue(capturedEvents.isEmpty(), "注册实现后不应再直接推送到底层框架"); + } finally { + FlowEventPublisher.unregister(publisher); + } + } + + /** + * 测试目标:注销发布器实现后,事件推送恢复为底层 EventPusher。 + * 前置条件:先注册再注销自定义发布器。 + * 执行步骤:通过门面推送事件。 + * 期望断言:重新回退到底层事件框架。 + */ + @Test + void shouldFallbackToEventPusherAfterUnregister() throws Exception { + initEventCapture(); + RecordPublisher publisher = new RecordPublisher(); + FlowEventPublisher.register(publisher); + FlowEventPublisher.unregister(publisher); + + FlowEventPublisher.push(new TestFlowEvent("process-3", false)); + + assertTrue(publisher.events.isEmpty(), "注销后不应再调用已注销的实现"); + assertEquals(1, capturedEvents.size(), "注销后应回退到底层 EventPusher"); + } + + private void initEventCapture() throws Exception { + ApplicationContext context = Mockito.mock(ApplicationContext.class); + Mockito.doAnswer(invocation -> { + DomainEvent domainEvent = invocation.getArgument(0); + capturedEvents.add(domainEvent.getEvent()); + return null; + }).when(context).publishEvent(Mockito.any(ApplicationEvent.class)); + new SpringEventInitializer(context).afterPropertiesSet(); + } +} diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java index 7dbaab48..1d0de03a 100644 --- a/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/AutoConfiguration.java @@ -1,6 +1,8 @@ package com.codingapi.flow; import com.codingapi.flow.context.RepositoryHolderContext; +import com.codingapi.flow.event.IFlowEventPublisher; +import com.codingapi.flow.event.SpringFlowEventPublisher; import com.codingapi.flow.gateway.FlowOperatorGateway; import com.codingapi.flow.register.NodeViewJavaScriptCacheContextRegister; import com.codingapi.flow.register.RepositoryHolderContextRegister; @@ -11,6 +13,8 @@ import com.codingapi.flow.service.FlowRecordService; import com.codingapi.flow.service.FlowService; import com.codingapi.flow.service.WorkflowService; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -35,6 +39,17 @@ public GatewayContextRegister gatewayContextRegister(FlowOperatorGateway flowOpe return new GatewayContextRegister(flowOperatorGateway); } + /** + * 流程事件发布器:事务提交后投递 + 按流程id分区串行(issue #274)。 + * 可通过 codingapi.flow.event.ordered=false 关闭,关闭后回退为直接推送到事件框架。 + */ + @Bean + @ConditionalOnMissingBean(IFlowEventPublisher.class) + @ConditionalOnProperty(value = "codingapi.flow.event.ordered", matchIfMissing = true) + public SpringFlowEventPublisher flowEventPublisher(ApplicationContext applicationContext) { + return new SpringFlowEventPublisher(applicationContext); + } + @Bean public FlowScriptContextRegister flowScriptContextRegister( ApplicationContext spring, diff --git a/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java b/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java new file mode 100644 index 00000000..f8386ead --- /dev/null +++ b/flow-engine-starter/src/main/java/com/codingapi/flow/event/SpringFlowEventPublisher.java @@ -0,0 +1,140 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 流程事件发布器的 Spring 实现(issue #274)。 + * + *

解决两个长期存在的一致性风险:

+ *
    + *
  1. 事务可见性:有活动事务时,事件通过 {@link TransactionSynchronization#afterCommit()} + * 在事务提交后才投递,订阅方回查数据库一定能读到流程记录/待办/关系数据;事务回滚则不投递。
  2. + *
  3. 投递顺序:按 {@link IFlowEvent#eventKey()}(默认流程id)散列到固定的单线程分区, + * 同一流程的事件严格按产生顺序投递,不同流程可并行;投递时使用同步事件 + * ({@code DomainEvent(sync=true)})在分区线程内完成 handler 调用,避免再落入底层线程池导致乱序。
  4. + *
+ * + *

与底层 {@code EventPusher} 的关系:未注册本实现时(仅使用 framework、单元测试等场景), + * {@link FlowEventPublisher} 直接回退 {@code EventPusher.push},行为与旧版本一致。 + * handler 抛出异常时只记录日志,不阻塞同分区后续事件的投递。

+ */ +@Slf4j +public class SpringFlowEventPublisher implements IFlowEventPublisher, InitializingBean, DisposableBean { + + /** + * 默认分区数:分区内串行、分区间并行 + */ + private static final int DEFAULT_PARTITION_SIZE = 4; + + private final ApplicationContext applicationContext; + + private final ExecutorService[] partitions; + + public SpringFlowEventPublisher(ApplicationContext applicationContext) { + this(applicationContext, DEFAULT_PARTITION_SIZE); + } + + public SpringFlowEventPublisher(ApplicationContext applicationContext, int partitionSize) { + this.applicationContext = applicationContext; + int size = Math.max(1, partitionSize); + this.partitions = new ExecutorService[size]; + } + + @Override + public void afterPropertiesSet() { + for (int i = 0; i < partitions.length; i++) { + partitions[i] = Executors.newSingleThreadExecutor(new FlowEventThreadFactory(i)); + } + FlowEventPublisher.register(this); + log.info("SpringFlowEventPublisher success initial, partitions:{}", partitions.length); + } + + @Override + public void push(IFlowEvent event) { + if (event == null) { + return; + } + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCommit() { + dispatch(event); + } + }); + return; + } + dispatch(event); + } + + /** + * 提交事件到对应分区:分区的单线程执行器天然保证「先提交先执行」。 + */ + private void dispatch(IFlowEvent event) { + String eventKey = event.eventKey(); + int index = eventKey == null ? 0 : Math.floorMod(eventKey.hashCode(), partitions.length); + partitions[index].execute(() -> publish(event)); + } + + /** + * 以同步事件方式投递,使 handler 在当前分区线程内执行完毕,从而获得确定顺序。 + */ + private void publish(IFlowEvent event) { + try { + applicationContext.publishEvent(new DomainEvent(event, true, generateTraceId())); + } catch (Exception e) { + log.error("flow event dispatch failed, eventType:{}, eventKey:{}", + event.getClass().getName(), safeEventKey(event), e); + } + } + + private String safeEventKey(IFlowEvent event) { + try { + return event.eventKey(); + } catch (Exception e) { + return null; + } + } + + private String generateTraceId() { + return UUID.randomUUID().toString().replace("-", ""); + } + + @Override + public void destroy() { + FlowEventPublisher.unregister(this); + for (ExecutorService partition : partitions) { + if (partition != null) { + partition.shutdown(); + } + } + } + + private static class FlowEventThreadFactory implements ThreadFactory { + + private final int index; + private final AtomicInteger counter = new AtomicInteger(1); + + private FlowEventThreadFactory(int index) { + this.index = index; + } + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "flow-event-dispatch-" + index + "-" + counter.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java new file mode 100644 index 00000000..4ad772e9 --- /dev/null +++ b/flow-engine-starter/src/test/java/com/codingapi/flow/event/SpringFlowEventPublisherTest.java @@ -0,0 +1,238 @@ +package com.codingapi.flow.event; + +import com.codingapi.springboot.framework.event.DomainEvent; +import com.codingapi.springboot.framework.event.IHandler; +import com.codingapi.springboot.framework.event.SpringDefaultEventHandler; +import com.codingapi.springboot.framework.properties.FrameworkProperties; +import com.codingapi.springboot.framework.properties.PropertiesContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEvent; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 流程事件发布器(提交后投递 + 分区串行)测试。 + */ +class SpringFlowEventPublisherTest { + + private static final List HANDLED = new CopyOnWriteArrayList<>(); + private static final List HANDLED_THREADS = new CopyOnWriteArrayList<>(); + private static volatile int slowEventId = -1; + private static volatile int failEventId = -1; + + private static ApplicationContext applicationContext; + + private SpringFlowEventPublisher publisher; + + static class TestFlowEvent implements IFlowEvent { + + private final int id; + private final String eventKey; + private final boolean mock; + + private TestFlowEvent(int id, String eventKey, boolean mock) { + this.id = id; + this.eventKey = eventKey; + this.mock = mock; + } + + @Override + public boolean isMock() { + return mock; + } + + @Override + public String eventKey() { + return eventKey; + } + } + + static class Recorder implements IHandler { + + @Override + public void handler(TestFlowEvent event) { + if (event.id == slowEventId) { + sleep(80); + } + if (event.id == failEventId) { + throw new IllegalStateException("handler error, eventId:" + event.id); + } + HANDLED.add(event.id); + HANDLED_THREADS.add(Thread.currentThread().getName()); + } + } + + @BeforeAll + static void initEventFramework() throws Exception { + PropertiesContext.getInstance().setProperties(new FrameworkProperties()); + SpringDefaultEventHandler eventHandler = new SpringDefaultEventHandler(List.of(new Recorder())); + eventHandler.afterPropertiesSet(); + + applicationContext = Mockito.mock(ApplicationContext.class); + Mockito.doAnswer(invocation -> { + DomainEvent domainEvent = invocation.getArgument(0); + eventHandler.dispatch(domainEvent); + return null; + }).when(applicationContext).publishEvent(Mockito.any(ApplicationEvent.class)); + } + + @AfterEach + void tearDown() { + if (publisher != null) { + publisher.destroy(); + publisher = null; + } + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + HANDLED.clear(); + HANDLED_THREADS.clear(); + slowEventId = -1; + failEventId = -1; + } + + /** + * 测试目标:事务内推送的事件必须等事务提交后才投递给订阅方。 + * 前置条件:存在活动事务同步。 + * 执行步骤:事务内连续推送两个事件 → 提交前观察 → afterCommit 后观察。 + * 期望断言:提交前无任何 handler 执行;提交后按产生顺序依次执行。 + */ + @Test + void shouldDispatchOnlyAfterCommit() throws Exception { + publisher = newPublisher(); + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-a", false)); + publisher.push(new TestFlowEvent(2, "process-a", false)); + + assertTrue(HANDLED.isEmpty(), "事务提交前不应投递事件"); + + commit(); + + awaitHandled(2); + assertEquals(List.of(1, 2), HANDLED, "提交后应按产生顺序投递"); + } + + /** + * 测试目标:事务回滚时事件不应投递。 + * 前置条件:存在活动事务同步。 + * 执行步骤:事务内推送事件 → 回滚(不触发 afterCommit)。 + * 期望断言:订阅方始终收不到事件。 + */ + @Test + void shouldNotDispatchWhenTransactionRolledBack() throws Exception { + publisher = newPublisher(); + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-b", false)); + for (TransactionSynchronization synchronization : TransactionSynchronizationManager.getSynchronizations()) { + synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); + } + + sleep(150); + assertTrue(HANDLED.isEmpty(), "事务回滚后不应投递事件"); + } + + /** + * 测试目标:同一流程(相同 eventKey)的事件严格按推送顺序投递,即使先推送的事件处理较慢。 + * 前置条件:存在活动事务同步,首个事件 handler 耗时 80ms。 + * 执行步骤:推送三个同 eventKey 事件 → 提交。 + * 期望断言:handler 执行顺序与推送顺序一致。 + */ + @Test + void shouldKeepOrderForSameEventKey() throws Exception { + publisher = newPublisher(); + slowEventId = 1; + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-c", false)); + publisher.push(new TestFlowEvent(2, "process-c", false)); + publisher.push(new TestFlowEvent(3, "process-c", false)); + + commit(); + + awaitHandled(3); + assertEquals(List.of(1, 2, 3), HANDLED, "同一分区内必须按推送顺序执行"); + } + + /** + * 测试目标:无事务上下文时(如定时任务、mock 调用)事件立即投递。 + * 前置条件:不存在活动事务同步。 + * 执行步骤:直接推送事件。 + * 期望断言:订阅方收到事件,且执行线程为事件投递线程。 + */ + @Test + void shouldDispatchImmediatelyWithoutTransaction() throws Exception { + publisher = newPublisher(); + + publisher.push(new TestFlowEvent(1, "process-d", true)); + + awaitHandled(1); + assertEquals(List.of(1), HANDLED); + assertTrue(HANDLED_THREADS.get(0).startsWith("flow-event-dispatch-"), + "应在事件投递线程内执行,实际线程:" + HANDLED_THREADS.get(0)); + } + + /** + * 测试目标:单个事件的 handler 异常不应阻塞同分区后续事件。 + * 前置条件:首个事件的 handler 抛出异常。 + * 执行步骤:推送两个同 eventKey 事件 → 提交。 + * 期望断言:第二个事件仍被正常处理。 + */ + @Test + void shouldContinueDispatchWhenHandlerThrows() throws Exception { + publisher = newPublisher(); + failEventId = 1; + TransactionSynchronizationManager.initSynchronization(); + + publisher.push(new TestFlowEvent(1, "process-e", false)); + publisher.push(new TestFlowEvent(2, "process-e", false)); + + commit(); + + awaitHandled(1); + sleep(100); + assertEquals(List.of(2), HANDLED, "handler 异常不应影响后续事件投递"); + } + + private SpringFlowEventPublisher newPublisher() throws Exception { + SpringFlowEventPublisher eventPublisher = new SpringFlowEventPublisher(applicationContext, 1); + eventPublisher.afterPropertiesSet(); + return eventPublisher; + } + + private void commit() { + List synchronizations = + new ArrayList<>(TransactionSynchronizationManager.getSynchronizations()); + for (TransactionSynchronization synchronization : synchronizations) { + synchronization.afterCommit(); + } + TransactionSynchronizationManager.clearSynchronization(); + } + + private void awaitHandled(int expected) throws InterruptedException { + long deadline = System.currentTimeMillis() + 3000; + while (System.currentTimeMillis() < deadline && HANDLED.size() < expected) { + sleep(10); + } + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +}