P3-4: platform-flow-gateway 单体侧流程网关(Flowable REST 客户端 + 待办聚合 + 事件回写)

- 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<status 单调递增;
  upsert UPDATE 命中或 0 行 INSERT);本地库验证,客户库只读。
- flowable-service 契约增强:Flowable 6.8.1 TaskInfo 无 getBusinessKey(),todo/done 出参由查询侧
  从实例补全 businessKey;新增 GET /api/flow/process/{id} 查实例(供办理后判定流程是否结束)。

验证(8089 连本地 eip4flow+客户库只读,8090 连本地 eip4m0,8084 未动):
- 待办聚合数=直查一致:真实用户 829cdcca /api/todo=4 == 8089 直查 count=4。
- 业务摘要拼接正确 + 优雅降级共存:命中条目拼到 SYS_USERGROUP 标题字段,同列表 3 条无映射降级为仅流程字段。
- 熔断:kill 8089 后 /api/todo 返回 503 干净 JSON,platform-app 进程存活不崩。
- 事件回写:本地构造 datastatus=1,经 8090 complete(流程结束)回写为 3;引擎侧实例确结束。
- 21 单测(客户端重试/降级、聚合拼接、回写守卫)+ 全模块 mvn test + ArchUnit 绿。

坑入手册 §6.8(TaskInfo 无 businessKey)/§6.9(503 熔断 + 回写守卫 + SYS_DATASTATUS 无主键)。

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 15:12:03 +08:00
parent 6ced9b15f2
commit ac9812e0a1
24 changed files with 1707 additions and 3 deletions

View File

@@ -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} 连接到客户库业务数据。
*
* <p><b>数据源 = 客户库只读</b>:本服务注入应用主 {@code JdbcTemplate}(default profile 连客户库副本)
* 与引擎 {@code POJOCRUDService}(其底座亦是该只读数据源)。映射与读全程只读,绝不写客户库。
*
* <p><b>两步连接</b>(对齐老系统 {@code SYS_DATASTATUS} 口径,见 framework
* {@code ProcessCoreServiceImpl} 第 2018 行 {@code select tablename,businesskey from SYS_DATASTATUS}):
* <ol>
* <li>{@code businessKey} → {@code SYS_DATASTATUS.tablename}(该表有 {@code tablename+businesskey} 列)。</li>
* <li>{@code loadPOJO(businessKey, tablename, ADMIN, false)} → 业务实体,只取<b>标题类字段</b>
* (优先引擎计算的 {@code _DISPLAY__};否则剔除系统列/主键/大文本后取业务列,封顶 6 列,只用于摘要展示)。</li>
* </ol>
*
* <p><b>优雅降级</b>:任一步失败(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<String> 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<String, Object> 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<String, Object> titleFields(GeneralPOJO po) {
Map<String, Object> fields = new LinkedHashMap<>();
Set<String> 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;
}
}

View File

@@ -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}。
*
* <p><b>职责</b>(架构第一节:gateway = Flowable REST 客户端 + 待办聚合):
* <ul>
* <li>当前用户待办——按 assignee + 候选组(JWT roles)聚合;</li>
* <li>逐条经 {@link BusinessSummaryService} 拼业务摘要(businessKey → 业务表标题字段);</li>
* <li>拼不到摘要时优雅降级为仅流程字段(由 BusinessSummaryService 内部兜底)。</li>
* </ul>
*
* <p>引擎不可达由 {@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<TodoItem> todo(String userId, List<String> candidateGroups, int firstResult, int maxResults) {
List<FlowTaskDto> tasks = flowableClient.todo(userId, candidateGroups, null, firstResult, maxResults);
return aggregate(tasks);
}
/** 当前用户已办。 */
public List<TodoItem> done(String userId, int firstResult, int maxResults) {
List<FlowTaskDto> tasks = flowableClient.done(userId, firstResult, maxResults);
return aggregate(tasks);
}
/** 逐条拼业务摘要(摘要侧异常已在 BusinessSummaryService 内降级,不在此抛出)。 */
private List<TodoItem> aggregate(List<FlowTaskDto> tasks) {
List<TodoItem> 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;
}
}

View File

@@ -0,0 +1,52 @@
package com.eip4.platform.flowgateway.aggregate;
import java.util.Map;
import com.eip4.platform.flowgateway.client.FlowTaskDto;
/**
* 聚合后的待办/已办条目:Flowable 流程字段 + 业务摘要。
*
* <p>聚合层把端口 8089 返回的纯流程任务({@link FlowTaskDto})与业务数据连接:
* 任务 {@code businessKey} → {@code SYS_DATASTATUS.tablename} → 引擎 {@code loadPOJO} 读业务表标题字段。
* 拼不到业务摘要(businessKey 无映射 / 业务表不在当前库 / 元数据缺失)时,{@code businessSummary} 为空 Map、
* {@code businessTable} 为 null —— <b>优雅降级为仅流程字段</b>,绝不让业务侧缺数据拖垮整张待办列表。
*/
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<String, Object> 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;
}
}

View File

