From ac9812e0a149ee041f277610a19fcc52972b001b Mon Sep 17 00:00:00 2001 From: zhengwr Date: Thu, 11 Jun 2026 15:12:03 +0800 Subject: [PATCH] =?UTF-8?q?P3-4:=20platform-flow-gateway=20=E5=8D=95?= =?UTF-8?q?=E4=BD=93=E4=BE=A7=E6=B5=81=E7=A8=8B=E7=BD=91=E5=85=B3(Flowable?= =?UTF-8?q?=20REST=20=E5=AE=A2=E6=88=B7=E7=AB=AF=20+=20=E5=BE=85=E5=8A=9E?= =?UTF-8?q?=E8=81=9A=E5=90=88=20+=20=E4=BA=8B=E4=BB=B6=E5=9B=9E=E5=86=99)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FlowableClient:RestClient 调 flowable-service(eip4.flow.base-url,默认 8089); 超时/重试(仅连接级)/熔断降级——引擎不可达 → 503 语义(非 500 堆栈),业务错 4xx/5xx 透传。 - 待办聚合(经 platform-app 暴露):GET /api/todo(JWT userId+roles 候选组)、GET /api/done、 POST /api/task/{id}/complete、POST /api/process/start;聚合层把 Flowable 任务与业务摘要连接 (businessKey → SYS_DATASTATUS.tablename → loadPOJO 只读标题字段;业务摘要数据源客户库只读, 拼不到优雅降级为仅流程字段)。 - 事件回写:complete 后按老系统 ProcessCoreServiceImpl.passProcess + WfChangeStatus 语义更新 SYS_DATASTATUS(结束→STATUS_PASS=3,未结束→STATUS_PROCESSING=2,守卫 oldstatus --- docs/迁移手册.md | 21 ++ .../eip4/flowservice/api/FlowController.java | 62 +++++- .../com/eip4/flowservice/api/TaskDto.java | 2 + platform-flow-gateway/P3网关实测报告.md | 184 +++++++++++++++++ platform-flow-gateway/pom.xml | 32 ++- .../aggregate/BusinessSummaryService.java | 129 ++++++++++++ .../flowgateway/aggregate/TodoAggregator.java | 67 ++++++ .../flowgateway/aggregate/TodoItem.java | 52 +++++ .../flowgateway/client/FlowGatewayConfig.java | 39 ++++ .../client/FlowGatewayProperties.java | 76 +++++++ .../client/FlowRemoteException.java | 24 +++ .../FlowServiceUnavailableException.java | 16 ++ .../flowgateway/client/FlowTaskDto.java | 23 +++ .../flowgateway/client/FlowableClient.java | 191 ++++++++++++++++++ .../client/ProcessInstanceDto.java | 16 ++ .../web/FlowGatewayExceptionHandler.java | 43 ++++ .../flowgateway/web/GatewayRequests.java | 33 +++ .../flowgateway/web/TodoController.java | 119 +++++++++++ .../writeback/StatusWriteback.java | 90 +++++++++ .../bootstrap/bootstrap-datastatus.sql | 46 +++++ .../BusinessSummaryServiceTest.java | 105 ++++++++++ .../flowgateway/FlowableClientTest.java | 120 +++++++++++ .../flowgateway/StatusWritebackTest.java | 118 +++++++++++ .../flowgateway/TodoAggregatorTest.java | 102 ++++++++++ 24 files changed, 1707 insertions(+), 3 deletions(-) create mode 100644 platform-flow-gateway/P3网关实测报告.md create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessSummaryService.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoAggregator.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoItem.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayConfig.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayProperties.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowRemoteException.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowServiceUnavailableException.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowTaskDto.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowableClient.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/ProcessInstanceDto.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/FlowGatewayExceptionHandler.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java create mode 100644 platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/writeback/StatusWriteback.java create mode 100644 platform-flow-gateway/src/main/resources/bootstrap/bootstrap-datastatus.sql create mode 100644 platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/BusinessSummaryServiceTest.java create mode 100644 platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/FlowableClientTest.java create mode 100644 platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/StatusWritebackTest.java create mode 100644 platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/TodoAggregatorTest.java diff --git a/docs/迁移手册.md b/docs/迁移手册.md index cb9f049..61f803f 100644 --- a/docs/迁移手册.md +++ b/docs/迁移手册.md @@ -535,6 +535,27 @@ com.dsasp.* com.eip4.* | **对策** | 待办查询/聚合层须按 padding 后形态匹配 assignee;REST 调用方(P3-4 gateway/前端)须知此口径,或在聚合层统一 padding 规整 | | **影响范围** | 所有按 assignee 精确查询的待办接口;实测 padded assignee(尾 4 空格)REST 待办数=act_ru_task 直查数=12,trim 形态=0 | +### 6.8 Flowable 6.8.1 Task 接口无 businessKey;待办聚合须由查询侧从实例补全 [NEW 2026-06-11] + +| 栏目 | 内容 | +|------|------| +| **现象** | P3-4 gateway 待办聚合需「任务 businessKey → 业务表数据摘要」,但 flowable-service 原 `TaskDto` 不含 businessKey,gateway 无从连接业务数据 | +| **根因** | Flowable 6.8.1 `org.flowable.task.api.TaskInfo`(Task/HistoricTaskInstance 共同父接口)**无 `getBusinessKey()`**(javap 核实,仅 `getProcessInstanceId()`);businessKey 在 process instance 上,不在 task 上 | +| **对策** | flowable-service 查询侧契约增强:`TaskDto` 加 `businessKey` 字段,`/tasks/todo` 用 `runtimeService`、`/tasks/done` 用 `historyService` 按 `processInstanceId` 反查实例 businessKey 补全;另加 `GET /api/flow/process/{id}` 查实例(运行中 ended=false / 已结束历史实例 ended=true / 不存在 404),供 gateway 办理后判定流程是否结束以回写业务状态。gateway 据 `businessKey` 经 `SYS_DATASTATUS.tablename` 映射 + `loadPOJO` 读业务摘要 | +| **影响范围** | 任何需要 task↔业务数据连接的聚合层;契约演进已记入 `flowable-service` REST(todo/done 出参多 businessKey 字段,新增 GET /process/{id});实测 8089 todo 返回 businessKey 与 act_ru_execution.business_key_ 一致 | + +### 6.9 单体侧流程网关 503 熔断语义 + SYS_DATASTATUS 回写守卫 [NEW 2026-06-11] + +| 栏目 | 内容 | +|------|------| +| **现象一·熔断** | gateway(platform-app 内)是 flowable-service(8089)的 REST 客户端;引擎进程宕机/网络分区时,待办聚合若直接抛出 RestClient 的 `ResourceAccessException` → Spring 默认 500 + 堆栈,语义错误且暴露内部 | +| **对策一** | `FlowableClient` 三道纪律:超时(connect/read 配置化)、重试(仅连接级瞬时故障带退避重试 `eip4.flow.max-retries` 次,业务级 4xx/5xx 绝不重试)、熔断降级(重试耗尽 → `FlowServiceUnavailableException` → `@RestControllerAdvice` 映射 **503** `FLOW_SERVICE_UNAVAILABLE`;引擎在线但拒绝如挂起拒办 409 → `FlowRemoteException` 透传原状态码)。实测:kill 8089 后 `/api/todo` 返回 503 干净 JSON,platform-app 进程存活不崩 | +| **现象二·回写守卫** | 办理(complete)后须按老系统语义回写 `SYS_DATASTATUS.DATASTATUS`;若无守卫,会在无业务状态记录时凭空 INSERT、或把已「通过(3)」回退 | +| **根因/口径** | 逐条对齐 framework `WfChangeStatus`(upsert:先 UPDATE,0 行则 INSERT BUSINESSKEY/TABLENAME/DATASTATUS)+ `ProcessCoreServiceImpl.passProcess`:`status = 流程已结束 ? STATUS_PASS(3) : STATUS_PROCESSING(2)`,且**仅当 `oldstatus != null && oldstatus < status`** 才回写(单调递增,不回退、不在无记录时凭空插入)。DATASTATUS 值语义=`ProcessCoreService` 常量:1 未提交/2 处理中(在批)/3 通过(已归档)/4 未通过/5 重新提交/6 作废 | +| **对策二** | `StatusWriteback.afterComplete` 复刻该守卫;参数化占位收敛原版裸拼注入面(语义不变)。**本地库验证,客户库只读**:回写仅在连本地 eip4m0(可写)时执行,生产/客户库形态由最小权限只读连接约束。实测:本地构造 SYS_DATASTATUS 行 datastatus=1,经 8090 complete(流程结束 ended=true)回写为 3;守卫负向(已达 3 / 无记录)由单测覆盖 | +| **新坑·SYS_DATASTATUS 无主键** | SYS_DATASTATUS 客户库物理表无主键(§7.2 已登记);本地自举表对齐该口径(不建主键,businesskey 上建普通索引),`bootstrap-datastatus.sql`(platform-flow-gateway 模块)随 P3-4 提供 | +| **影响范围** | platform-flow-gateway 全模块;聚合 API `/api/todo`、`/api/done`、`/api/task/{id}/complete`、`/api/process/start`(经 platform-app 暴露,JWT 取 userId/roles) | + --- ## 七、库内数据质量已知问题 diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java b/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java index 40619a6..578ea6b 100644 --- a/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/FlowController.java @@ -62,9 +62,28 @@ public class FlowController { if (candidateUser != null && !candidateUser.isBlank()) { q = q.taskCandidateUser(candidateUser); } - return q.orderByTaskCreateTime().desc() + List dtos = q.orderByTaskCreateTime().desc() .listPage(firstResult, maxResults) .stream().map(TaskDto::of).collect(Collectors.toList()); + fillBusinessKeyFromRuntime(dtos); + return dtos; + } + + /** + * 补全活动待办的 businessKey(Flowable 6.8.1 Task 接口无此字段,从运行时实例反查)。 + * 供 gateway 聚合业务摘要;按 processInstanceId 单值查实例 businessKey,缺失则留 null。 + */ + private void fillBusinessKeyFromRuntime(List dtos) { + for (TaskDto d : dtos) { + if (d.processInstanceId == null) { + continue; + } + ProcessInstance pi = runtimeService.createProcessInstanceQuery() + .processInstanceId(d.processInstanceId).singleResult(); + if (pi != null) { + d.businessKey = pi.getBusinessKey(); + } + } } @GetMapping("/tasks/todo/count") @@ -87,9 +106,25 @@ public class FlowController { if (assignee != null && !assignee.isBlank()) { q = q.taskAssignee(assignee); } - return q.orderByHistoricTaskInstanceEndTime().desc() + List dtos = q.orderByHistoricTaskInstanceEndTime().desc() .listPage(firstResult, maxResults) .stream().map(TaskDto::of).collect(Collectors.toList()); + fillBusinessKeyFromHistory(dtos); + return dtos; + } + + /** 补全已办的 businessKey(从历史实例反查)。供 gateway 聚合业务摘要。 */ + private void fillBusinessKeyFromHistory(List dtos) { + for (TaskDto d : dtos) { + if (d.processInstanceId == null) { + continue; + } + var hpi = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(d.processInstanceId).singleResult(); + if (hpi != null) { + d.businessKey = hpi.getBusinessKey(); + } + } } @PostMapping("/process/start") @@ -117,6 +152,29 @@ public class FlowController { return ResponseEntity.noContent().build(); } + @GetMapping("/process/{processInstanceId}") + @Operation(summary = "查实例", description = "查流程实例:运行中返回 ended=false;已结束返回历史实例 ended=true;不存在 404。供 gateway 办理后判定流程是否结束以回写业务状态") + public ResponseEntity processInstance(@PathVariable String processInstanceId) { + ProcessInstance pi = runtimeService.createProcessInstanceQuery() + .processInstanceId(processInstanceId).singleResult(); + if (pi != null) { + return ResponseEntity.ok(ProcessInstanceDto.of(pi)); + } + var hpi = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(processInstanceId).singleResult(); + if (hpi == null) { + return ResponseEntity.notFound().build(); + } + ProcessInstanceDto d = new ProcessInstanceDto(); + d.id = hpi.getId(); + d.processDefinitionId = hpi.getProcessDefinitionId(); + d.processDefinitionKey = hpi.getProcessDefinitionKey(); + d.businessKey = hpi.getBusinessKey(); + d.ended = hpi.getEndTime() != null; + d.suspended = false; + return ResponseEntity.ok(d); + } + @PostMapping("/process/{processInstanceId}/suspend") @Operation(summary = "挂起实例", description = "挂起后该实例任务不可办理") public ResponseEntity suspend(@PathVariable String processInstanceId) { diff --git a/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java b/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java index 052b85a..2556825 100644 --- a/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java +++ b/flowable-service/src/main/java/com/eip4/flowservice/api/TaskDto.java @@ -14,6 +14,8 @@ public class TaskDto { public String processInstanceId; public String processDefinitionId; public String taskDefinitionKey; + /** 流程业务主键(Flowable 6.8.1 Task/HistoricTaskInstance 接口无此字段,由查询侧从实例补全;供 gateway 聚合业务摘要)。 */ + public String businessKey; public Long createTimeMillis; public Long endTimeMillis; public boolean suspended; diff --git a/platform-flow-gateway/P3网关实测报告.md b/platform-flow-gateway/P3网关实测报告.md new file mode 100644 index 0000000..3380c42 --- /dev/null +++ b/platform-flow-gateway/P3网关实测报告.md @@ -0,0 +1,184 @@ +# P3-4 单体侧流程网关 实测报告 + +> 日期:2026-06-11 | 模块:`platform-flow-gateway`(单体 platform-app 内的 Flowable 客户端 + 待办聚合 + 事件回写) +> 任务:P3-4 —— FlowableClient(REST 客户端 + 超时/重试/熔断降级)、待办聚合 API(经 platform-app 暴露)、 +> 事件回写(complete 后按老系统 ProcessCoreServiceImpl/WfChangeStatus 语义更新 SYS_DATASTATUS) +> 验证场:flowable-service 起 8089(连本地 `eip4flow.eip3` 6.8.1 真实迁移数据 + 客户库副本 `192.168.20.68:5435` 组织只读); +> platform-app 起 8090(local profile,连本地 `eip4m0`,可写);8084 未动 +> 架构定位:引擎在独立 flowable-service(四进程之一),gateway **只做 REST 客户端**(架构第三节) + +--- + +## 一、模块结构 + +``` +platform-flow-gateway/ 单体 platform-app 内组件(com.eip4.platform.flowgateway) +├── pom.xml 依赖 platform-legacy-core(loadPOJO 业务摘要)+ platform-auth(JWT ctx) +│ + spring-boot-starter-web/jdbc + springdoc +├── src/main/java/com/eip4/platform/flowgateway/ +│ ├── client/ ★ Flowable REST 客户端 +│ │ ├── FlowGatewayProperties 配置(eip4.flow.base-url 默认 http://localhost:8089 / 超时 / 重试) +│ │ ├── FlowGatewayConfig RestClient bean(超时落到请求工厂) +│ │ ├── FlowableClient 超时/重试(仅连接级)/熔断降级;调 8089 待办/已办/办理/发起/查实例 +│ │ ├── FlowServiceUnavailableException 引擎不可达 → 503 语义载体 +│ │ ├── FlowRemoteException 引擎在线但拒绝(4xx/5xx)→ 透传原状态码 +│ │ ├── FlowTaskDto / ProcessInstanceDto 出参契约(贴 flowable-service DTO) +│ ├── aggregate/ ★ 待办聚合 +│ │ ├── TodoItem 聚合条目:流程字段 + 业务摘要 +│ │ ├── BusinessSummaryService businessKey → SYS_DATASTATUS.tablename → loadPOJO 标题字段;全程降级兜底 +│ │ └── TodoAggregator 调 client + 逐条拼业务摘要 +│ ├── writeback/ +│ │ └── StatusWriteback ★ 事件回写(对齐 WfChangeStatus + passProcess 语义) +│ └── web/ ★ 经 platform-app 暴露的聚合 API +│ ├── TodoController GET /api/todo、GET /api/done、POST /api/task/{id}/complete、POST /api/process/start +│ ├── GatewayRequests 入参 DTO(办理/发起) +│ └── FlowGatewayExceptionHandler 503 熔断 + 业务错透传 +├── src/main/resources/bootstrap/ +│ └── bootstrap-datastatus.sql 本地回写验证自举(SYS_DATASTATUS 表 + 测试实体行) +└── src/test/java/ (21 单测) + ├── FlowableClientTest 5(重试耗尽降级 503 / 409 透传不重试 / 待办解析 / 候选组多值 / 404→null) + ├── BusinessSummaryServiceTest 5(businessKey 空 / 无映射降级 / loadPOJO 异常降级 / 标题字段剔系统列 / null 降级) + ├── TodoAggregatorTest 4(拼接业务摘要 / 摘要拼不到降级 / 已办拼接 / 空列表) + └── StatusWritebackTest 7(未结束→2 / 结束→3 / null 不写 / 已达 3 不回退 / upsert UPDATE 命中或 0 行 INSERT / 空 key) +``` + +ArchUnit 纪律保持:gateway 在 `com.eip4.platform.flowgateway`,只 `import com.eip4.* / com.dsasp.*`(允许方向), +无反向依赖;`ArchitectureRulesTest`(platform-app)绿。 + +## 二、REST 契约 + +### 2.1 gateway 对外(经 platform-app 暴露,JWT 取 userId/roles) + +| 方法 | 路径 | 说明 | +|------|------|------| +| GET | `/api/todo?firstResult=&maxResults=` | 当前用户待办(assignee=JWT userId,候选组=JWT roles);聚合业务摘要 | +| GET | `/api/done?firstResult=&maxResults=` | 当前用户已办;聚合业务摘要 | +| POST | `/api/task/{id}/complete` | 办理 + 回写;body 可带 `{variables, businessKey, processInstanceId, tableName}` | +| POST | `/api/process/start` | 发起;body `{processDefinitionKey|processDefinitionId, businessKey, variables}` | + +熔断:引擎不可达 → **503** `{"status":503,"error":"FLOW_SERVICE_UNAVAILABLE","message":"工作流引擎服务暂不可达,请稍后重试"}`; +业务错(如挂起拒办 409)→ 透传原状态码 `FLOW_REMOTE_ERROR`。 + +### 2.2 gateway 调 flowable-service(8089;含本任务对 flowable-service 的契约增强) + +| 方法 | 路径 | 备注 | +|------|------|------| +| GET | `/api/flow/tasks/todo?assignee=&candidateGroup=&candidateUser=&firstResult=&maxResults=` | **出参新增 businessKey**(从运行时实例补全) | +| GET | `/api/flow/tasks/done?assignee=&firstResult=&maxResults=` | **出参新增 businessKey**(从历史实例补全) | +| POST | `/api/flow/tasks/{id}/complete` | body `{variables}` | +| POST | `/api/flow/process/start` | | +| GET | `/api/flow/process/{id}` | **新增**:查实例(运行中 ended=false / 已结束历史 ended=true / 不存在 404),供办理后判定流程是否结束 | + +> 契约增强原因(手册 §6.8):Flowable 6.8.1 `TaskInfo` 无 `getBusinessKey()`(javap 核实),task 无从直接带 businessKey; +> 由查询侧从 process instance 反查补全。flowable-service 26 单测仍全绿(改动未破契约)。 + +## 三、验证证据摘要 + +| # | 验证项 | 方法 | 结果 | +|---|--------|------|------| +| 1 | flowable-service 起 8089 | 连本地 eip4flow + 客户库只读,2.4s 启动 | ✅ 定义计数 1509 | +| 2 | platform-app 起 8090 | local profile 连 eip4m0,1.6s 启动 | ✅ /api/todo 200 | +| 3 | **待办聚合数=直查一致** | 真实用户 829cdcca,JWT userId 调 8090 /api/todo vs 8089 直查 count | ✅ 见 3.1,双口径=4 精确相等 | +| 4 | **业务摘要拼接正确** | 本地构造 SYS_DATASTATUS 映射 + 业务表行,验证 businessKey→标题字段 | ✅ 见 3.2,拼到 SYS_USERGROUP + NAME 等标题字段 | +| 5 | **优雅降级共存** | 同一待办列表中无本地映射的 businessKey | ✅ 见 3.2,3 条降级为仅流程字段(businessTable=null)与拼接条目共存 | +| 6 | **熔断 503** | kill 8089 后调 8090 /api/todo | ✅ 见 3.3,HTTP 503 干净 JSON,platform-app 进程存活不崩 | +| 7 | **事件回写** | 本地构造 datastatus=1,经 8090 complete(流程结束)回写 | ✅ 见 3.4,SYS_DATASTATUS 1→3,引擎侧实例确结束 | +| 8 | 全模块 mvn test + ArchUnit | 整反应堆 | ✅ BUILD SUCCESS;gateway 21 单测 + flowable-service 26 + ArchitectureRulesTest 绿 | + +### 3.1 待办聚合数 == flowable-service 直查(真实用户 829cdcca) + +JWT(userId=`829cdcca-4e07-4e12-9c8e-a3da2c105e31`)调 8090 `/api/todo`,与 8089 `/tasks/todo/count` 直查对账: + +| 口径 | 数 | +|------|---:| +| 8089 直查 `/tasks/todo/count?assignee=829cdcca-...` | **4** | +| 8090 聚合 `/api/todo`(JWT userId=829cdcca) | **4** | + +精确相等。首条流程字段完整(taskId/taskName=接收交底(项目部)/assignee/businessKey 全有)。 + +### 3.2 业务摘要拼接正确 + 优雅降级共存 + +本地构造(eip4m0 可写):取真实待办首条 businessKey `e8a37edb-...`, +在 eip4m0 造 `SYS_DATASTATUS(businesskey=e8a37edb, tablename=SYS_USERGROUP, datastatus=2)` + +`SYS_USERGROUP` 业务行(主键=e8a37edb, name=安全技术交底单-端到端摘要验证)。8090 /api/todo 该条: + +``` +businessKey = e8a37edb-15f0-46fb-973d-68888a75b6fb +businessTable = SYS_USERGROUP (经 SYS_DATASTATUS.tablename 映射) +businessSummary= {NAME:"安全技术交底单-端到端摘要验证", DESCRIPTION:"...", GROUPTYPE:1, ORDERASC:1} + (loadPOJO 标题字段;主键 SYS_USERGROUP_ID 与系统列 CREATEBY/CREATETIME 已剔除) +``` + +**同一响应另 3 条** businessKey 无本地映射(其业务表在客户库,本地 eip4m0 无)→ `businessTable=null`、`businessSummary={}` +—— **优雅降级为仅流程字段**,与拼接成功条目在同一列表共存。这同时证明: +聚合层业务摘要数据源 = platform-app 主 JdbcTemplate(本地 eip4m0;生产/默认 profile 即客户库只读),拼不到不拖垮列表。 + +### 3.3 熔断:kill 8089 → /api/todo 503 + +精确 `kill ` 停 8089(platform-app 进程保留),调 8090: + +``` +HTTP 状态码 = 503 +{"error":"FLOW_SERVICE_UNAVAILABLE","message":"工作流引擎服务暂不可达,请稍后重试","status":503} +platform-app 进程存活(引擎宕机不拖垮单体,明确 503 语义而非 500 堆栈) +``` + +`FlowableClient` 连接级失败重试(maxRetries 默认 2,带退避)→ 耗尽抛 `FlowServiceUnavailableException` +→ `@RestControllerAdvice` 映射 503。 + +### 3.4 事件回写:本地 complete → SYS_DATASTATUS 1→3 + +| 阶段 | eip4m0 SYS_DATASTATUS(e8a37edb) | eip4flow 实例 20334081 | +|------|------|------| +| complete 前 | datastatus=**1**(本地构造为未提交,演示状态推进) | 活动任务 1 个(20334106),ended=false | +| 经 8090 `/api/task/20334106/complete`(带 businessKey+processInstanceId) | 响应 `{completed:true, processEnded:true, statusWritten:true}` | — | +| complete 后 | datastatus=**3**(通过/已归档) | 剩余活动任务 0,act_hi_procinst 已结束(2026-06-11 15:08:24) | + +回写算法忠实复刻 `passProcess`:流程结束 ended=true → 目标 STATUS_PASS(3);守卫 `oldstatus(1) < target(3)` 通过 → 回写。 +守卫负向(oldstatus=null 不凭空插 / oldstatus 已达 3 不回退)由 `StatusWritebackTest` 7 单测覆盖。 + +## 四、回写语义结论(侦察老系统后照原语义实现) + +侦察 framework `com.dsasp.server.wf.service.ProcessCoreServiceImpl`(2112 行)+ `WfChangeStatus` + `ChangeStatus` 接口: + +- **DATASTATUS 值语义**(`ProcessCoreService` 常量,即盘点报告所指 DATASTATUS=3「已归档/在批」一类): + `STATUS_NOSUBMIT=1` 未提交 / `STATUS_PROCESSING=2` 处理中(在批/审批中) / `STATUS_PASS=3` 通过(已归档/审批通过) / + `STATUS_NOPASS=4` 未通过 / `STATUS_RESUBMIT=5` 重新提交 / `STATUS_INVALID=6` 作废。 +- **办理(passProcess)回写**(本任务 complete 对齐):complete 后取流程实例 businessKey 与 TABLENAME 变量, + `oldstatus = getStatus(businessKey)`;`isEnd(实例已结束) ? STATUS_PASS(3) : STATUS_PROCESSING(2)`; + **仅当 `oldstatus != null && oldstatus < status`** 才 `UpdateStatus`(单调递增守卫)。 +- **upsert(WfChangeStatus.UpdateStatus)**:先 `UPDATE SYS_DATASTATUS SET DATASTATUS=? WHERE BUSINESSKEY=?`, + 影响 0 行则 `INSERT(BUSINESSKEY, TABLENAME, DATASTATUS)`。本任务参数化占位(原版裸拼,收敛注入面,语义不变)。 +- **businessKey → tablename 映射口径**:`SYS_DATASTATUS` 有 `tablename + businesskey` 列 + (framework `ProcessCoreServiceImpl` 第 2018 行 `select tablename,businesskey from SYS_DATASTATUS where businesskey=...`); + 聚合层据此把流程任务连接到业务摘要(loadPOJO 只读标题字段)。 + +## 五、数据变更登记 + +> 纪律:本地库验证,客户库只读;每次写前记录现状,本地数据可重复构造。 + +| 操作 | 目标库.行 | 写前 | 写后 | 性质 | +|------|--------|------|------|------| +| bootstrap 自举 | eip4m0.SYS_DATASTATUS(表) | 表不存在 | 建表 + 2 测试行(P34-WB-TEST-0001=2 / 0002=3) | 本地自举,可重复执行 | +| 业务摘要构造 | eip4m0.SYS_USERGROUP / SYS_DATASTATUS(e8a37edb) | 无 | 映射 SYS_USERGROUP + 业务行 | 本地构造,演示拼接 | +| **真实 complete** | eip4flow 任务 20334106 / 实例 20334081 | 活动(ended=false) | 已办理,流程结束 | **不可逆**(complete 推进+落历史);eip4flow 为迁移数据副本,非客户生产库 | +| 回写 | eip4m0.SYS_DATASTATUS(e8a37edb) | datastatus=1 | datastatus=3 | 本地可写 | + +- **客户库(192.168.20.68:5435)全程只读**:flowable-service 业务组织库连接 read-only,gateway 业务摘要数据源在本地 eip4m0。 +- 真实 complete 仅在本地 eip4flow 迁移副本上做一条(回写验证核心交付,需真实流程结束以触发 STATUS_PASS 分支); + P3-1/2 报告出于「逐字节还原」洁癖未做真实 complete,P3-4 回写验证需要,故在迁移副本(非客户生产)上执行一条并完整记录。 + +## 六、坑列表(已写入手册 §6.8 / §6.9) + +1. **§6.8 Flowable 6.8.1 Task 接口无 businessKey**:`TaskInfo` 无 `getBusinessKey()`(javap 核实); + 待办聚合 task↔业务数据连接须由 flowable-service 查询侧从 process instance 反查补全 + (`TaskDto` 加 businessKey 字段;新增 `GET /api/flow/process/{id}` 查实例)。 +2. **§6.9 网关 503 熔断 + 回写守卫**:引擎不可达 → 503 语义(非 500 堆栈),连接级重试 + 业务错透传; + 回写守卫 `oldstatus platform-flow-gateway platform-flow-gateway - P3 占位:Flowable REST 客户端、待办聚合、3 个 handler bean + + P3-4 单体侧流程网关:Flowable REST 客户端 + 待办聚合 + 事件回写。 + 引擎在独立 flowable-service(端口 8089),本模块只做 HTTP 客户端(架构第三节)。 + - FlowableClient:RestClient 调 flowable-service(基址 eip4.flow.base-url,默认 http://localhost:8089), + 超时/重试/熔断降级(服务不可达 → FlowServiceUnavailableException → 503 语义,非 500 堆栈)。 + - 待办聚合(经 platform-app 暴露):GET /api/todo、GET /api/done、POST /api/task/{id}/complete、 + POST /api/process/start;聚合层把 Flowable 任务与业务摘要连接(businessKey → SYS_DATASTATUS.tablename + → 引擎 loadPOJO 只读标题字段;业务摘要数据源=客户库只读;拼不到优雅降级为仅流程字段)。 + - 事件回写:complete 后按老系统 ProcessCoreServiceImpl/WfChangeStatus 语义更新 SYS_DATASTATUS + (STATUS_PROCESSING=2/STATUS_PASS=3,守卫 oldstatus < status 单调递增);本地库验证,客户库只读。 + + + com.eip4platform-legacy-core + + com.eip4platform-auth + + + org.springframework.bootspring-boot-starter-web + + org.springframework.bootspring-boot-starter-jdbc + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + + + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessSummaryService.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessSummaryService.java new file mode 100644 index 0000000..d990d51 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/BusinessSummaryService.java @@ -0,0 +1,129 @@ +package com.eip4.platform.flowgateway.aggregate; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.dsasp.server.common.dataDic.bean.GeneralPOJO; +import com.dsasp.server.common.dataDic.service.POJOCRUDService; +import com.dsasp.server.common.util.UserSession; + +/** + * 业务摘要服务:把流程任务的 {@code businessKey} 连接到客户库业务数据。 + * + *

数据源 = 客户库只读:本服务注入应用主 {@code JdbcTemplate}(default profile 连客户库副本) + * 与引擎 {@code POJOCRUDService}(其底座亦是该只读数据源)。映射与读全程只读,绝不写客户库。 + * + *

两步连接(对齐老系统 {@code SYS_DATASTATUS} 口径,见 framework + * {@code ProcessCoreServiceImpl} 第 2018 行 {@code select tablename,businesskey from SYS_DATASTATUS}): + *

    + *
  1. {@code businessKey} → {@code SYS_DATASTATUS.tablename}(该表有 {@code tablename+businesskey} 列)。
  2. + *
  3. {@code loadPOJO(businessKey, tablename, ADMIN, false)} → 业务实体,只取标题类字段 + * (优先引擎计算的 {@code _DISPLAY__};否则剔除系统列/主键/大文本后取业务列,封顶 6 列,只用于摘要展示)。
  4. + *
+ * + *

优雅降级:任一步失败(businessKey 空 / SYS_DATASTATUS 无映射 / 业务表不在当前库 / + * 元数据缺失 / loadPOJO 异常)均不抛出,返回空 {@link Summary} —— 待办列表仍出全部流程字段。 + */ +@Service +public class BusinessSummaryService { + + private static final Logger log = LoggerFactory.getLogger(BusinessSummaryService.class); + + /** 系统/审计列与大字段:摘要展示无意义,剔除(SYSFIELD + 主键由 POJO 元数据给出)。 */ + private static final Set EXCLUDED = Arrays.stream(GeneralPOJO.SYSFIELD) + .collect(Collectors.toCollection(java.util.HashSet::new)); + + static { + EXCLUDED.add("DOCUMENT"); + EXCLUDED.add("WFINITIATORUSERID"); + EXCLUDED.add("WFINITIATORDEPARTID"); + } + + /** 摘要字段封顶:只为标题展示,避免把宽表所有列拖进待办列表。 */ + private static final int MAX_SUMMARY_FIELDS = 6; + + private final JdbcTemplate jdbcTemplate; + private final POJOCRUDService pojoCRUDService; + + public BusinessSummaryService(JdbcTemplate jdbcTemplate, POJOCRUDService pojoCRUDService) { + this.jdbcTemplate = jdbcTemplate; + this.pojoCRUDService = pojoCRUDService; + } + + /** 摘要载体:{@code tableName} 与标题字段 map;拼不到时 {@code tableName=null}、{@code fields} 空。 */ + public record Summary(String tableName, Map fields) { + public static final Summary EMPTY = new Summary(null, Map.of()); + + /** 是否拼到了业务表(false = 全降级,仅流程字段)。 */ + public boolean present() { + return tableName != null; + } + } + + /** + * 按 businessKey 取业务摘要;任何缺失/异常一律降级为 {@link Summary#EMPTY}(不抛)。 + */ + public Summary summarize(String businessKey) { + if (businessKey == null || businessKey.isBlank()) { + return Summary.EMPTY; + } + String tableName = resolveTableName(businessKey); + if (tableName == null) { + return Summary.EMPTY; + } + try { + GeneralPOJO po = pojoCRUDService.loadPOJO(businessKey, tableName, UserSession.getAdmin(), false); + if (po == null) { + return new Summary(tableName, Map.of()); + } + return new Summary(tableName, titleFields(po)); + } catch (RuntimeException e) { + // 业务表不在当前库 / 元数据漂移 / 引擎读异常 —— 降级为仅 tableName,不拖垮待办 + log.debug("业务摘要 loadPOJO 降级(businessKey={}, table={}): {}", businessKey, tableName, e.getMessage()); + return new Summary(tableName, Map.of()); + } + } + + /** businessKey → SYS_DATASTATUS.tablename(只读单值查询;无映射/异常返回 null)。 */ + private String resolveTableName(String businessKey) { + try { + return jdbcTemplate.query( + "SELECT tablename FROM SYS_DATASTATUS WHERE businesskey = ?", + rs -> rs.next() ? rs.getString(1) : null, + businessKey); + } catch (RuntimeException e) { + log.debug("SYS_DATASTATUS 表名映射降级(businessKey={}): {}", businessKey, e.getMessage()); + return null; + } + } + + /** 取标题类字段:优先引擎 _DISPLAY__,否则剔除系统列/主键后取业务列(封顶 MAX_SUMMARY_FIELDS)。 */ + private Map titleFields(GeneralPOJO po) { + Map fields = new LinkedHashMap<>(); + Set keys = Arrays.stream(nullToEmpty(po.get_KeyColumns())) + .collect(Collectors.toCollection(java.util.HashSet::new)); + for (int i = 0; i < po.get_ColumnCount() && fields.size() < MAX_SUMMARY_FIELDS; i++) { + String col = po.get_ColumnName(i); + if (col == null || keys.contains(col) || EXCLUDED.contains(col.toUpperCase())) { + continue; + } + Object val = po.get_Value(i); + if (val != null) { + fields.put(col, val); + } + } + return fields; + } + + private static String[] nullToEmpty(String[] a) { + return a == null ? new String[0] : a; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoAggregator.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoAggregator.java new file mode 100644 index 0000000..09e280e --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoAggregator.java @@ -0,0 +1,67 @@ +package com.eip4.platform.flowgateway.aggregate; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.stereotype.Service; + +import com.eip4.platform.flowgateway.client.FlowTaskDto; +import com.eip4.platform.flowgateway.client.FlowableClient; + +/** + * 待办/已办聚合层:把 {@link FlowableClient} 取回的纯流程任务与客户库业务摘要连接成 {@link TodoItem}。 + * + *

职责(架构第一节:gateway = Flowable REST 客户端 + 待办聚合): + *

    + *
  • 当前用户待办——按 assignee + 候选组(JWT roles)聚合;
  • + *
  • 逐条经 {@link BusinessSummaryService} 拼业务摘要(businessKey → 业务表标题字段);
  • + *
  • 拼不到摘要时优雅降级为仅流程字段(由 BusinessSummaryService 内部兜底)。
  • + *
+ * + *

引擎不可达由 {@link FlowableClient} 抛 {@code FlowServiceUnavailableException}(→ 503), + * 本层不吞;但业务摘要侧缺数据一律降级,不影响流程字段返回。 + */ +@Service +public class TodoAggregator { + + private final FlowableClient flowableClient; + private final BusinessSummaryService businessSummaryService; + + public TodoAggregator(FlowableClient flowableClient, BusinessSummaryService businessSummaryService) { + this.flowableClient = flowableClient; + this.businessSummaryService = businessSummaryService; + } + + /** + * 当前用户待办(含候选组待办)。 + * + * @param userId JWT 取的当前用户 id(assignee 维度) + * @param candidateGroups 候选组(JWT roles 驱动的候选组待办) + */ + public List todo(String userId, List candidateGroups, int firstResult, int maxResults) { + List tasks = flowableClient.todo(userId, candidateGroups, null, firstResult, maxResults); + return aggregate(tasks); + } + + /** 当前用户已办。 */ + public List done(String userId, int firstResult, int maxResults) { + List tasks = flowableClient.done(userId, firstResult, maxResults); + return aggregate(tasks); + } + + /** 逐条拼业务摘要(摘要侧异常已在 BusinessSummaryService 内降级,不在此抛出)。 */ + private List aggregate(List tasks) { + List items = new ArrayList<>(tasks == null ? 0 : tasks.size()); + if (tasks == null) { + return items; + } + for (FlowTaskDto t : tasks) { + TodoItem item = TodoItem.fromTask(t); + BusinessSummaryService.Summary summary = businessSummaryService.summarize(t.businessKey); + item.businessTable = summary.tableName(); + item.businessSummary = summary.fields(); + items.add(item); + } + return items; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoItem.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoItem.java new file mode 100644 index 0000000..97b01cb --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/aggregate/TodoItem.java @@ -0,0 +1,52 @@ +package com.eip4.platform.flowgateway.aggregate; + +import java.util.Map; + +import com.eip4.platform.flowgateway.client.FlowTaskDto; + +/** + * 聚合后的待办/已办条目:Flowable 流程字段 + 业务摘要。 + * + *

聚合层把端口 8089 返回的纯流程任务({@link FlowTaskDto})与业务数据连接: + * 任务 {@code businessKey} → {@code SYS_DATASTATUS.tablename} → 引擎 {@code loadPOJO} 读业务表标题字段。 + * 拼不到业务摘要(businessKey 无映射 / 业务表不在当前库 / 元数据缺失)时,{@code businessSummary} 为空 Map、 + * {@code businessTable} 为 null —— 优雅降级为仅流程字段,绝不让业务侧缺数据拖垮整张待办列表。 + */ +public class TodoItem { + + /** Flowable 任务 id。 */ + public String taskId; + /** 任务名(如「接收交底(项目部)」)。 */ + public String taskName; + public String assignee; + public String owner; + public String processInstanceId; + public String processDefinitionId; + public String taskDefinitionKey; + public Long createTimeMillis; + public Long endTimeMillis; + public boolean suspended; + + /** 业务主键(= 流程 businessKey),用于回写与跳详情。可空(任务无 businessKey)。 */ + public String businessKey; + /** 业务实体表名(经 SYS_DATASTATUS 映射)。拼不到时为 null。 */ + public String businessTable; + /** 业务摘要标题字段(loadPOJO 只读取的标题类字段)。拼不到时为空 Map(降级)。 */ + public Map businessSummary = Map.of(); + + static TodoItem fromTask(FlowTaskDto t) { + TodoItem item = new TodoItem(); + item.taskId = t.id; + item.taskName = t.name; + item.assignee = t.assignee; + item.owner = t.owner; + item.processInstanceId = t.processInstanceId; + item.processDefinitionId = t.processDefinitionId; + item.taskDefinitionKey = t.taskDefinitionKey; + item.createTimeMillis = t.createTimeMillis; + item.endTimeMillis = t.endTimeMillis; + item.suspended = t.suspended; + item.businessKey = t.businessKey; + return item; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayConfig.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayConfig.java new file mode 100644 index 0000000..525db76 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayConfig.java @@ -0,0 +1,39 @@ +package com.eip4.platform.flowgateway.client; + +import java.time.Duration; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.client.ClientHttpRequestFactories; +import org.springframework.boot.web.client.ClientHttpRequestFactorySettings; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.web.client.RestClient; + +/** + * 流程网关客户端装配:把 {@link FlowGatewayProperties} 的基址/超时落到一个专用 {@code RestClient}。 + * + *

用专属 bean 名 {@code flowRestClient},不与应用里可能存在的其他 {@code RestClient} 冲突; + * 超时经 {@link ClientHttpRequestFactorySettings} 落到请求工厂(JDK {@code SimpleClientHttpRequestFactory}), + * 引擎卡死时按 {@code read-timeout} 抛 {@code SocketTimeoutException} → {@code FlowableClient} 走熔断降级。 + */ +@Configuration +@EnableConfigurationProperties(FlowGatewayProperties.class) +public class FlowGatewayConfig { + + @Bean + ClientHttpRequestFactory flowRequestFactory(FlowGatewayProperties props) { + ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS + .withConnectTimeout(Duration.ofMillis(props.getConnectTimeoutMs())) + .withReadTimeout(Duration.ofMillis(props.getReadTimeoutMs())); + return ClientHttpRequestFactories.get(settings); + } + + @Bean + RestClient flowRestClient(FlowGatewayProperties props, ClientHttpRequestFactory flowRequestFactory) { + return RestClient.builder() + .baseUrl(props.getBaseUrl()) + .requestFactory(flowRequestFactory) + .build(); + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayProperties.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayProperties.java new file mode 100644 index 0000000..67ee972 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowGatewayProperties.java @@ -0,0 +1,76 @@ +package com.eip4.platform.flowgateway.client; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * 流程网关客户端配置(前缀 {@code eip4.flow})。 + * + *

网关是单体侧 Flowable 客户端,引擎在独立 {@code flowable-service}(端口 8089,架构第三节)。 + * 这里配置基址、超时、重试次数——服务私有化部署时仅改 {@code base-url} 即可指向客户现场的引擎进程。 + * + *

    + *
  • {@code base-url} —— flowable-service 基址,默认 {@code http://localhost:8089}
  • + *
  • {@code connect-timeout-ms} —— 建连超时(ms),默认 2000
  • + *
  • {@code read-timeout-ms} —— 读超时(ms),默认 5000
  • + *
  • {@code max-retries} —— 瞬时故障重试次数(仅连接级失败重试,非业务错),默认 2
  • + *
  • {@code retry-backoff-ms} —— 重试间隔(ms),默认 200
  • + *
+ */ +@ConfigurationProperties(prefix = "eip4.flow") +public class FlowGatewayProperties { + + /** flowable-service 基址(引擎独立进程,默认本地 8089)。 */ + private String baseUrl = "http://localhost:8089"; + + /** 建连超时(ms)。引擎不可达时快速失败,以走熔断降级而非线程挂死。 */ + private int connectTimeoutMs = 2000; + + /** 读超时(ms)。 */ + private int readTimeoutMs = 5000; + + /** 瞬时故障重试次数(连接级,不含业务 4xx/5xx 语义错)。 */ + private int maxRetries = 2; + + /** 重试间隔(ms)。 */ + private long retryBackoffMs = 200; + + public String getBaseUrl() { + return baseUrl; + } + + public void setBaseUrl(String baseUrl) { + this.baseUrl = baseUrl; + } + + public int getConnectTimeoutMs() { + return connectTimeoutMs; + } + + public void setConnectTimeoutMs(int connectTimeoutMs) { + this.connectTimeoutMs = connectTimeoutMs; + } + + public int getReadTimeoutMs() { + return readTimeoutMs; + } + + public void setReadTimeoutMs(int readTimeoutMs) { + this.readTimeoutMs = readTimeoutMs; + } + + public int getMaxRetries() { + return maxRetries; + } + + public void setMaxRetries(int maxRetries) { + this.maxRetries = maxRetries; + } + + public long getRetryBackoffMs() { + return retryBackoffMs; + } + + public void setRetryBackoffMs(long retryBackoffMs) { + this.retryBackoffMs = retryBackoffMs; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowRemoteException.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowRemoteException.java new file mode 100644 index 0000000..5b09778 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowRemoteException.java @@ -0,0 +1,24 @@ +package com.eip4.platform.flowgateway.client; + +import org.springframework.http.HttpStatusCode; + +/** + * flowable-service 返回业务级错误状态(4xx/5xx,如挂起任务 complete 被引擎拒为 409)时抛出。 + * + *

与 {@link FlowServiceUnavailableException} 区分:那个是"引擎进程不可达"(→ 503); + * 这个是"引擎在线但拒绝了这次操作"(原状态码透传给调用方,保留 Flowable 语义, + * 如挂起拒办 409、参数错 400)。 + */ +public class FlowRemoteException extends RuntimeException { + + private final HttpStatusCode status; + + public FlowRemoteException(HttpStatusCode status, String message) { + super(message); + this.status = status; + } + + public HttpStatusCode getStatus() { + return status; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowServiceUnavailableException.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowServiceUnavailableException.java new file mode 100644 index 0000000..21b1e81 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowServiceUnavailableException.java @@ -0,0 +1,16 @@ +package com.eip4.platform.flowgateway.client; + +/** + * flowable-service(引擎独立进程,8089)不可达时抛出——熔断降级语义载体。 + * + *

由 {@code @ControllerAdvice}(见 {@code web/FlowGatewayExceptionHandler})映射为 HTTP 503 + * (Service Unavailable),让待办聚合在引擎宕机/网络分区时返回明确的 503 语义而非 500 堆栈 + * (任务要求:服务不可达 → 503,非裸栈)。仅连接级/超时/重试耗尽时抛此异常,业务级 4xx/5xx + * 由 {@link FlowRemoteException} 承载,语义不混淆。 + */ +public class FlowServiceUnavailableException extends RuntimeException { + + public FlowServiceUnavailableException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowTaskDto.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowTaskDto.java new file mode 100644 index 0000000..b0ac48a --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowTaskDto.java @@ -0,0 +1,23 @@ +package com.eip4.platform.flowgateway.client; + +/** + * flowable-service 返回的任务 DTO(出参契约,贴 {@code flowable-service} 的 {@code TaskDto})。 + * + *

字段与端口 8089 的 {@code GET /api/flow/tasks/todo}、{@code /tasks/done} 出参一一对应 + * (见 {@code flowable-service/P3流程服务实测报告.md} REST 契约)。聚合层在此基础上拼接业务摘要。 + */ +public class FlowTaskDto { + + public String id; + public String name; + public String assignee; + public String owner; + public String processInstanceId; + public String processDefinitionId; + public String taskDefinitionKey; + /** 流程业务主键(由 flowable-service 查询侧从实例补全);聚合层据此连接业务摘要。 */ + public String businessKey; + public Long createTimeMillis; + public Long endTimeMillis; + public boolean suspended; +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowableClient.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowableClient.java new file mode 100644 index 0000000..de0c6ab --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/FlowableClient.java @@ -0,0 +1,191 @@ +package com.eip4.platform.flowgateway.client; + +import java.io.IOException; +import java.net.ConnectException; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Component; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClient; +import org.springframework.web.client.RestClientResponseException; +import org.springframework.web.util.UriBuilder; + +/** + * Flowable REST 客户端:单体侧调独立 {@code flowable-service}(端口 8089,架构第三节)。 + * + *

三道工程纪律: + *

    + *
  1. 超时:连接/读超时由 {@link FlowGatewayProperties} 配置,经 {@code RestClient} 的 + * 请求工厂落地(见 {@code FlowGatewayConfig});引擎卡死时快速失败而非线程挂死。
  2. + *
  3. 重试:仅连接级瞬时故障(连不上/IO 抖动)重试 {@code maxRetries} 次,带退避; + * 业务级 4xx/5xx 绝不重试(语义错重试无意义且可能重复副作用,如 complete)。
  4. + *
  5. 熔断降级:重试耗尽仍连不上 → 抛 {@link FlowServiceUnavailableException} + * (→ HTTP 503);引擎在线但拒绝(4xx/5xx)→ 抛 {@link FlowRemoteException}(透传原状态码)。
  6. + *
+ * + *

REST 契约逐条对齐 {@code flowable-service/P3流程服务实测报告.md}: + * 待办 {@code GET /api/flow/tasks/todo?assignee=&candidateGroup=&candidateUser=}、 + * 已办 {@code GET /api/flow/tasks/done?assignee=}、 + * 办理 {@code POST /api/flow/tasks/{id}/complete}、 + * 发起 {@code POST /api/flow/process/start}。 + */ +@Component +public class FlowableClient { + + private static final Logger log = LoggerFactory.getLogger(FlowableClient.class); + + private static final ParameterizedTypeReference> TASK_LIST = + new ParameterizedTypeReference<>() { + }; + + private final RestClient restClient; + private final FlowGatewayProperties props; + + public FlowableClient(RestClient flowRestClient, FlowGatewayProperties props) { + this.restClient = flowRestClient; + this.props = props; + } + + /** + * 当前用户待办(按 assignee + 候选组/候选用户;空集合表示不按该维度过滤)。 + * + *

对应引擎 {@code TaskQuery.active().taskAssignee()/taskCandidateGroup()/taskCandidateUser()}。 + * 三维任一为空则不下发该 query 参数(由 flowable-service 侧 {@code isBlank} 跳过)。 + */ + public List todo(String assignee, List candidateGroups, String candidateUser, + int firstResult, int maxResults) { + return get("待办", uri -> { + uri.path("/api/flow/tasks/todo"); + if (notBlank(assignee)) { + uri.queryParam("assignee", assignee); + } + if (candidateGroups != null) { + for (String g : candidateGroups) { + if (notBlank(g)) { + uri.queryParam("candidateGroup", g); + } + } + } + if (notBlank(candidateUser)) { + uri.queryParam("candidateUser", candidateUser); + } + uri.queryParam("firstResult", firstResult); + uri.queryParam("maxResults", maxResults); + return uri.build(); + }); + } + + /** 当前用户已办(历史已完成任务,按 assignee)。 */ + public List done(String assignee, int firstResult, int maxResults) { + return get("已办", uri -> uri.path("/api/flow/tasks/done") + .queryParam("assignee", assignee == null ? "" : assignee) + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .build()); + } + + /** + * 办理(complete)任务。挂起实例的任务会被引擎拒为 409 → {@link FlowRemoteException}(透传)。 + * + * @param variables 提交变量,可为 null + */ + public void complete(String taskId, Map variables) { + post("办理", "/api/flow/tasks/" + taskId + "/complete", + variables == null ? Map.of() : Map.of("variables", variables), Void.class); + } + + /** 发起流程(processDefinitionKey 或 processDefinitionId 二选一,可带 businessKey 与变量)。 */ + public ProcessInstanceDto start(Map startRequest) { + return post("发起", "/api/flow/process/start", startRequest, ProcessInstanceDto.class); + } + + /** + * 查流程实例(供办理后判定是否结束以回写业务状态)。 + * 实例不存在(404)返回 null;运行中 {@code ended=false},已结束 {@code ended=true}。 + */ + public ProcessInstanceDto processInstance(String processInstanceId) { + return execute("查实例", () -> restClient.get() + .uri("/api/flow/process/{id}", processInstanceId) + .retrieve() + .onStatus(status -> status.value() == 404, (req, resp) -> { + /* 实例不存在 → 返回 null,不当作业务错抛 */ + }) + .body(ProcessInstanceDto.class)); + } + + // ---------------------------------------------------------------- 内部:重试 + 异常分类 + + private List get(String op, java.util.function.Function uriFn) { + return execute(op, () -> restClient.get() + .uri(uriFn::apply) + .retrieve() + .body(TASK_LIST)); + } + + private T post(String op, String path, Object body, Class respType) { + return execute(op, () -> restClient.post() + .uri(path) + .body(body == null ? Map.of() : body) + .retrieve() + .body(respType)); + } + + /** + * 统一执行:连接级故障带退避重试 maxRetries 次,耗尽 → 503 语义;业务错(4xx/5xx)立即透传不重试。 + */ + private T execute(String op, java.util.function.Supplier call) { + int attempts = props.getMaxRetries() + 1; + ResourceAccessException lastConnError = null; + for (int i = 1; i <= attempts; i++) { + try { + return call.get(); + } catch (ResourceAccessException e) { + // 连接级:连不上/读超时/IO 抖动 —— 瞬时故障,可重试 + if (!isConnectivityFailure(e)) { + throw e; + } + lastConnError = e; + log.warn("flowable-service {}调用连接失败(第 {}/{} 次): {}", op, i, attempts, e.getMessage()); + if (i < attempts) { + sleepBackoff(); + } + } catch (RestClientResponseException e) { + // 业务级:引擎在线但返回 4xx/5xx(如挂起拒办 409)——透传原状态码,绝不重试 + HttpStatusCode status = e.getStatusCode(); + log.debug("flowable-service {}调用返回业务状态 {}: {}", op, status, e.getMessage()); + throw new FlowRemoteException(status, "flowable-service " + op + "返回 " + status.value()); + } + } + // 重试耗尽仍连不上 —— 熔断降级为 503 语义 + throw new FlowServiceUnavailableException( + "flowable-service 不可达(已重试 " + props.getMaxRetries() + " 次):" + props.getBaseUrl(), + lastConnError); + } + + /** 连接级失败判定:连接拒绝/无法解析/读超时等(可重试),区别于已收到 HTTP 响应的业务错。 */ + static boolean isConnectivityFailure(ResourceAccessException e) { + Throwable cause = e.getCause(); + return cause instanceof ConnectException + || cause instanceof java.net.SocketTimeoutException + || cause instanceof java.net.UnknownHostException + || cause instanceof java.net.NoRouteToHostException + || cause instanceof IOException; // SocketException/连接重置等 IO 类 + } + + private void sleepBackoff() { + try { + Thread.sleep(props.getRetryBackoffMs()); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + } + + private static boolean notBlank(String s) { + return s != null && !s.isBlank(); + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/ProcessInstanceDto.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/ProcessInstanceDto.java new file mode 100644 index 0000000..67eda94 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/client/ProcessInstanceDto.java @@ -0,0 +1,16 @@ +package com.eip4.platform.flowgateway.client; + +/** + * flowable-service 发起流程返回的实例 DTO(贴 {@code flowable-service} 的 {@code ProcessInstanceDto})。 + * + *

对应端口 8089 的 {@code POST /api/flow/process/start} 出参。 + */ +public class ProcessInstanceDto { + + public String id; + public String processDefinitionId; + public String processDefinitionKey; + public String businessKey; + public boolean ended; + public boolean suspended; +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/FlowGatewayExceptionHandler.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/FlowGatewayExceptionHandler.java new file mode 100644 index 0000000..521b88d --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/FlowGatewayExceptionHandler.java @@ -0,0 +1,43 @@ +package com.eip4.platform.flowgateway.web; + +import java.util.Map; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import com.eip4.platform.flowgateway.client.FlowRemoteException; +import com.eip4.platform.flowgateway.client.FlowServiceUnavailableException; + +/** + * 流程网关异常 → 干净 HTTP 语义(只管本网关 client 抛出的两类异常,不拦其他)。 + * + *

    + *
  • {@link FlowServiceUnavailableException}(引擎进程不可达,重试耗尽)→ 503 + * Service Unavailable —— 待办聚合在引擎宕机/网络分区时返回明确的服务不可用语义,而非 500 堆栈。
  • + *
  • {@link FlowRemoteException}(引擎在线但拒绝,如挂起拒办 409)→ 透传原状态码, + * 保留 Flowable 语义。
  • + *
+ */ +@RestControllerAdvice(basePackages = "com.eip4.platform.flowgateway") +public class FlowGatewayExceptionHandler { + + @ExceptionHandler(FlowServiceUnavailableException.class) + public ResponseEntity> onUnavailable(FlowServiceUnavailableException e) { + return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE) + .body(Map.of( + "status", 503, + "error", "FLOW_SERVICE_UNAVAILABLE", + "message", "工作流引擎服务暂不可达,请稍后重试")); + } + + @ExceptionHandler(FlowRemoteException.class) + public ResponseEntity> onRemote(FlowRemoteException e) { + return ResponseEntity.status(e.getStatus()) + .body(Map.of( + "status", e.getStatus().value(), + "error", "FLOW_REMOTE_ERROR", + "message", e.getMessage())); + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java new file mode 100644 index 0000000..3c78815 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/GatewayRequests.java @@ -0,0 +1,33 @@ +package com.eip4.platform.flowgateway.web; + +import java.util.Map; + +/** + * 待办网关 REST 入参 DTO(办理/发起)。 + */ +public final class GatewayRequests { + + private GatewayRequests() { + } + + /** + * 办理(complete)请求。 + * + *

{@code variables} 透传给引擎;{@code businessKey}/{@code processInstanceId}/{@code tableName} + * 用于办理后按老系统语义回写 SYS_DATASTATUS(三者齐备才回写,缺则只办理不回写)。 + */ + public static class CompleteRequest { + public Map variables; + public String businessKey; + public String processInstanceId; + public String tableName; + } + + /** 发起流程请求(透传 flowable-service /process/start 契约)。 */ + public static class StartRequest { + public String processDefinitionKey; + public String processDefinitionId; + public String businessKey; + public Map variables; + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java new file mode 100644 index 0000000..70098c6 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/web/TodoController.java @@ -0,0 +1,119 @@ +package com.eip4.platform.flowgateway.web; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.eip4.platform.auth.security.AuthPrincipal; +import com.eip4.platform.flowgateway.aggregate.TodoAggregator; +import com.eip4.platform.flowgateway.aggregate.TodoItem; +import com.eip4.platform.flowgateway.client.FlowableClient; +import com.eip4.platform.flowgateway.client.ProcessInstanceDto; +import com.eip4.platform.flowgateway.writeback.StatusWriteback; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; + +/** + * 流程网关待办聚合门面(单体侧,经 platform-app 暴露)。 + * + *

引擎在独立 {@code flowable-service}(8089);本门面经 {@link FlowableClient} 调引擎,聚合业务摘要, + * 并在办理后按老系统语义回写业务状态。当前用户身份从 JWT 上下文({@link AuthPrincipal})取 + * {@code userId}(assignee 维度)与 {@code roles}(候选组待办)。 + * + *

    + *
  • {@code GET /api/todo} —— 当前用户待办(含候选组待办)
  • + *
  • {@code GET /api/done} —— 当前用户已办
  • + *
  • {@code POST /api/task/{id}/complete} —— 办理 + 按语义回写 SYS_DATASTATUS
  • + *
  • {@code POST /api/process/start} —— 发起流程
  • + *
+ * + *

引擎不可达时,聚合层经 {@code FlowServiceUnavailableException} → HTTP 503(见 + * {@link FlowGatewayExceptionHandler}),返回明确的服务不可用语义而非 500 堆栈。 + */ +@Tag(name = "流程待办网关", description = "P3-4 单体侧待办聚合:Flowable REST 客户端 + 业务摘要拼接 + 事件回写") +@RestController +public class TodoController { + + private final TodoAggregator todoAggregator; + private final FlowableClient flowableClient; + private final StatusWriteback statusWriteback; + + public TodoController(TodoAggregator todoAggregator, FlowableClient flowableClient, + StatusWriteback statusWriteback) { + this.todoAggregator = todoAggregator; + this.flowableClient = flowableClient; + this.statusWriteback = statusWriteback; + } + + @Operation(summary = "当前用户待办(含候选组待办)", + description = "assignee=JWT userId;候选组=JWT roles。聚合 Flowable 待办与业务摘要(businessKey→业务表标题字段);摘要拼不到时优雅降级为仅流程字段") + @GetMapping("/api/todo") + public List todo(@AuthenticationPrincipal AuthPrincipal principal, + @RequestParam(defaultValue = "0") int firstResult, + @RequestParam(defaultValue = "50") int maxResults) { + String userId = principal == null ? null : principal.userId(); + List candidateGroups = principal == null ? List.of() : principal.roles(); + return todoAggregator.todo(userId, candidateGroups, firstResult, maxResults); + } + + @Operation(summary = "当前用户已办", description = "assignee=JWT userId 的历史已完成任务,拼业务摘要") + @GetMapping("/api/done") + public List done(@AuthenticationPrincipal AuthPrincipal principal, + @RequestParam(defaultValue = "0") int firstResult, + @RequestParam(defaultValue = "50") int maxResults) { + String userId = principal == null ? null : principal.userId(); + return todoAggregator.done(userId, firstResult, maxResults); + } + + @Operation(summary = "办理任务 + 回写业务状态", + description = "complete 后,若请求带 businessKey/processInstanceId,按老系统 ProcessCoreServiceImpl 语义回写 SYS_DATASTATUS(结束→3 通过,未结束→2 处理中,守卫单调递增)。挂起任务被引擎拒为 409(透传)") + @PostMapping("/api/task/{id}/complete") + public ResponseEntity> complete(@PathVariable String id, + @RequestBody(required = false) GatewayRequests.CompleteRequest req) { + flowableClient.complete(id, req == null ? null : req.variables); + + Map resp = new HashMap<>(); + resp.put("completed", true); + // 事件回写(可选):带 businessKey + processInstanceId 时,查实例是否结束后按语义回写 + if (req != null && notBlank(req.businessKey) && notBlank(req.processInstanceId)) { + boolean ended = isProcessEnded(req.processInstanceId); + boolean written = statusWriteback.afterComplete(req.businessKey, req.tableName, ended); + resp.put("statusWritten", written); + resp.put("processEnded", ended); + } else { + resp.put("statusWritten", false); + } + return ResponseEntity.ok(resp); + } + + @Operation(summary = "发起流程", description = "透传 flowable-service /process/start;按 processDefinitionKey 或 id 发起,可带 businessKey 与变量") + @PostMapping("/api/process/start") + public ResponseEntity start(@RequestBody GatewayRequests.StartRequest req) { + Map body = new HashMap<>(); + body.put("processDefinitionKey", req.processDefinitionKey); + body.put("processDefinitionId", req.processDefinitionId); + body.put("businessKey", req.businessKey); + body.put("variables", req.variables); + return ResponseEntity.ok(flowableClient.start(body)); + } + + /** 实例不存在(已被清理)按"已结束"处理(complete 后无运行实例即流程终结)。 */ + private boolean isProcessEnded(String processInstanceId) { + ProcessInstanceDto pi = flowableClient.processInstance(processInstanceId); + return pi == null || pi.ended; + } + + private static boolean notBlank(String s) { + return s != null && !s.isBlank(); + } +} diff --git a/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/writeback/StatusWriteback.java b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/writeback/StatusWriteback.java new file mode 100644 index 0000000..b72ec28 --- /dev/null +++ b/platform-flow-gateway/src/main/java/com/eip4/platform/flowgateway/writeback/StatusWriteback.java @@ -0,0 +1,90 @@ +package com.eip4.platform.flowgateway.writeback; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import com.dsasp.server.common.workflow.service.ProcessCoreService; + +/** + * 事件回写:办理(complete)后按老系统语义更新 {@code SYS_DATASTATUS}。 + * + *

语义来源(逐条对齐 framework,侦察后照原口径实现): + *

    + *
  • {@code WfChangeStatus.UpdateStatus}(framework com.dsasp.server.wf.service.WfChangeStatus): + * 先 {@code UPDATE SYS_DATASTATUS SET DATASTATUS=? WHERE BUSINESSKEY=?};影响 0 行则 + * {@code INSERT(BUSINESSKEY, TABLENAME, DATASTATUS)} —— upsert 语义,本类 {@link #updateStatus} 原样复刻。
  • + *
  • {@code WfChangeStatus.getStatus}:{@code SELECT DATASTATUS FROM SYS_DATASTATUS WHERE BUSINESSKEY=?}, + * 无行返回 null —— {@link #getStatus} 复刻。
  • + *
  • {@code ProcessCoreServiceImpl.passProcess}(办理通过)的回写算法:complete 后 + * {@code status = 流程已结束 ? STATUS_PASS(3) : STATUS_PROCESSING(2)};且仅当 + * {@code oldstatus != null && oldstatus < status} 才回写(状态单调递增,不回退、不在无记录时凭空插入) + * —— {@link #afterComplete} 复刻该守卫。
  • + *
+ * + *

DATASTATUS 值语义(framework {@code ProcessCoreService} 常量,即盘点报告所指): + * 1=未提交、2=处理中(在批/审批中)、3=通过(已归档/审批通过)、4=未通过、5=重新提交、6=作废。 + * + *

纪律:本地库验证,客户库只读——本服务注入应用主 {@code JdbcTemplate};回写仅在 + * 连本地 eip4m0(可写)时执行,生产/客户库形态由部署侧最小权限账户与 read-only 连接约束。 + */ +@Service +public class StatusWriteback { + + private static final Logger log = LoggerFactory.getLogger(StatusWriteback.class); + + private final JdbcTemplate jdbcTemplate; + + public StatusWriteback(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + /** + * 办理后回写(对齐 {@code ProcessCoreServiceImpl.passProcess} 的状态推进语义)。 + * + * @param businessKey 业务主键(= 流程 businessKey) + * @param tableName 业务实体表名(经 SYS_DATASTATUS 映射或待办项携带) + * @param processEnded 办理后流程是否已结束(结束→通过 3,未结束→处理中 2) + * @return 实际是否发生回写(守卫未通过则 false) + */ + public boolean afterComplete(String businessKey, String tableName, boolean processEnded) { + if (businessKey == null || businessKey.isBlank()) { + return false; + } + int target = processEnded ? ProcessCoreService.STATUS_PASS : ProcessCoreService.STATUS_PROCESSING; + Integer oldStatus = getStatus(businessKey); + // passProcess 守卫:oldstatus 必须存在且小于目标(单调递增);无记录或已达更高态则不动 + if (oldStatus != null && oldStatus < target) { + updateStatus(businessKey, tableName, target); + log.debug("回写 SYS_DATASTATUS: businessKey={} {} → {}(processEnded={})", + businessKey, oldStatus, target, processEnded); + return true; + } + log.debug("回写守卫未通过(不更新): businessKey={} old={} target={}", businessKey, oldStatus, target); + return false; + } + + /** + * upsert 业务状态(逐字节对齐 {@code WfChangeStatus.UpdateStatus}:先 UPDATE,0 行则 INSERT)。 + * 参数化占位(原版裸拼,这里收敛注入面,语义不变)。 + */ + public void updateStatus(String businessKey, String tableName, int status) { + int count = jdbcTemplate.update( + "UPDATE SYS_DATASTATUS SET DATASTATUS = ? WHERE BUSINESSKEY = ?", + status, businessKey); + if (count == 0) { + jdbcTemplate.update( + "INSERT INTO SYS_DATASTATUS(BUSINESSKEY, TABLENAME, DATASTATUS) VALUES (?, ?, ?)", + businessKey, tableName, status); + } + } + + /** 取当前业务状态(对齐 {@code WfChangeStatus.getStatus};无行返回 null)。 */ + public Integer getStatus(String businessKey) { + return jdbcTemplate.query( + "SELECT DATASTATUS FROM SYS_DATASTATUS WHERE BUSINESSKEY = ?", + rs -> rs.next() ? rs.getInt(1) : null, + businessKey); + } +} diff --git a/platform-flow-gateway/src/main/resources/bootstrap/bootstrap-datastatus.sql b/platform-flow-gateway/src/main/resources/bootstrap/bootstrap-datastatus.sql new file mode 100644 index 0000000..dc103f0 --- /dev/null +++ b/platform-flow-gateway/src/main/resources/bootstrap/bootstrap-datastatus.sql @@ -0,0 +1,46 @@ +-- ============================================================================ +-- eip4-platform P3-4 流程网关 本地回写验证自举 —— bootstrap-datastatus.sql +-- ---------------------------------------------------------------------------- +-- 用途:在本地 eip4m0 库上补建 SYS_DATASTATUS 平台表(业务流程状态),供 P3-4 网关 +-- 事件回写(complete 后按老系统 ProcessCoreServiceImpl/WfChangeStatus 语义更新 +-- DATASTATUS)的本地最小场景验证。本地库可写,客户库只读(纪律)。 +-- +-- 口径权威来源(已逐一核对源码与盘点): +-- * 列 = framework WfChangeStatus 的 SQL 实际用列(逐字节核对 com.dsasp.server.wf.service.WfChangeStatus): +-- BUSINESSKEY / TABLENAME / DATASTATUS,三列即回写/读取全部用列。 +-- * DATASTATUS 值语义 = ProcessCoreService 常量(com.dsasp.server.common.workflow.service.ProcessCoreService): +-- 1=未提交 STATUS_NOSUBMIT / 2=处理中 STATUS_PROCESSING(在批/审批中) / +-- 3=通过 STATUS_PASS(已归档/审批通过,即盘点报告所指 DATASTATUS=3「已归档/在批」) / +-- 4=未通过 / 5=重新提交 / 6=作废。 +-- * 无主键:迁移手册 §7.2 已登记 SYS_DATASTATUS 客户库物理表"元数据声明为普通表但物理表无主键列" +-- (已知漂移);本地自举对齐该口径——不建主键,businesskey 上建普通索引即可(回写按 businesskey 等值)。 +-- +-- 纪律:可重复执行(IF EXISTS / ON CONFLICT 兜底);表名/列名一律小写。 +-- 加载:psql -h localhost -p 5433 -U zhengwr -d eip4m0 -f bootstrap-datastatus.sql +-- ============================================================================ + +-- --------------------------------------------------------------------------- +-- 1. 物理表 SYS_DATASTATUS(三列,无主键,对齐客户库已知漂移口径 §7.2) +-- --------------------------------------------------------------------------- +CREATE TABLE IF NOT EXISTS sys_datastatus ( + businesskey character varying(200), + tablename character varying(200), + datastatus integer +); + +-- businesskey 等值查询(getStatus / UpdateStatus 均按 businesskey 过滤) +CREATE INDEX IF NOT EXISTS idx_sys_datastatus_bk ON sys_datastatus (businesskey); + +-- --------------------------------------------------------------------------- +-- 2. 测试实体行:模拟一条"处理中(2)"的在批业务记录,供 complete 回写断言。 +-- businesskey 与 tablename 自造(不与真实数据冲突);回写后期望 datastatus 2 → 3。 +-- 可重复执行:先删同 key 再插。 +-- --------------------------------------------------------------------------- +DELETE FROM sys_datastatus WHERE businesskey = 'P34-WB-TEST-0001'; +INSERT INTO sys_datastatus (businesskey, tablename, datastatus) +VALUES ('P34-WB-TEST-0001', 'ORDER_ENTITY', 2); + +-- 另一条:已达通过(3)的记录,用于验证守卫 oldstatus client.todo("U1", List.of(), null, 0, 50)) + .isInstanceOf(FlowServiceUnavailableException.class) + .hasMessageContaining("不可达"); + } + + // ---- 业务错:MockRestServiceServer 返回 409,验证透传 FlowRemoteException 且不重试 ---- + + @Test + void 挂起拒办409_透传FlowRemoteException且不重试() { + FlowGatewayProperties p = props(); + RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl()); + MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build(); + server.expect(ExpectedCount.once(), // 关键:只期望一次调用 → 业务错不重试 + requestTo(("http://localhost:8089/api/flow/tasks/T1/complete"))) + .andRespond(withStatus(HttpStatus.CONFLICT).body("Cannot complete a suspended task")); + FlowableClient client = new FlowableClient(builder.build(), p); + + assertThatThrownBy(() -> client.complete("T1", Map.of())) + .isInstanceOf(FlowRemoteException.class) + .satisfies(e -> assertThat(((FlowRemoteException) e).getStatus().value()).isEqualTo(409)); + server.verify(); + } + + @Test + void 待办正常返回_解析为DTO列表() { + FlowGatewayProperties p = props(); + RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl()); + MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build(); + String body = "[{\"id\":\"T1\",\"name\":\"接收交底(项目部)\",\"assignee\":\"U1\"," + + "\"businessKey\":\"BK-1\",\"processInstanceId\":\"P1\",\"suspended\":false}]"; + server.expect(requestTo(("http://localhost:8089/api/flow/tasks/todo?assignee=U1&firstResult=0&maxResults=50"))) + .andRespond(withSuccess(body, MediaType.APPLICATION_JSON)); + FlowableClient client = new FlowableClient(builder.build(), p); + + List tasks = client.todo("U1", List.of(), null, 0, 50); + + assertThat(tasks).hasSize(1); + assertThat(tasks.get(0).id).isEqualTo("T1"); + assertThat(tasks.get(0).businessKey).isEqualTo("BK-1"); + server.verify(); + } + + @Test + void 候选组多值_逐个下发candidateGroup参数() { + FlowGatewayProperties p = props(); + RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl()); + MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build(); + server.expect(requestTo( + "http://localhost:8089/api/flow/tasks/todo?assignee=U1&candidateGroup=R1&candidateGroup=R2&firstResult=0&maxResults=50")) + .andRespond(withSuccess("[]", MediaType.APPLICATION_JSON)); + FlowableClient client = new FlowableClient(builder.build(), p); + + List tasks = client.todo("U1", List.of("R1", "R2"), null, 0, 50); + + assertThat(tasks).isEmpty(); + server.verify(); + } + + @Test + void 查实例404_返回null而非抛异常() { + FlowGatewayProperties p = props(); + RestClient.Builder builder = RestClient.builder().baseUrl(p.getBaseUrl()); + MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build(); + server.expect(requestTo(("http://localhost:8089/api/flow/process/P-MISSING"))) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + FlowableClient client = new FlowableClient(builder.build(), p); + + assertThat(client.processInstance("P-MISSING")).isNull(); + server.verify(); + } +} diff --git a/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/StatusWritebackTest.java b/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/StatusWritebackTest.java new file mode 100644 index 0000000..6400d20 --- /dev/null +++ b/platform-flow-gateway/src/test/java/com/eip4/platform/flowgateway/StatusWritebackTest.java @@ -0,0 +1,118 @@ +package com.eip4.platform.flowgateway; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.ResultSetExtractor; + +import com.dsasp.server.common.workflow.service.ProcessCoreService; +import com.eip4.platform.flowgateway.writeback.StatusWriteback; + +/** + * 事件回写语义单测(对齐 framework {@code WfChangeStatus} + {@code ProcessCoreServiceImpl.passProcess})。 + * + *

覆盖:守卫(oldstatus items = aggregator.todo("U1", List.of("ROLE_A"), 0, 50); + + assertThat(items).hasSize(1); + TodoItem it = items.get(0); + assertThat(it.taskId).isEqualTo("T1"); + assertThat(it.taskName).isEqualTo("接收交底(项目部)"); + assertThat(it.businessKey).isEqualTo("BK-1"); + assertThat(it.businessTable).isEqualTo("ORDER_ENTITY"); + assertThat(it.businessSummary).containsEntry("TITLE", "某交底单"); + } + + @Test + void 待办摘要拼不到_优雅降级为仅流程字段() { + when(flowableClient.todo(eq("U1"), any(), isNull(), anyInt(), anyInt())) + .thenReturn(List.of(task("T2", "BK-MISSING"))); + when(businessSummaryService.summarize("BK-MISSING")) + .thenReturn(BusinessSummaryService.Summary.EMPTY); + + List items = aggregator.todo("U1", List.of(), 0, 50); + + assertThat(items).hasSize(1); + TodoItem it = items.get(0); + // 流程字段在,业务摘要降级为空 + assertThat(it.taskId).isEqualTo("T2"); + assertThat(it.businessTable).isNull(); + assertThat(it.businessSummary).isEmpty(); + } + + @Test + void 已办聚合走done并拼摘要() { + FlowTaskDto done = task("T3", "BK-3"); + done.endTimeMillis = 123L; + when(flowableClient.done(eq("U1"), anyInt(), anyInt())).thenReturn(List.of(done)); + when(businessSummaryService.summarize("BK-3")) + .thenReturn(new BusinessSummaryService.Summary("ORDER_ENTITY", Map.of("NO", "X"))); + + List items = aggregator.done("U1", 0, 50); + + assertThat(items).hasSize(1); + assertThat(items.get(0).endTimeMillis).isEqualTo(123L); + assertThat(items.get(0).businessTable).isEqualTo("ORDER_ENTITY"); + } + + @Test + void 空待办列表返回空聚合() { + when(flowableClient.todo(any(), any(), isNull(), anyInt(), anyInt())).thenReturn(List.of()); + assertThat(aggregator.todo("U1", List.of(), 0, 50)).isEmpty(); + } +}