@@ -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}。
*
* <p>用专属 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();
}
}

View File

@@ -0,0 +1,76 @@
package com.eip4.platform.flowgateway.client;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 流程网关客户端配置(前缀 {@code eip4.flow})。
*
* <p>网关是单体侧 Flowable 客户端,引擎在独立 {@code flowable-service}(端口 8089,架构第三节)。
* 这里配置基址、超时、重试次数——服务私有化部署时仅改 {@code base-url} 即可指向客户现场的引擎进程。
*
* <ul>
* <li>{@code base-url} —— flowable-service 基址,默认 {@code http://localhost:8089}</li>
* <li>{@code connect-timeout-ms} —— 建连超时(ms),默认 2000</li>
* <li>{@code read-timeout-ms} —— 读超时(ms),默认 5000</li>
* <li>{@code max-retries} —— 瞬时故障重试次数(仅连接级失败重试,非业务错),默认 2</li>
* <li>{@code retry-backoff-ms} —— 重试间隔(ms),默认 200</li>
* </ul>
*/
@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;
}
}

View File

@@ -0,0 +1,24 @@
package com.eip4.platform.flowgateway.client;
import org.springframework.http.HttpStatusCode;
/**
* flowable-service 返回业务级错误状态(4xx/5xx,如挂起任务 complete 被引擎拒为 409)时抛出。
*
* <p>与 {@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;
}
}

View File

@@ -0,0 +1,16 @@
package com.eip4.platform.flowgateway.client;
/**
* flowable-service(引擎独立进程,8089)不可达时抛出——熔断降级语义载体。
*
* <p>由 {@code @ControllerAdvice}(见 {@code web/FlowGatewayExceptionHandler})映射为 HTTP <b>503</b>
* (Service Unavailable),让待办聚合在引擎宕机/网络分区时返回<b>明确的 503 语义</b>而非 500 堆栈
* (任务要求:服务不可达 → 503,非裸栈)。仅连接级/超时/重试耗尽时抛此异常,业务级 4xx/5xx
* 由 {@link FlowRemoteException} 承载,语义不混淆。
*/
public class FlowServiceUnavailableException extends RuntimeException {
public FlowServiceUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,23 @@
package com.eip4.platform.flowgateway.client;
/**
* flowable-service 返回的任务 DTO(出参契约,贴 {@code flowable-service} 的 {@code TaskDto})。
*
* <p>字段与端口 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;
}

View File

@@ -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,架构第三节)。
*
* <p><b>三道工程纪律</b>:
* <ol>
* <li><b>超时</b>:连接/读超时由 {@link FlowGatewayProperties} 配置,经 {@code RestClient} 的
* 请求工厂落地(见 {@code FlowGatewayConfig});引擎卡死时快速失败而非线程挂死。</li>
* <li><b>重试</b>:仅<b>连接级瞬时故障</b>(连不上/IO 抖动)重试 {@code maxRetries} 次,带退避;
* 业务级 4xx/5xx <b>绝不重试</b>(语义错重试无意义且可能重复副作用,如 complete)。</li>
* <li><b>熔断降级</b>:重试耗尽仍连不上 → 抛 {@link FlowServiceUnavailableException}
* (→ HTTP 503);引擎在线但拒绝(4xx/5xx)→ 抛 {@link FlowRemoteException}(透传原状态码)。</li>
* </ol>
*
* <p>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<List<FlowTaskDto>> 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 + 候选组/候选用户;空集合表示不按该维度过滤)。
*
* <p>对应引擎 {@code TaskQuery.active().taskAssignee()/taskCandidateGroup()/taskCandidateUser()}。
* 三维任一为空则不下发该 query 参数(由 flowable-service 侧 {@code isBlank} 跳过)。
*/
public List<FlowTaskDto> todo(String assignee, List<String> 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<FlowTaskDto> 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<String, Object> variables) {
post("办理", "/api/flow/tasks/" + taskId + "/complete",
variables == null ? Map.of() : Map.of("variables", variables), Void.class);
}
/** 发起流程(processDefinitionKey 或 processDefinitionId 二选一,可带 businessKey 与变量)。 */
public ProcessInstanceDto start(Map<String, Object> 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<FlowTaskDto> get(String op, java.util.function.Function<UriBuilder, java.net.URI> uriFn) {
return execute(op, () -> restClient.get()
.uri(uriFn::apply)
.retrieve()
.body(TASK_LIST));
}
private <T> T post(String op, String path, Object body, Class<T> respType) {
return execute(op, () -> restClient.post()
.uri(path)
.body(body == null ? Map.of() : body)
.retrieve()
.body(respType));
}
/**
* 统一执行:连接级故障带退避重试 maxRetries 次,耗尽 → 503 语义;业务错(4xx/5xx)立即透传不重试。
*/
private <T> T execute(String op, java.util.function.Supplier<T> 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();
}
}

View File

@@ -0,0 +1,16 @@
package com.eip4.platform.flowgateway.client;
/**
* flowable-service 发起流程返回的实例 DTO(贴 {@code flowable-service} 的 {@code ProcessInstanceDto})。
*
* <p>对应端口 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;
}

View File

@@ -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 抛出的两类异常,不拦其他)。
*
* <ul>
* <li>{@link FlowServiceUnavailableException}(引擎进程不可达,重试耗尽)→ <b>503</b>
* Service Unavailable —— 待办聚合在引擎宕机/网络分区时返回明确的服务不可用语义,而非 500 堆栈。</li>
* <li>{@link FlowRemoteException}(引擎在线但拒绝,如挂起拒办 409)→ <b>透传原状态码</b>,
* 保留 Flowable 语义。</li>
* </ul>
*/
@RestControllerAdvice(basePackages = "com.eip4.platform.flowgateway")
public class FlowGatewayExceptionHandler {
@ExceptionHandler(FlowServiceUnavailableException.class)
public ResponseEntity<Map<String, Object>> onUnavailable(FlowServiceUnavailableException e) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"status", 503,
"error", "FLOW_SERVICE_UNAVAILABLE",
"message", "工作流引擎服务暂不可达,请稍后重试"));
}
@ExceptionHandler(FlowRemoteException.class)
public ResponseEntity<Map<String, Object>> onRemote(FlowRemoteException e) {
return ResponseEntity.status(e.getStatus())
.body(Map.of(
"status", e.getStatus().value(),
"error", "FLOW_REMOTE_ERROR",
"message", e.getMessage()));
}
}

View File

@@ -0,0 +1,33 @@
package com.eip4.platform.flowgateway.web;
import java.util.Map;
/**
* 待办网关 REST 入参 DTO(办理/发起)。
*/
public final class GatewayRequests {
private GatewayRequests() {
}
/**
* 办理(complete)请求。
*
* <p>{@code variables} 透传给引擎;{@code businessKey}/{@code processInstanceId}/{@code tableName}
* 用于办理后按老系统语义回写 SYS_DATASTATUS(三者齐备才回写,缺则只办理不回写)。
*/
public static class CompleteRequest {
public Map<String, Object> 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<String, Object> variables;
}
}

View File

@@ -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 暴露)。
*
* <p>引擎在独立 {@code flowable-service}(8089);本门面经 {@link FlowableClient} 调引擎,聚合业务摘要,
* 并在办理后按老系统语义回写业务状态。当前用户身份从 JWT 上下文({@link AuthPrincipal})取
* {@code userId}(assignee 维度)与 {@code roles}(候选组待办)。
*
* <ul>
* <li>{@code GET /api/todo} —— 当前用户待办(含候选组待办)</li>
* <li>{@code GET /api/done} —— 当前用户已办</li>
* <li>{@code POST /api/task/{id}/complete} —— 办理 + 按语义回写 SYS_DATASTATUS</li>
* <li>{@code POST /api/process/start} —— 发起流程</li>
* </ul>
*
* <p>引擎不可达时,聚合层经 {@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<TodoItem> todo(@AuthenticationPrincipal AuthPrincipal principal,
@RequestParam(defaultValue = "0") int firstResult,
@RequestParam(defaultValue = "50") int maxResults) {
String userId = principal == null ? null : principal.userId();
List<String> 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<TodoItem> 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<Map<String, Object>> complete(@PathVariable String id,
@RequestBody(required = false) GatewayRequests.CompleteRequest req) {
flowableClient.complete(id, req == null ? null : req.variables);
Map<String, Object> 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<ProcessInstanceDto> start(@RequestBody GatewayRequests.StartRequest req) {
Map<String, Object> 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();
}
}

View File

@@ -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}。
*
* <p><b>语义来源</b>(逐条对齐 framework,侦察后照原口径实现):
* <ul>
* <li>{@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} 原样复刻。</li>
* <li>{@code WfChangeStatus.getStatus}:{@code SELECT DATASTATUS FROM SYS_DATASTATUS WHERE BUSINESSKEY=?},
* 无行返回 null —— {@link #getStatus} 复刻。</li>
* <li>{@code ProcessCoreServiceImpl.passProcess}(办理通过)的回写算法:complete 后
* {@code status = 流程已结束 ? STATUS_PASS(3) : STATUS_PROCESSING(2)};且<b>仅当
* {@code oldstatus != null && oldstatus < status}</b> 才回写(状态单调递增,不回退、不在无记录时凭空插入)
* —— {@link #afterComplete} 复刻该守卫。</li>
* </ul>
*
* <p>DATASTATUS 值语义(framework {@code ProcessCoreService} 常量,即盘点报告所指):
* 1=未提交、2=处理中(在批/审批中)、3=通过(已归档/审批通过)、4=未通过、5=重新提交、6=作废。
*
* <p><b>纪律:本地库验证,客户库只读</b>——本服务注入应用主 {@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);
}
}

View File

@@ -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<target 不回退/不重复写。
DELETE FROM sys_datastatus WHERE businesskey = 'P34-WB-TEST-0002';
INSERT INTO sys_datastatus (businesskey, tablename, datastatus)
VALUES ('P34-WB-TEST-0002', 'ORDER_ENTITY', 3);