release: FL 2.0 候选(C01 记账边界+P2-2 认领协议+D10 变量契约+D11 资格终审+D09 激活代次+T01/T03/T04/T05)
按《FL最终代码审计与上线阻断清单》194 项已审计工作树形成候选,基座 = origin/main 11e0778。
- 源码/测试/资源:沿用已审计工作树内容(96 项相对远端为新增或更新),含未跟踪实现
CallbackFactStore、CallbackSourcePolicy、VariableContract、FormalApplyCommandService、
FlowActorContextGate 等;C01 续验夹具修正一并入内。
- CI:保留远端 11e0778 的门禁强化(CI_SOURCE_SHA 核对、容器回收验证、空 schema 反向门禁、
main ref 才推镜像);ci/flow-test-schema.sql 按当前实体重新生成(14→20 表,补 6 新表与
6 新列,回调日志复合唯一键 uk_flw_log_event_reg),workflow 表数断言同步 14→20。
- 依据:docs/tasks/evidence/FL-final-audit-20261027(194 项哈希/版本核对)。
This commit is contained in:
@@ -0,0 +1,265 @@
|
||||
package com.yunhai.flowcenter.callback;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackLog;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackReg;
|
||||
import com.yunhai.flowcenter.notify.UserMsgClient;
|
||||
import com.yunhai.flowcenter.repository.FlwCallbackLogRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwCallbackRegRepository;
|
||||
import com.yunhai.flowcenter.service.FlowCallbackAdminService;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/** 两个独立本地集合、独立数据库会话,共用真 MySQL 8 和受屏障控制的真 HTTP 接收端。 */
|
||||
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@ActiveProfiles("test")
|
||||
class CallbackConcurrentPushIT {
|
||||
@Autowired FlwCallbackLogRepository logs;
|
||||
@Autowired FlwCallbackRegRepository regs;
|
||||
@Autowired CallbackLogStore store;
|
||||
@Autowired DataSource dataSource;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
// 仅关闭与本类无关的扫描;竞争由测试屏障精确触发,不让调度器成为第三个执行者。
|
||||
@MockBean CallbackDispatcher dispatcher;
|
||||
|
||||
HttpServer server;
|
||||
ExecutorService serverThreads;
|
||||
ExecutorService workers;
|
||||
final List<Long> logIds=new ArrayList<>(), regIds=new ArrayList<>();
|
||||
final AtomicReference<Receiver> receiver=new AtomicReference<>();
|
||||
final AtomicInteger hits=new AtomicInteger(), active=new AtomicInteger(), maxActive=new AtomicInteger();
|
||||
final List<String> eventIds=new CopyOnWriteArrayList<>(), bodies=new CopyOnWriteArrayList<>();
|
||||
CountingMessages messages;
|
||||
CallbackProperties properties;
|
||||
|
||||
interface Receiver { int respond(int sequence) throws Exception; }
|
||||
|
||||
@BeforeEach void setup() throws Exception {
|
||||
assertEquals(13429,jdbc.queryForObject("SELECT @@port",Integer.class));
|
||||
assertTrue(jdbc.queryForObject("SELECT @@version",String.class).startsWith("8."));
|
||||
assertEquals("c:/users/chenx/.zcode/tmp/fl-d09-zcode-mysql8/",
|
||||
jdbc.queryForObject("SELECT @@datadir",String.class).replace('\\','/').toLowerCase());
|
||||
assertEquals("fl_d09_20261026",jdbc.queryForObject("SELECT DATABASE()",String.class));
|
||||
messages=new CountingMessages();properties=new CallbackProperties();properties.setAlertUserIds("999");
|
||||
workers=Executors.newFixedThreadPool(4);serverThreads=Executors.newCachedThreadPool();
|
||||
server=HttpServer.create(new InetSocketAddress("127.0.0.1",0),0);server.setExecutor(serverThreads);
|
||||
receiver.set(n -> 200);
|
||||
server.createContext("/callback",this::receive);server.start();
|
||||
}
|
||||
|
||||
@AfterEach void cleanup() throws Exception {
|
||||
if (workers!=null) {workers.shutdownNow();assertTrue(workers.awaitTermination(12,TimeUnit.SECONDS));}
|
||||
if (server!=null) server.stop(0);
|
||||
if (serverThreads!=null) serverThreads.shutdownNow();
|
||||
for (Long id:logIds) logs.deleteById(id);
|
||||
for (Long id:regIds) regs.deleteById(id);
|
||||
}
|
||||
|
||||
void receive(HttpExchange exchange) {
|
||||
int now=active.incrementAndGet();maxActive.accumulateAndGet(now,Math::max);
|
||||
try {
|
||||
int sequence=hits.incrementAndGet();
|
||||
eventIds.add(exchange.getRequestHeaders().getFirst("X-Flw-EventId"));
|
||||
bodies.add(new String(org.springframework.util.StreamUtils.copyToByteArray(exchange.getRequestBody()),StandardCharsets.UTF_8));
|
||||
int status=receiver.get().respond(sequence);
|
||||
byte[] body="{\"ok\":true}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status,body.length);exchange.getResponseBody().write(body);
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
} finally {active.decrementAndGet();exchange.close();}
|
||||
}
|
||||
|
||||
CallbackPushService executor(CallbackLogStore claimStore) {
|
||||
return new CallbackPushService(logs,regs,properties,claimStore,messages,mock(ObjectProvider.class));
|
||||
}
|
||||
|
||||
FlwCallbackLog row(String eventId) {
|
||||
FlwCallbackReg reg=new FlwCallbackReg();reg.setSchId(1L);reg.setFlowGuid(UUID.randomUUID().toString().replace("-",""));
|
||||
reg.setAppKey("100018");reg.setStatus(0);reg.setSecret("p22-secret");
|
||||
reg.setCallbackUrl("http://127.0.0.1:"+server.getAddress().getPort()+"/callback");reg=regs.saveAndFlush(reg);regIds.add(reg.getId());
|
||||
FlwCallbackLog row=new FlwCallbackLog();row.setSchId(1L);row.setRegId(reg.getId());row.setEventId(eventId);
|
||||
row.setEvent("flow.submitted");row.setInstanceId(0L);row.setBizType("p22");row.setBizId(eventId);
|
||||
row.setPayloadJson("{\"eventId\":\""+eventId+"\",\"event\":\"flow.submitted\"}");
|
||||
row.setNextRetryTime(LocalDateTime.now());row=logs.saveAndFlush(row);logIds.add(row.getId());return row;
|
||||
}
|
||||
FlwCallbackLog row() {return row(UUID.randomUUID().toString().replace("-",""));}
|
||||
FlwCallbackLog current(Long id) {return logs.findById(id).orElseThrow(AssertionError::new);}
|
||||
void gate(CountDownLatch latch) throws InterruptedException {assertTrue(latch.await(8,TimeUnit.SECONDS),"barrier timed out");}
|
||||
|
||||
/** 每一轮真正同时争抢;胜者 HTTP 阻塞到落败执行者已返回,排除“恰巧串行”的假证明。 */
|
||||
void contest(FlwCallbackLog row, int result) throws Exception {
|
||||
CallbackPushService a=executor(store),b=executor(store);
|
||||
assertNotSame(ReflectionTestUtils.getField(a,"IN_FLIGHT"),ReflectionTestUtils.getField(b,"IN_FLIGHT"));
|
||||
CountDownLatch entered=new CountDownLatch(1),release=new CountDownLatch(1),returned=new CountDownLatch(1);
|
||||
receiver.set(n -> {entered.countDown();gate(release);return result;});
|
||||
CyclicBarrier start=new CyclicBarrier(2);
|
||||
Future<?> x=workers.submit(()->{start.await(5,TimeUnit.SECONDS);try {a.pushAsync(row.getId());} finally {returned.countDown();}return null;});
|
||||
Future<?> y=workers.submit(()->{start.await(5,TimeUnit.SECONDS);try {b.pushAsync(row.getId());} finally {returned.countDown();}return null;});
|
||||
try {
|
||||
gate(entered);gate(returned);
|
||||
assertEquals(1,active.get());assertTrue(a.inFlight(row.getId()) ^ b.inFlight(row.getId()));
|
||||
assertEquals(0,jdbc.queryForObject("SELECT count(*) FROM information_schema.innodb_trx WHERE trx_mysql_thread_id="
|
||||
+ "IS_USED_LOCK(SHA2(CONCAT(LOWER(DATABASE()), ':flw_callback:', ?, ':', ?),256))",Integer.class,row.getEventId(),row.getRegId()),
|
||||
"HTTP 期间不得持有数据库事务");
|
||||
} finally {release.countDown();}
|
||||
x.get(12,TimeUnit.SECONDS);y.get(12,TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test void independentExecutorsHaveExactlyOneEffectiveDispatcher() throws Exception {
|
||||
FlwCallbackLog row=row();contest(row,200);
|
||||
assertEquals(1,hits.get());assertEquals(1,maxActive.get());assertEquals(1,current(row.getId()).getStatus());
|
||||
assertEquals(0,current(row.getId()).getRetryCount());
|
||||
executor(store).pushAsync(row.getId());assertEquals(1,hits.get(),"重复认领成功行不应再发 HTTP");
|
||||
assertThat(eventIds).containsExactly(row.getEventId());assertThat(bodies).containsExactly(row.getPayloadJson());
|
||||
}
|
||||
|
||||
@Test void competingFailuresIncrementOncePerValidAttemptAndAlertOnlyOnCommittedThreshold() throws Exception {
|
||||
FlwCallbackLog row=row();
|
||||
List<Long> backoff=properties.getRetryBackoffMinutes();
|
||||
for (int attempt=1;attempt<=7;attempt++) {
|
||||
LocalDateTime before=LocalDateTime.now();contest(row,503);
|
||||
FlwCallbackLog saved=current(row.getId());long minutes=attempt<=backoff.size()?backoff.get(attempt-1):60;
|
||||
assertEquals(attempt,saved.getRetryCount());assertEquals(attempt,hits.get());assertEquals(0,saved.getStatus());
|
||||
assertNotNull(saved.getLastError());assertThat(saved.getNextRetryTime())
|
||||
.isAfterOrEqualTo(before.plusMinutes(minutes)).isBeforeOrEqualTo(LocalDateTime.now().plusMinutes(minutes));
|
||||
assertEquals(attempt>=6?1:0,messages.hung.get());
|
||||
}
|
||||
assertEquals(1,maxActive.get());assertThat(eventIds).allMatch(row.getEventId()::equals);
|
||||
}
|
||||
|
||||
void awaitExpired(FlwCallbackLog row) throws Exception {
|
||||
// 直接等待数据库释放旧会话锁,不用 sleep,也不触碰旧连接以免续租。
|
||||
try (Connection connection=dataSource.getConnection();java.sql.PreparedStatement acquire=connection.prepareStatement(
|
||||
"SELECT GET_LOCK(SHA2(CONCAT(LOWER(DATABASE()), ':flw_callback:', ?, ':', ?),256),6)")) {
|
||||
acquire.setString(1,row.getEventId());acquire.setLong(2,row.getRegId());
|
||||
try(java.sql.ResultSet rs=acquire.executeQuery()){rs.next();assertEquals(1,rs.getInt(1),"expired owner must release its claim");}
|
||||
try(java.sql.PreparedStatement release=connection.prepareStatement(
|
||||
"SELECT RELEASE_LOCK(SHA2(CONCAT(LOWER(DATABASE()), ':flw_callback:', ?, ':', ?),256))")) {
|
||||
release.setString(1,row.getEventId());release.setLong(2,row.getRegId());release.execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest @CsvSource({"503,200,true", "200,503,false", "503,502,false"})
|
||||
void lateOldResultCannotOverwriteNewSuccessOrNewFailure(int oldStatus, int newStatus, boolean sameExecutor) throws Exception {
|
||||
FlwCallbackLog row=row();CallbackPushService old=executor(new CallbackLogStore(logs,dataSource,1));
|
||||
CountDownLatch entered=new CountDownLatch(1),releaseOld=new CountDownLatch(1);
|
||||
receiver.set(n -> {if(n==1){entered.countDown();gate(releaseOld);return oldStatus;}return newStatus;});
|
||||
Future<?> first=workers.submit(()->old.pushAsync(row.getId()));
|
||||
try {
|
||||
gate(entered);awaitExpired(row);
|
||||
// 同一服务实例也须能在本地旧线程未退出时恢复;另一路验证独立执行者。
|
||||
(sameExecutor ? old : executor(store)).pushAsync(row.getId());
|
||||
FlwCallbackLog newer=current(row.getId());
|
||||
assertEquals(newStatus==200?1:0,newer.getStatus());assertEquals(newStatus==200?0:1,newer.getRetryCount());
|
||||
releaseOld.countDown();first.get(12,TimeUnit.SECONDS);
|
||||
FlwCallbackLog after=current(row.getId());
|
||||
assertEquals(newer.getStatus(),after.getStatus());assertEquals(newer.getRetryCount(),after.getRetryCount());
|
||||
assertEquals(newer.getLastError(),after.getLastError());assertEquals(newer.getNextRetryTime(),after.getNextRetryTime());
|
||||
assertEquals(newer.getLastHttpStatus(),after.getLastHttpStatus());assertEquals(newer.getPushTime(),after.getPushTime());
|
||||
assertEquals(newer.getUpdateTime(),after.getUpdateTime());assertEquals(2,hits.get());
|
||||
assertThat(eventIds).containsExactly(row.getEventId(),row.getEventId());
|
||||
} finally {releaseOld.countDown();}
|
||||
}
|
||||
|
||||
@Test void abandonedAndAbortedClaimBothRecoverWithoutARecordMigration() throws Exception {
|
||||
for (boolean abort:Arrays.asList(false,true)) {
|
||||
FlwCallbackLog row=row();
|
||||
try (CallbackLogStore.Claim orphan=new CallbackLogStore(logs,dataSource,1).tryClaim(row.getId())) {
|
||||
assertNotNull(orphan);assertTrue(orphan.active());
|
||||
assertNull(store.tryClaim(row.getId()));
|
||||
if(abort)((Connection)ReflectionTestUtils.getField(orphan,"connection")).abort(Runnable::run);
|
||||
awaitExpired(row);executor(store).pushAsync(row.getId());
|
||||
assertEquals(1,current(row.getId()).getStatus());assertFalse(orphan.failure("late failure",null,1));
|
||||
assertFalse(orphan.success(200));assertEquals(0,current(row.getId()).getRetryCount());
|
||||
}
|
||||
}
|
||||
assertEquals(2,hits.get());
|
||||
}
|
||||
|
||||
@Test void aClaimCanSettleOnlyOnceAndReleasedSessionRestoresItsTimeout() throws Exception {
|
||||
FlwCallbackLog row=row();
|
||||
try (CallbackLogStore.Claim claim=store.tryClaim(row.getId())) {
|
||||
assertNotNull(claim);assertTrue(((Connection)ReflectionTestUtils.getField(claim,"connection")).getAutoCommit());
|
||||
assertTrue(claim.failure("first", "503",1));assertFalse(claim.failure("duplicate",null,5));assertFalse(claim.success(200));
|
||||
}
|
||||
assertEquals(1,current(row.getId()).getRetryCount());assertEquals("first",current(row.getId()).getLastError());
|
||||
try (Connection connection=dataSource.getConnection();java.sql.Statement st=connection.createStatement();
|
||||
java.sql.ResultSet rs=st.executeQuery("SELECT @@session.wait_timeout")) {
|
||||
rs.next();assertEquals(jdbc.queryForObject("SELECT @@global.wait_timeout",Long.class),Long.valueOf(rs.getLong(1)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void differentSubscriptionsShareEventIdentityButHaveIndependentDispatchRights() throws Exception {
|
||||
FlwCallbackLog a=row(),b=row(a.getEventId());
|
||||
CountDownLatch entered=new CountDownLatch(2),release=new CountDownLatch(1);
|
||||
receiver.set(n -> {entered.countDown();gate(release);return 200;});
|
||||
Future<?> first=workers.submit(()->executor(store).pushAsync(a.getId()));
|
||||
Future<?> second=workers.submit(()->executor(store).pushAsync(b.getId()));
|
||||
try {gate(entered);assertEquals(2,active.get());}finally {release.countDown();}
|
||||
first.get(12,TimeUnit.SECONDS);second.get(12,TimeUnit.SECONDS);
|
||||
assertEquals(1,current(a.getId()).getStatus());assertEquals(1,current(b.getId()).getStatus());
|
||||
assertThat(eventIds).containsExactlyInAnyOrder(a.getEventId(),a.getEventId());
|
||||
FlwCallbackLog duplicate=new FlwCallbackLog();org.springframework.beans.BeanUtils.copyProperties(a,duplicate,"id");
|
||||
assertThrows(org.springframework.dao.DataIntegrityViolationException.class,()->logs.saveAndFlush(duplicate));
|
||||
}
|
||||
|
||||
@Test void manualActionsCannotResetOrOverwriteAnActiveOrSuccessfulAttempt() throws Exception {
|
||||
FlwCallbackLog row=row();CallbackPushService worker=executor(store);
|
||||
FlowCallbackAdminService admin=new FlowCallbackAdminService(regs,logs,worker,properties,store);
|
||||
CountDownLatch entered=new CountDownLatch(1),release=new CountDownLatch(1);
|
||||
receiver.set(n -> {entered.countDown();gate(release);return 200;});
|
||||
Future<?> sending=workers.submit(()->worker.pushAsync(row.getId()));
|
||||
try {
|
||||
gate(entered);
|
||||
assertThrows(BizException.class,()->admin.rePush(1L,Collections.singletonList(row.getId())));
|
||||
assertThrows(BizException.class,()->admin.markDead(1L,row.getId()));
|
||||
assertEquals(0,current(row.getId()).getRetryCount());
|
||||
} finally {release.countDown();}
|
||||
sending.get(12,TimeUnit.SECONDS);assertEquals(1,current(row.getId()).getStatus());
|
||||
assertThrows(BizException.class,()->worker.markDead(row,"stale admin snapshot"));
|
||||
admin.rePush(1L,Collections.singletonList(row.getId()));assertEquals(1,hits.get());
|
||||
}
|
||||
|
||||
@Test void batchManualReplayCommitsBeforeHttpAndKeepsSuccessfulRowsUntouched() {
|
||||
FlwCallbackLog a=row(),b=row();CallbackPushService worker=executor(store);
|
||||
worker.markDead(a,"manual");worker.pushAsync(b.getId());
|
||||
FlowCallbackAdminService admin=new FlowCallbackAdminService(regs,logs,worker,properties,store);
|
||||
receiver.set(n -> {assertEquals(0,current(a.getId()).getStatus());assertEquals(0,current(a.getId()).getRetryCount());return 200;});
|
||||
admin.rePush(1L,Arrays.asList(a.getId(),b.getId()));
|
||||
assertEquals(2,hits.get());assertEquals(1,current(a.getId()).getStatus());assertEquals(1,current(b.getId()).getStatus());
|
||||
}
|
||||
|
||||
static class CountingMessages extends UserMsgClient {
|
||||
final AtomicInteger hung=new AtomicInteger();
|
||||
CountingMessages(){super(null,null,false,"");}
|
||||
@Override public void sendUserMsg(Integer sch,List<Integer> users,Integer type,String bizType,String bizId,
|
||||
String title,String content,String path,String app,String number,Integer expiry) {
|
||||
if(number!=null&&number.startsWith("hang:"))hung.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,9 +171,10 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
+ "\"submitterId\":201,\"submitterName\":\"张三\"}";
|
||||
org.springframework.http.ResponseEntity<JsonNode> applyResp =
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
// 3. 轮询 stub:submitted + task.created 两事件都到齐(探活 ping 不计)
|
||||
// 3. 轮询 stub:submitted + task.created 两事件都到齐(探活 ping 不计;异步首推
|
||||
// 可能被启动扫描的遗留行恢复推送短暂占池,等待上限放宽——P1-1)
|
||||
waitUntil(() -> received.stream().anyMatch(r -> r.body.contains("flow.submitted"))
|
||||
&& received.stream().anyMatch(r -> r.body.contains("flow.task.created")), 10_000);
|
||||
&& received.stream().anyMatch(r -> r.body.contains("flow.task.created")), 60_000);
|
||||
boolean hasSubmitted = false;
|
||||
boolean hasTaskCreated = false;
|
||||
for (Received r : received) {
|
||||
@@ -221,10 +222,13 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
.filter(r -> r.body != null && r.body.contains("\"ping\"")).findFirst().orElse(null);
|
||||
assertNotNull(ping, "注册探活应命中 stub");
|
||||
assertAppSignature("/callback/flow", ping);
|
||||
// 4. 日志表成功态(异步推送落定,轮询等待)
|
||||
assertTrue(logRepository.findAll().size() >= 2);
|
||||
// 4. 日志表成功态(异步推送落定,轮询等待——只认本用例两行,残留行不计)
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.allMatch(l -> l.getStatus() == FlwEnums.CallbackLogStatus.SUCCESS.getCode()), 10_000);
|
||||
.filter(l -> "cb-1".equals(l.getBizId())).count() >= 2, 60_000);
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.filter(l -> "cb-1".equals(l.getBizId()))
|
||||
.allMatch(l -> l.getStatus() == FlwEnums.CallbackLogStatus.SUCCESS.getCode()),
|
||||
60_000);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -261,7 +265,7 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
+ "\"submitterId\":201,\"submitterName\":\"张三\"}";
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
|
||||
waitUntil(() -> hits.stream().anyMatch(r -> r.body != null && r.body.contains("flow.submitted")), 10_000);
|
||||
waitUntil(() -> hits.stream().anyMatch(r -> r.body != null && r.body.contains("flow.submitted")), 60_000);
|
||||
Received push = hits.stream()
|
||||
.filter(r -> r.body != null && r.body.contains("flow.submitted"))
|
||||
.findFirst().orElseThrow(IllegalStateException::new);
|
||||
@@ -288,16 +292,14 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
+ "\"submitterId\":201,\"submitterName\":\"张三\"}";
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
|
||||
// 首推失败:retryCount=1(异步首推,轮询等待)
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.anyMatch(l -> l.getRetryCount() != null && l.getRetryCount() >= 1), 10_000);
|
||||
// 首推失败:retryCount=1(异步首推,轮询等待——只认本用例行)
|
||||
waitFirstFailureLanded("cb-2");
|
||||
// 手工逐次触发扫描语义再失败 5 轮(共 6 次,越过退避表 5 项)
|
||||
FlwCallbackLog hung = soleRow("cb-2");
|
||||
for (int round = 0; round < 5; round++) {
|
||||
for (FlwCallbackLog row : logRepository.findAll()) {
|
||||
pushService.pushAsync(row.getId());
|
||||
}
|
||||
pushService.pushAsync(hung.getId());
|
||||
hung = logRepository.findById(hung.getId()).orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
FlwCallbackLog hung = logRepository.findAll().get(0);
|
||||
// T1.1 核心语义:持续重试不自动死信——status 仍=0、retryCount=6、nextRetry≈now+60min(封顶)
|
||||
assertEquals(FlwEnums.CallbackLogStatus.PENDING.getCode(), hung.getStatus(),
|
||||
"越过退避表后必须保持待推持续重试,不得自动死信");
|
||||
@@ -308,8 +310,9 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
&& hung.getNextRetryTime().isBefore(expectedNext.plusMinutes(5)),
|
||||
"越过退避表后 nextRetryTime 应封顶 +60 分钟: " + hung.getNextRetryTime());
|
||||
assertTrue(logRepository.findAll().stream()
|
||||
.allMatch(l -> l.getStatus() == FlwEnums.CallbackLogStatus.PENDING.getCode()),
|
||||
"任何行都不应出现死信(status=2)");
|
||||
.filter(l -> "cb-2".equals(l.getBizId()))
|
||||
.allMatch(l -> l.getStatus() == FlwEnums.CallbackLogStatus.PENDING.getCode()),
|
||||
"本用例行不应出现死信(status=2)");
|
||||
assertNotNull(hung.getLastError());
|
||||
}
|
||||
|
||||
@@ -330,23 +333,21 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
+ "\"bizType\":\"svc_item\",\"bizId\":\"cb-4\",\"bizTitle\":\"张三的告警件\","
|
||||
+ "\"submitterId\":201,\"submitterName\":\"张三\"}";
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.anyMatch(l -> l.getRetryCount() != null && l.getRetryCount() >= 1), 10_000);
|
||||
waitFirstFailureLanded("cb-4");
|
||||
|
||||
// 失败到第 6 次(=挂起阈值):告警恰一次
|
||||
FlwCallbackLog row = soleRow("cb-4");
|
||||
for (int round = 0; round < 5; round++) {
|
||||
for (FlwCallbackLog row : logRepository.findAll()) {
|
||||
pushService.pushAsync(row.getId());
|
||||
}
|
||||
pushService.pushAsync(row.getId());
|
||||
row = logRepository.findById(row.getId()).orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
assertEquals(1, STUB_USER_MSG.hangAlerts.get(), "第 6 次失败后挂起告警应恰发送一次");
|
||||
|
||||
// 第 7 次失败:仍是 1(恰一次)
|
||||
for (FlwCallbackLog row : logRepository.findAll()) {
|
||||
pushService.pushAsync(row.getId());
|
||||
}
|
||||
pushService.pushAsync(row.getId());
|
||||
row = logRepository.findById(row.getId()).orElseThrow(IllegalStateException::new);
|
||||
assertEquals(1, STUB_USER_MSG.hangAlerts.get(), "第 7 次失败后告警计数仍应为 1");
|
||||
assertEquals(7, logRepository.findAll().get(0).getRetryCount());
|
||||
assertEquals(7, row.getRetryCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -373,13 +374,12 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
|
||||
// 首推 500 → 进入重试(status=0, retryCount=1)
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.anyMatch(l -> l.getRetryCount() != null && l.getRetryCount() >= 1), 10_000);
|
||||
waitFirstFailureLanded("cb-5");
|
||||
// 消费方恢复后(扫描/重推触发)→ 200 → status=1 + pushTime 落定
|
||||
for (FlwCallbackLog row : logRepository.findAll()) {
|
||||
pushService.pushAsync(row.getId());
|
||||
}
|
||||
FlwCallbackLog recovered = logRepository.findAll().get(0);
|
||||
FlwCallbackLog failed = soleRow("cb-5");
|
||||
pushService.pushAsync(failed.getId());
|
||||
FlwCallbackLog recovered = logRepository.findById(failed.getId())
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
assertEquals(FlwEnums.CallbackLogStatus.SUCCESS.getCode(), recovered.getStatus(),
|
||||
"瞬时失败恢复后应自动治愈为成功");
|
||||
assertNotNull(recovered.getPushTime());
|
||||
@@ -402,37 +402,39 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
+ "\"bizType\":\"svc_item\",\"bizId\":\"cb-6\",\"bizTitle\":\"张三的管理件\","
|
||||
+ "\"submitterId\":201,\"submitterName\":\"张三\"}";
|
||||
client.post("/oapi/flow/apply?schId=1", body, JsonNode.class);
|
||||
waitUntil(() -> logRepository.findAll().stream()
|
||||
.anyMatch(l -> l.getRetryCount() != null && l.getRetryCount() >= 1), 10_000);
|
||||
waitFirstFailureLanded("cb-6");
|
||||
FlwCallbackLog hung = soleRow("cb-6");
|
||||
for (int round = 0; round < 5; round++) {
|
||||
for (FlwCallbackLog row : logRepository.findAll()) {
|
||||
pushService.pushAsync(row.getId());
|
||||
}
|
||||
pushService.pushAsync(hung.getId());
|
||||
hung = logRepository.findById(hung.getId()).orElseThrow(IllegalStateException::new);
|
||||
}
|
||||
FlwCallbackLog hung = logRepository.findAll().get(0);
|
||||
assertEquals(6, hung.getRetryCount());
|
||||
final FlwCallbackLog hungRow = hung;
|
||||
|
||||
// 挂起列表:status=0 且 retryCount≥阈值的分页行,不含正常行
|
||||
// 挂起列表:包含本用例挂起行,且该行合法(status=0、retryCount≥阈值)
|
||||
com.yunhai.platform.utils.model.BasePageResult<FlwCallbackLog> hungPage =
|
||||
callbackAdminService.pageHung(SCH, 1, 10);
|
||||
assertTrue(hungPage.getContent().stream().anyMatch(l -> l.getId().equals(hung.getId())));
|
||||
assertTrue(hungPage.getContent().stream()
|
||||
.allMatch(l -> l.getStatus() == FlwEnums.CallbackLogStatus.PENDING.getCode()
|
||||
&& l.getRetryCount() >= 6));
|
||||
assertTrue(hungPage.getContent().stream().anyMatch(l -> l.getId().equals(hungRow.getId())));
|
||||
FlwCallbackLog listed = hungPage.getContent().stream()
|
||||
.filter(l -> l.getId().equals(hungRow.getId())).findFirst()
|
||||
.orElseThrow(IllegalStateException::new);
|
||||
assertTrue(listed.getStatus() == FlwEnums.CallbackLogStatus.PENDING.getCode()
|
||||
&& listed.getRetryCount() >= 6,
|
||||
"挂起列表中的本用例行必须待推且达阈值");
|
||||
|
||||
// 管理端手工标记死信(唯一死信入口)
|
||||
callbackAdminService.markDead(SCH, hung.getId());
|
||||
FlwCallbackLog dead = logRepository.findById(hung.getId()).orElseThrow(IllegalStateException::new);
|
||||
callbackAdminService.markDead(SCH, hungRow.getId());
|
||||
FlwCallbackLog dead = logRepository.findById(hungRow.getId()).orElseThrow(IllegalStateException::new);
|
||||
assertEquals(FlwEnums.CallbackLogStatus.DEAD.getCode(), dead.getStatus());
|
||||
|
||||
// 恢复消费方地址后既有 rePush 复活:置回待推立即推送 → 成功
|
||||
regRow.setCallbackUrl("http://localhost:" + stubPort + "/callback/flow");
|
||||
regRepository.save(regRow);
|
||||
callbackAdminService.rePush(SCH, java.util.Collections.singletonList(hung.getId()));
|
||||
callbackAdminService.rePush(SCH, java.util.Collections.singletonList(hungRow.getId()));
|
||||
waitUntil(() -> {
|
||||
FlwCallbackLog row = logRepository.findById(hung.getId()).orElse(null);
|
||||
FlwCallbackLog row = logRepository.findById(hungRow.getId()).orElse(null);
|
||||
return row != null && row.getStatus() == FlwEnums.CallbackLogStatus.SUCCESS.getCode();
|
||||
}, 10_000);
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -465,6 +467,29 @@ class CallbackDispatchIT extends FlowTestSupport {
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 本用例自建投递行(bizId 每用例唯一)。P1-1 教训:库中会残留上一轮运行未推完的
|
||||
* PENDING 行(崩溃/中断运行遗产),启动扫描会立即恢复推送它们——等待谓词与行定位
|
||||
* 一律以本用例 bizId 过滤,不与残留行混淆。
|
||||
*/
|
||||
private FlwCallbackLog soleRow(String bizId) {
|
||||
java.util.List<FlwCallbackLog> rows = logRepository.findAll().stream()
|
||||
.filter(l -> bizId.equals(l.getBizId()))
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
assertEquals(1, rows.size(), "本用例应恰有一条投递行:bizId=" + bizId);
|
||||
return rows.get(0);
|
||||
}
|
||||
|
||||
/** 等待本用例行首推失败落定(retryCount≥1)且首推线程已完全退出 IN_FLIGHT——
|
||||
* 否则紧随的手动重推首轮会被在途跳过静默吞计(P1-1 实测根因)。 */
|
||||
private void waitFirstFailureLanded(String bizId) {
|
||||
waitUntil(() -> logRepository.findAll().stream().anyMatch(l ->
|
||||
bizId.equals(l.getBizId()) && l.getRetryCount() != null && l.getRetryCount() >= 1),
|
||||
60_000);
|
||||
FlwCallbackLog row = soleRow(bizId);
|
||||
waitUntil(() -> !pushService.inFlight(row.getId()), 10_000);
|
||||
}
|
||||
|
||||
/** 应用签名断言:canonical = METHOD + "\n" + 剥离 base-path 后的 path(+排序 query) + "\n" + ts */
|
||||
private void assertAppSignature(String expectedTarget, Received r) {
|
||||
assertNotNull(r.appKey, "推送必须带 X-App-Key");
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package com.yunhai.flowcenter.callback;
|
||||
|
||||
import com.yunhai.flowcenter.engine.FlowEvent;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackLog;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackReg;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.support.FlowTestSupport;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.boot.test.mock.mockito.SpyBean;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.util.AopTestUtils;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mockingDetails;
|
||||
|
||||
/**
|
||||
* C01: real business commit -> real AFTER_COMMIT -> independent fact commit, plus the real sweep entry.
|
||||
* Run alone on the existing P2-2 MySQL 8 fixture (13429/fl_d09_20261026), with ddl-auto=validate.
|
||||
* No test-managed transaction. Only HTTP transport is mocked: all facts/deliveries use real repositories.
|
||||
*/
|
||||
@SpringBootTest(properties = "spring.jpa.hibernate.ddl-auto=validate")
|
||||
@ActiveProfiles("test")
|
||||
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
|
||||
class CallbackFactDispatchIT extends FlowTestSupport {
|
||||
|
||||
@Autowired private DataSource dataSource;
|
||||
@Autowired private JdbcTemplate jdbc;
|
||||
@Autowired private PlatformTransactionManager transactionManager;
|
||||
@Autowired private ApplicationEventPublisher publisher;
|
||||
@PersistenceContext private EntityManager entityManager;
|
||||
@SpyBean private CallbackDispatcher dispatcher;
|
||||
@SpyBean private CallbackFactStore factStore;
|
||||
@SpyBean private CallbackLogStore logStore;
|
||||
@MockBean private CallbackPushService pushService;
|
||||
@MockBean private TaskScheduler scheduler;
|
||||
|
||||
private ExecutorService worker;
|
||||
private final AtomicBoolean skipNormalDispatch = new AtomicBoolean();
|
||||
private final AtomicBoolean failFactCommit = new AtomicBoolean();
|
||||
private final AtomicBoolean failSecondDelivery = new AtomicBoolean();
|
||||
private final AtomicInteger deliveryAttempts = new AtomicInteger();
|
||||
private final AtomicInteger flushedButRolledBack = new AtomicInteger();
|
||||
private final AtomicInteger factTransactions = new AtomicInteger();
|
||||
private final AtomicReference<Object> businessEntityManager = new AtomicReference<>();
|
||||
private final List<Long> pushed = new CopyOnWriteArrayList<>();
|
||||
private final AtomicBoolean pushSawTransaction = new AtomicBoolean();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Guard BEFORE cleanDb or any test DML. Reuse the original P2-2 verifier's physical identity.
|
||||
assertThat(jdbc.queryForObject("SELECT @@version", String.class)).startsWith("8.");
|
||||
assertThat(jdbc.queryForObject("SELECT @@port", Integer.class)).isEqualTo(13429);
|
||||
assertThat(jdbc.queryForObject("SELECT DATABASE()", String.class)).isEqualTo("fl_d09_20261026");
|
||||
String datadir = jdbc.queryForObject("SELECT @@datadir", String.class);
|
||||
assertThat(datadir.replace('\\', '/').replaceAll("/+", "/").replaceAll("/$", "").toLowerCase(java.util.Locale.ROOT))
|
||||
.isEqualTo("c:/users/chenx/.zcode/tmp/fl-d09-zcode-mysql8");
|
||||
cleanDb();
|
||||
|
||||
worker = Executors.newSingleThreadExecutor();
|
||||
// Inject only the executor, never invoke private dispatchFact: sweep itself selects and submits work.
|
||||
// Typed local first: an inline generic argument would resolve to the setField(Class<?>,...) overload.
|
||||
Object dispatcherTarget = AopTestUtils.getUltimateTargetObject(dispatcher);
|
||||
ReflectionTestUtils.setField(dispatcherTarget, "pushExecutor", worker);
|
||||
skipNormalDispatch.set(false);
|
||||
failFactCommit.set(false);
|
||||
failSecondDelivery.set(false);
|
||||
deliveryAttempts.set(0);
|
||||
flushedButRolledBack.set(0);
|
||||
factTransactions.set(0);
|
||||
pushed.clear();
|
||||
pushSawTransaction.set(false);
|
||||
businessEntityManager.set(null);
|
||||
|
||||
doAnswer(call -> skipNormalDispatch.get() ? null : call.callRealMethod())
|
||||
.when(dispatcher).onFlowEvent(any(FlowEvent.class));
|
||||
|
||||
assertThat(AopUtils.isAopProxy(factStore)).as("bookkeeping must cross a Spring transaction proxy").isTrue();
|
||||
CallbackFactStore factTarget = AopTestUtils.getUltimateTargetObject(factStore);
|
||||
assertThat(mockingDetails(factTarget).isSpy()).isTrue();
|
||||
doAnswer(call -> {
|
||||
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
|
||||
assertThat(entityManager.getDelegate()).isNotSameAs(businessEntityManager.get());
|
||||
factTransactions.incrementAndGet();
|
||||
call.callRealMethod();
|
||||
if (failFactCommit.get()) {
|
||||
// Real SQL is flushed, then the real REQUIRES_NEW transaction must roll it back.
|
||||
entityManager.flush();
|
||||
String eventId = call.getArgument(0);
|
||||
assertThat(jdbc.queryForObject("SELECT dispatched FROM flw_state_event WHERE event_id=?",
|
||||
Integer.class, eventId)).isEqualTo(1);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", eventId)).isZero();
|
||||
flushedButRolledBack.incrementAndGet();
|
||||
throw new DataAccessResourceFailureException("C01 test: failure after fact UPDATE flush");
|
||||
}
|
||||
return null;
|
||||
}).when(factTarget).markDispatched(anyString());
|
||||
|
||||
CallbackLogStore logTarget = AopTestUtils.getUltimateTargetObject(logStore);
|
||||
assertThat(mockingDetails(logTarget).isSpy()).isTrue();
|
||||
doAnswer(call -> {
|
||||
if (failSecondDelivery.get() && deliveryAttempts.incrementAndGet() == 2) {
|
||||
throw new DataAccessResourceFailureException("C01 test: second delivery persistence failed");
|
||||
}
|
||||
return call.callRealMethod();
|
||||
}).when(logTarget).persist(any(FlwCallbackLog.class));
|
||||
|
||||
doAnswer(call -> {
|
||||
pushed.add(call.getArgument(0));
|
||||
if (TransactionSynchronizationManager.isActualTransactionActive()) pushSawTransaction.set(true);
|
||||
return null;
|
||||
}).when(pushService).pushAsync(anyLong());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws Exception {
|
||||
if (worker != null) {
|
||||
worker.shutdown();
|
||||
assertThat(worker.awaitTermination(10, TimeUnit.SECONDS)).as("no work may leak into the next cleanup").isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalCommitPersistsBookkeepingAndFrozenDelivery() throws Exception {
|
||||
FlowEvent event = publish(1, false);
|
||||
drain();
|
||||
assertThat(factTransactions.get()).isEqualTo(1);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
assertDeliveries(event, 1);
|
||||
assertThat(pushed).containsExactly(deliveryIds(event).get(0));
|
||||
assertThat(pushSawTransaction.get()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroSubscribersCommitBookkeepingWithoutInventingDeliveries() throws Exception {
|
||||
FlowEvent event = publish(0, false);
|
||||
drain();
|
||||
assertThat(factTransactions.get()).isEqualTo(1);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
assertDeliveries(event, 0);
|
||||
assertThat(pushed).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void bookkeepingFailureRollsBackAndSweepReusesCommittedDelivery() throws Exception {
|
||||
failFactCommit.set(true);
|
||||
FlowEvent event = publish(1, false);
|
||||
drain();
|
||||
assertThat(flushedButRolledBack.get()).isEqualTo(1);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isZero();
|
||||
assertThat(readInt("SELECT count(*) FROM flw_instance WHERE id=?", event.getInstanceId())).isEqualTo(1);
|
||||
assertDeliveries(event, 1);
|
||||
List<Long> original = deliveryIds(event);
|
||||
|
||||
failFactCommit.set(false);
|
||||
age(event, 120);
|
||||
sweep();
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
assertThat(deliveryIds(event)).containsExactlyElementsOf(original);
|
||||
sweep();
|
||||
assertThat(deliveryIds(event)).containsExactlyElementsOf(original);
|
||||
assertThat(pushed).containsExactly(original.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepHonorsBufferThenPersistsFrozenDeliveriesIdempotently() throws Exception {
|
||||
skipNormalDispatch.set(true); // Simulate missed AFTER_COMMIT delivery, not a mocked repository.
|
||||
FlowEvent event = publish(2, false);
|
||||
age(event, 0);
|
||||
sweep();
|
||||
assertDeliveries(event, 0);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isZero();
|
||||
|
||||
age(event, 120);
|
||||
sweep();
|
||||
assertDeliveries(event, 2);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
List<Long> original = deliveryIds(event);
|
||||
sweep();
|
||||
assertThat(deliveryIds(event)).containsExactlyElementsOf(original);
|
||||
assertThat(pushed).containsExactlyInAnyOrderElementsOf(original);
|
||||
assertThat(pushSawTransaction.get()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepZeroSubscribersCommitsBookkeeping() throws Exception {
|
||||
skipNormalDispatch.set(true);
|
||||
FlowEvent event = publish(0, false);
|
||||
age(event, 120);
|
||||
sweep();
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
assertDeliveries(event, 0);
|
||||
assertThat(pushed).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalPartialPersistenceFailureCannotMarkDoneAndSweepCompletes() throws Exception {
|
||||
failSecondDelivery.set(true);
|
||||
FlowEvent event = publish(2, false);
|
||||
drain();
|
||||
assertThat(factTransactions.get()).isZero(); // dispatch failed before bookkeeping could run.
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isZero();
|
||||
assertDeliveries(event, 1);
|
||||
Long original = deliveryIds(event).get(0);
|
||||
failSecondDelivery.set(false);
|
||||
age(event, 120);
|
||||
sweep();
|
||||
assertDeliveries(event, 2);
|
||||
assertThat(deliveryIds(event)).contains(original);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepPartialPersistenceFailureRetainsFactUntilAllDeliveriesExist() throws Exception {
|
||||
skipNormalDispatch.set(true);
|
||||
FlowEvent event = publish(2, false);
|
||||
failSecondDelivery.set(true);
|
||||
age(event, 120);
|
||||
sweep();
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isZero();
|
||||
assertDeliveries(event, 1);
|
||||
Long original = deliveryIds(event).get(0);
|
||||
failSecondDelivery.set(false);
|
||||
sweep();
|
||||
assertDeliveries(event, 2);
|
||||
assertThat(deliveryIds(event)).contains(original);
|
||||
assertThat(readInt("SELECT dispatched FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isEqualTo(1);
|
||||
List<Long> completed = deliveryIds(event);
|
||||
sweep();
|
||||
assertThat(deliveryIds(event)).containsExactlyElementsOf(completed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rolledBackBusinessTransactionDoesNotDispatchOrLeaveFact() throws Exception {
|
||||
FlowEvent event = publish(1, true);
|
||||
drain();
|
||||
assertThat(readInt("SELECT count(*) FROM flw_state_event WHERE event_id=?", event.getStableEventId())).isZero();
|
||||
assertThat(readInt("SELECT count(*) FROM flw_instance WHERE id=?", event.getInstanceId())).isZero();
|
||||
assertDeliveries(event, 0);
|
||||
assertThat(factTransactions.get()).isZero();
|
||||
assertThat(pushed).isEmpty();
|
||||
}
|
||||
|
||||
private FlowEvent publish(int subscriptions, boolean rollback) {
|
||||
return new TransactionTemplate(transactionManager).execute(tx -> {
|
||||
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue();
|
||||
businessEntityManager.set(entityManager.getDelegate());
|
||||
FlwDef def = saveAndPublishDef("c01", "C01", "{\"start\":\"s\",\"nodes\":[{\"id\":\"s\",\"type\":\"START\"}],\"edges\":[]}");
|
||||
FlwInstance instance = new FlwInstance();
|
||||
instance.setSchId(SCH);
|
||||
instance.setDefId(def.getId());
|
||||
instance.setDefCode(def.getCode());
|
||||
instance.setDefVersion(def.getVersion());
|
||||
instance.setBizType("c01");
|
||||
instance.setBizId(UUID.randomUUID().toString().replace("-", ""));
|
||||
instance.setBizTitle("C01 fixture");
|
||||
instance.setSubmitterId(201);
|
||||
instance.setSubmitterName("C01 submitter");
|
||||
instance.setSubmitTime(LocalDateTime.now());
|
||||
instance.setApplyRound(1);
|
||||
instanceRepository.saveAndFlush(instance);
|
||||
for (int i = 0; i < subscriptions; i++) {
|
||||
FlwCallbackReg reg = new FlwCallbackReg();
|
||||
reg.setSchId(SCH);
|
||||
reg.setFlowGuid(def.getFlowGuid());
|
||||
reg.setAppKey("c01-" + i);
|
||||
reg.setSecret("local-test-only");
|
||||
reg.setStatus(0);
|
||||
reg.setEventTypes(FlowEvent.Type.SUBMITTED.getCode());
|
||||
reg.setCallbackUrl("http://127.0.0.1:9/c01-never-sent");
|
||||
regRepository.saveAndFlush(reg);
|
||||
}
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.SUBMITTED, instance.getId());
|
||||
publisher.publishEvent(event); // Real identity/recorder/listener registration, no manual onFlowEvent call.
|
||||
entityManager.flush();
|
||||
assertThat(event.getStableEventId()).isNotNull();
|
||||
assertThat(jdbc.queryForObject("SELECT dispatched FROM flw_state_event WHERE event_id=?",
|
||||
Integer.class, event.getStableEventId())).isZero();
|
||||
assertThat(jdbc.queryForObject("SELECT count(*) FROM flw_callback_log WHERE event_id=?",
|
||||
Integer.class, event.getStableEventId())).isZero();
|
||||
if (rollback) tx.setRollbackOnly();
|
||||
return event;
|
||||
});
|
||||
}
|
||||
|
||||
private void age(FlowEvent event, int seconds) {
|
||||
assertThat(jdbc.update("UPDATE flw_state_event SET create_time=DATE_SUB(NOW(), INTERVAL ? SECOND) WHERE event_id=?",
|
||||
seconds, event.getStableEventId())).isEqualTo(1);
|
||||
}
|
||||
|
||||
private void sweep() throws Exception {
|
||||
dispatcher.sweepUndispatchedFacts();
|
||||
drain();
|
||||
}
|
||||
|
||||
private void drain() throws Exception {
|
||||
// FIFO barriers include sweep work and its subsequently queued initial pushes; no timing sleep.
|
||||
for (int i = 0; i < 2; i++) worker.submit(() -> { }).get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private int readInt(String sql, Object value) throws Exception {
|
||||
try (Connection connection = dataSource.getConnection(); PreparedStatement query = connection.prepareStatement(sql)) {
|
||||
assertThat(connection.getAutoCommit()).isTrue();
|
||||
query.setObject(1, value);
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
assertThat(rows.next()).isTrue();
|
||||
return rows.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<Long> deliveryIds(FlowEvent event) throws Exception {
|
||||
List<Long> ids = new ArrayList<>();
|
||||
try (Connection connection = dataSource.getConnection(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT id FROM flw_callback_log WHERE event_id=? ORDER BY id")) {
|
||||
query.setString(1, event.getStableEventId());
|
||||
try (ResultSet rows = query.executeQuery()) { while (rows.next()) ids.add(rows.getLong(1)); }
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private void assertDeliveries(FlowEvent event, int expected) throws Exception {
|
||||
try (Connection connection = dataSource.getConnection(); PreparedStatement query = connection.prepareStatement(
|
||||
"SELECT l.event_id,l.payload_json,l.status,l.retry_count,r.flow_guid,r.event_types,l.reg_id "
|
||||
+ "FROM flw_callback_log l JOIN flw_callback_reg r ON r.id=l.reg_id WHERE l.event_id=?")) {
|
||||
query.setString(1, event.getStableEventId());
|
||||
int count = 0;
|
||||
java.util.Set<Long> regIds = new java.util.HashSet<>();
|
||||
try (ResultSet rows = query.executeQuery()) {
|
||||
while (rows.next()) {
|
||||
count++;
|
||||
assertThat(rows.getString(1)).isEqualTo(event.getStableEventId());
|
||||
assertThat(rows.getString(2)).isEqualTo(event.getStablePayloadJson());
|
||||
assertThat(rows.getInt(3)).isZero();
|
||||
assertThat(rows.getInt(4)).isZero();
|
||||
assertThat(rows.getString(5)).isEqualTo(new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.readTree(event.getStablePayloadJson()).path("flowGuid").asText());
|
||||
assertThat(rows.getString(6)).isEqualTo(FlowEvent.Type.SUBMITTED.getCode());
|
||||
assertThat(regIds.add(rows.getLong(7))).as("one row per event/subscription").isTrue();
|
||||
}
|
||||
}
|
||||
assertThat(count).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
package com.yunhai.flowcenter.callback;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.engine.FlowEvent;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackLog;
|
||||
import com.yunhai.flowcenter.entity.FlwCallbackReg;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.entity.FlwStateEvent;
|
||||
import com.yunhai.flowcenter.repository.FlwCallbackLogRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwCallbackRegRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwDefRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwInstanceRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwStateEventRepository;
|
||||
import com.yunhai.platform.flowcallback.FlowCallbackEventStore;
|
||||
import com.yunhai.platform.flowcallback.FlowCallbackHandler;
|
||||
import com.yunhai.platform.flowcallback.FlowCallbackProperties;
|
||||
import com.yunhai.platform.flowcallback.FlowCallbackReceiver;
|
||||
import com.yunhai.platform.openapi.flow.model.FlowCallbackEvent;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.support.SimpleTransactionStatus;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* R2(Codex 终审 D04)投递可靠性契约单测:
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>统一冻结信封</b>:正常链复用事实冻结体;恢复链对冻结体原样复用、对 R2 前存量行
|
||||
* 幂等补齐 eventId/eventSeq/flowGuid——两条路径消息体同构;</li>
|
||||
* <li><b>恢复消息实际到达真实 Receiver</b>:用 BasePlatform starter 的
|
||||
* {@link FlowCallbackReceiver}(非替身)验证正常体/恢复体均被接收、落事件行并推进
|
||||
* Handler;修复前的残缺恢复体(消息缺 eventId)被按脏消息丢弃作反例对照;</li>
|
||||
* <li><b>未可靠建行不记账</b>:任一订阅方建行失败→事实保持 dispatched=0;全部建行
|
||||
* (含 uk 并发兜底 DuplicateKeyException=已建行)→才标记 dispatched=1。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@DisplayName("事件投递恢复契约(R2:冻结信封/真实 Receiver/未建行不记账)")
|
||||
class CallbackRecoveryDeliveryTest {
|
||||
|
||||
private static final long SCH = 1L;
|
||||
private static final String FLOW_GUID = "fg-r2-recovery";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private FlwInstanceRepository instanceRepository;
|
||||
private FlwDefRepository defRepository;
|
||||
private FlwCallbackRegRepository regRepository;
|
||||
private FlwCallbackLogRepository logRepository;
|
||||
private CallbackLogStore logStore;
|
||||
private FlwStateEventRepository stateEventRepository;
|
||||
private CallbackDispatcher dispatcher;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
instanceRepository = mock(FlwInstanceRepository.class);
|
||||
defRepository = mock(FlwDefRepository.class);
|
||||
regRepository = mock(FlwCallbackRegRepository.class);
|
||||
logRepository = mock(FlwCallbackLogRepository.class);
|
||||
logStore = mock(CallbackLogStore.class);
|
||||
stateEventRepository = mock(FlwStateEventRepository.class);
|
||||
dispatcher = new CallbackDispatcher(instanceRepository, defRepository, regRepository,
|
||||
logRepository, logStore, mock(CallbackPushService.class), new CallbackProperties(),
|
||||
mapper, stateEventRepository, new CallbackFactStore(stateEventRepository));
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(dispatcher, "pushExecutor",
|
||||
mock(ExecutorService.class));
|
||||
|
||||
FlwInstance instance = new FlwInstance();
|
||||
instance.setId(900L);
|
||||
instance.setSchId(SCH);
|
||||
instance.setDefId(55L);
|
||||
instance.setVersion(2);
|
||||
instance.setApplyRound(3);
|
||||
instance.setBizType("svc_item");
|
||||
instance.setBizId("r2-42");
|
||||
when(instanceRepository.findById(900L)).thenReturn(Optional.of(instance));
|
||||
|
||||
FlwDef def = new FlwDef();
|
||||
def.setId(55L);
|
||||
def.setSchId(SCH);
|
||||
def.setFlowGuid(FLOW_GUID);
|
||||
when(defRepository.findById(55L)).thenReturn(Optional.of(def));
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0)).thenReturn(new ArrayList<>());
|
||||
|
||||
when(logRepository.existsByEventIdAndRegId(anyString(), org.mockito.ArgumentMatchers.anyLong()))
|
||||
.thenReturn(false);
|
||||
when(logStore.persist(any(FlwCallbackLog.class))).thenAnswer(c -> {
|
||||
FlwCallbackLog row = c.getArgument(0);
|
||||
row.setId(System.nanoTime());
|
||||
return row.getId();
|
||||
});
|
||||
}
|
||||
|
||||
private FlwCallbackReg reg(long id, String eventTypes) {
|
||||
FlwCallbackReg reg = new FlwCallbackReg();
|
||||
reg.setId(id);
|
||||
reg.setSchId(SCH);
|
||||
reg.setFlowGuid(FLOW_GUID);
|
||||
reg.setEventTypes(eventTypes);
|
||||
reg.setStatus(0);
|
||||
return reg;
|
||||
}
|
||||
|
||||
/** 经真实 Recorder 冻结的事实行(信封与身份同源) */
|
||||
private FlwStateEvent frozenFact() {
|
||||
FlwStateEventRecorder recorder = new FlwStateEventRecorder(stateEventRepository,
|
||||
instanceRepository, defRepository, mapper);
|
||||
when(instanceRepository.nextEventSeqForUpdate(900L)).thenReturn(7);
|
||||
when(instanceRepository.setEventSeqCounter(eq(900L), org.mockito.ArgumentMatchers.anyInt()))
|
||||
.thenReturn(1);
|
||||
when(stateEventRepository.save(any(FlwStateEvent.class))).thenAnswer(c -> c.getArgument(0));
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
event.captureRoundIdentity(3, "tok-r2");
|
||||
recorder.record(event);
|
||||
FlwStateEvent fact = new FlwStateEvent();
|
||||
fact.setId(11L);
|
||||
fact.setEventId(event.getStableEventId());
|
||||
fact.setSchId(SCH);
|
||||
fact.setInstanceId(900L);
|
||||
fact.setApplyRound(3);
|
||||
fact.setEventSeq(event.getStableEventSeq());
|
||||
fact.setEventType("flow.completed");
|
||||
fact.setPayloadJson(event.getStablePayloadJson());
|
||||
fact.setDispatched(0);
|
||||
return fact;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void dispatchFact(FlwStateEvent fact) {
|
||||
org.springframework.test.util.ReflectionTestUtils.invokeMethod(dispatcher, "dispatchFact", fact);
|
||||
}
|
||||
|
||||
// ==================== 冻结信封统一性 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("正常链复用事实冻结体:投递行消息体=冻结信封原文(含 eventId/eventSeq/flowGuid)")
|
||||
void normalDispatchUsesFrozenEnvelope() throws Exception {
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
FlwStateEvent fact = frozenFact();
|
||||
when(stateEventRepository.findByEventId(fact.getEventId())).thenReturn(Optional.of(fact));
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
event.assignStableIdentity(fact.getEventId(), fact.getEventSeq());
|
||||
event.assignStablePayload(fact.getPayloadJson());
|
||||
|
||||
dispatcher.onFlowEvent(event);
|
||||
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore).persist(captor.capture());
|
||||
assertThat(captor.getValue().getPayloadJson()).isEqualTo(fact.getPayloadJson());
|
||||
JsonNode body = mapper.readTree(captor.getValue().getPayloadJson());
|
||||
assertThat(body.path("eventId").asText()).isEqualTo(fact.getEventId());
|
||||
assertThat(body.path("eventSeq").asInt()).isEqualTo(7);
|
||||
assertThat(body.path("flowGuid").asText()).isEqualTo(FLOW_GUID);
|
||||
// 正常链全建行成功 → 事实记账 dispatched=1
|
||||
verify(stateEventRepository).save(org.mockito.ArgumentMatchers.argThat(
|
||||
f -> Integer.valueOf(1).equals(f.getDispatched())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("恢复链(R2 冻结体):原样复用事实载荷,与正常链消息体逐字节一致")
|
||||
void recoveryReusesFrozenEnvelopeVerbatim() throws Exception {
|
||||
FlwStateEvent fact = frozenFact();
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
|
||||
dispatchFact(fact);
|
||||
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore).persist(captor.capture());
|
||||
assertThat(captor.getValue().getPayloadJson())
|
||||
.as("恢复链必须原样复用冻结体(不可变)").isEqualTo(fact.getPayloadJson());
|
||||
assertThat(fact.getDispatched()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("恢复链(R2 前存量事实行,消息体缺 eventId/eventSeq/flowGuid):按列值幂等补齐后投出")
|
||||
void recoveryRepairsLegacyFactBody() throws Exception {
|
||||
// 构造修复前的存量形态:载荷=老 basePayload(无 eventId/eventSeq/flowGuid)
|
||||
Map<String, Object> legacyBody = new HashMap<>();
|
||||
legacyBody.put("event", "flow.completed");
|
||||
legacyBody.put("schId", SCH);
|
||||
legacyBody.put("instanceId", 900L);
|
||||
legacyBody.put("bizType", "svc_item");
|
||||
legacyBody.put("bizId", "r2-42");
|
||||
legacyBody.put("occurredTime", "2026-10-25 00:00:00");
|
||||
FlwStateEvent fact = frozenFact();
|
||||
fact.setPayloadJson(mapper.writeValueAsString(legacyBody));
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
|
||||
dispatchFact(fact);
|
||||
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore).persist(captor.capture());
|
||||
JsonNode body = mapper.readTree(captor.getValue().getPayloadJson());
|
||||
assertThat(body.path("eventId").asText()).isEqualTo(fact.getEventId());
|
||||
assertThat(body.path("eventSeq").asInt()).isEqualTo(fact.getEventSeq());
|
||||
assertThat(body.path("flowGuid").asText()).isEqualTo(FLOW_GUID);
|
||||
assertThat(fact.getDispatched()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// ==================== 恢复消息实际到达真实 Receiver ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("恢复消息到达真实 FlowCallbackReceiver:事件行落库、Handler 推进、eventId 幂等")
|
||||
void recoveryMessageReachesRealReceiver() throws Exception {
|
||||
FlwStateEvent fact = frozenFact();
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
dispatchFact(fact);
|
||||
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore).persist(captor.capture());
|
||||
String recoveryBody = captor.getValue().getPayloadJson();
|
||||
|
||||
CapturingStore store = new CapturingStore();
|
||||
CapturingHandler handler = new CapturingHandler();
|
||||
FlowCallbackReceiver receiver = newReceiver(store, handler);
|
||||
|
||||
// Outcome 是 starter 包私有枚举,用名字断言(CONSUMED=接收端 200,RETRY=5xx 重试)
|
||||
Object outcome = receiver.receive(recoveryBody.getBytes(
|
||||
java.nio.charset.StandardCharsets.UTF_8));
|
||||
assertThat(String.valueOf(outcome)).isEqualTo("CONSUMED");
|
||||
assertThat(handler.events).as("恢复消息必须被真实接收端消费推进,而非按脏消息丢弃")
|
||||
.hasSize(1);
|
||||
assertThat(handler.events.get(0).getEventId()).isEqualTo(fact.getEventId());
|
||||
assertThat(handler.events.get(0).getBizId()).isEqualTo("r2-42");
|
||||
assertThat(store.savedEventIds).containsExactly(fact.getEventId());
|
||||
|
||||
// 同一恢复体重投:eventId 幂等(已消费,不再推进 Handler)
|
||||
Object dup = receiver.receive(recoveryBody.getBytes(
|
||||
java.nio.charset.StandardCharsets.UTF_8));
|
||||
assertThat(String.valueOf(dup)).isEqualTo("CONSUMED");
|
||||
assertThat(handler.events).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("正常链消息同样到达真实 Receiver;修复前残缺恢复体被丢弃作反例对照")
|
||||
void normalMessageReachesRealReceiver_andBrokenBodyDropped() throws Exception {
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
FlwStateEvent fact = frozenFact();
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
event.assignStableIdentity(fact.getEventId(), fact.getEventSeq());
|
||||
event.assignStablePayload(fact.getPayloadJson());
|
||||
dispatcher.onFlowEvent(event);
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore).persist(captor.capture());
|
||||
String normalBody = captor.getValue().getPayloadJson();
|
||||
|
||||
CapturingStore store = new CapturingStore();
|
||||
CapturingHandler handler = new CapturingHandler();
|
||||
FlowCallbackReceiver receiver = newReceiver(store, handler);
|
||||
Object consumed = receiver.receive(normalBody.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
assertThat(String.valueOf(consumed)).isEqualTo("CONSUMED");
|
||||
assertThat(handler.events).hasSize(1);
|
||||
|
||||
// 反例:R2 修复前的恢复消息体(eventId 只在 HTTP 头/列,消息体缺失)→ 真实接收端
|
||||
// 按"缺必填字段"脏消息 200 丢弃——这正是 D04 关闭的缺陷形态
|
||||
JsonNode broken = mapper.readTree(normalBody);
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) broken).remove("eventId");
|
||||
CapturingStore store2 = new CapturingStore();
|
||||
CapturingHandler handler2 = new CapturingHandler();
|
||||
FlowCallbackReceiver receiver2 = newReceiver(store2, handler2);
|
||||
Object dropped = receiver2.receive(mapper.writeValueAsBytes(broken));
|
||||
assertThat(String.valueOf(dropped)).isEqualTo("CONSUMED");
|
||||
assertThat(handler2.events).as("缺 eventId 的消息体不应推进业务").isEmpty();
|
||||
assertThat(store2.savedEventIds).isEmpty();
|
||||
}
|
||||
|
||||
// ==================== 未可靠建行不记账 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("恢复链任一订阅方建行失败:事实保持 dispatched=0,重试轮补齐后才记账")
|
||||
void recoveryKeepsUndispatchedOnPartialFailure() throws Exception {
|
||||
FlwStateEvent fact = frozenFact();
|
||||
FlwCallbackReg ok = reg(7L, null);
|
||||
FlwCallbackReg bad = reg(8L, null);
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(ok, bad));
|
||||
|
||||
// 第一轮:reg=8 建行抛错(模拟持久化失败)→ 不标记 dispatched
|
||||
when(logStore.persist(any(FlwCallbackLog.class)))
|
||||
.thenReturn(101L)
|
||||
.thenThrow(new RuntimeException("db down"));
|
||||
dispatchFact(fact);
|
||||
assertThat(fact.getDispatched()).as("部分建行失败不得标记已分发").isEqualTo(0);
|
||||
|
||||
// 第二轮(重扫):reg=7 的行已在(exists=true 跳过),reg=8 补建成功 → 记账
|
||||
when(logStore.persist(any(FlwCallbackLog.class))).thenReturn(102L);
|
||||
when(logRepository.existsByEventIdAndRegId(fact.getEventId(), 7L)).thenReturn(true);
|
||||
dispatchFact(fact);
|
||||
assertThat(fact.getDispatched()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("正常链建行失败:不标记事实已分发(恢复扫描稍后补建)")
|
||||
void normalDispatchFailureSkipsDispatchedMarking() throws Exception {
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
FlwStateEvent fact = frozenFact();
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
event.assignStableIdentity(fact.getEventId(), fact.getEventSeq());
|
||||
event.assignStablePayload(fact.getPayloadJson());
|
||||
when(stateEventRepository.findByEventId(fact.getEventId())).thenReturn(Optional.of(fact));
|
||||
when(logStore.persist(any(FlwCallbackLog.class))).thenThrow(new RuntimeException("db down"));
|
||||
// frozenFact() 经真实 recorder 落过一次事实(save 已被调用)——清掉夹具期调用,
|
||||
// 只断言分发失败后不再有"记账 save"
|
||||
org.mockito.Mockito.clearInvocations(stateEventRepository);
|
||||
|
||||
dispatcher.onFlowEvent(event);
|
||||
|
||||
verify(stateEventRepository, never()).save(any(FlwStateEvent.class));
|
||||
assertThat(fact.getDispatched()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("并发撞 uk(event_id, reg_id):DuplicateKeyException=已建行,按幂等成功记账")
|
||||
void duplicateKeyTreatedAsIdempotentSuccess() throws Exception {
|
||||
FlwStateEvent fact = frozenFact();
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null)));
|
||||
when(logStore.persist(any(FlwCallbackLog.class)))
|
||||
.thenThrow(new DuplicateKeyException("uk_flw_log_event_reg"));
|
||||
|
||||
dispatchFact(fact);
|
||||
|
||||
assertThat(fact.getDispatched()).as("uk 兜底=另一路径已建行,视为全部建行").isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("两个订阅方订阅同一事件:各建一行(同 eventId 不同 regId),全部成功才记账")
|
||||
void twoSubscribersEachGetDeliveryRow() throws Exception {
|
||||
FlwStateEvent fact = frozenFact();
|
||||
when(regRepository.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0))
|
||||
.thenReturn(Arrays.asList(reg(7L, null), reg(8L, "flow.completed,flow.rejected")));
|
||||
|
||||
dispatchFact(fact);
|
||||
|
||||
ArgumentCaptor<FlwCallbackLog> captor = ArgumentCaptor.forClass(FlwCallbackLog.class);
|
||||
verify(logStore, times(2)).persist(captor.capture());
|
||||
assertThat(captor.getAllValues().get(0).getRegId()).isEqualTo(7L);
|
||||
assertThat(captor.getAllValues().get(1).getRegId()).isEqualTo(8L);
|
||||
assertThat(captor.getAllValues().get(0).getEventId())
|
||||
.isEqualTo(captor.getAllValues().get(1).getEventId());
|
||||
assertThat(fact.getDispatched()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// ==================== 真实 Receiver 装配夹具 ====================
|
||||
|
||||
private FlowCallbackReceiver newReceiver(CapturingStore store, CapturingHandler handler) {
|
||||
return new FlowCallbackReceiver(store, handler,
|
||||
new TransactionTemplate(NOOP_TX_MANAGER), mapper, new FlowCallbackProperties());
|
||||
}
|
||||
|
||||
private static final PlatformTransactionManager NOOP_TX_MANAGER = new PlatformTransactionManager() {
|
||||
@Override
|
||||
public TransactionStatus getTransaction(TransactionDefinition definition) {
|
||||
return new SimpleTransactionStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commit(TransactionStatus status) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rollback(TransactionStatus status) {
|
||||
}
|
||||
};
|
||||
|
||||
/** 事件留痕/幂等存储内存实现(同事务语义由 noop 事务管理器退化,DupKey 语义保留) */
|
||||
private static class CapturingStore implements FlowCallbackEventStore {
|
||||
final List<String> savedEventIds = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public boolean existsByEventId(String eventId) {
|
||||
return savedEventIds.contains(eventId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(FlowCallbackEvent event, String payloadJson) {
|
||||
if (savedEventIds.contains(event.getEventId())) {
|
||||
throw new DuplicateKeyException("uk_event_id");
|
||||
}
|
||||
savedEventIds.add(event.getEventId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer maxInstanceVersion(String bizType, String bizId, String excludeEventId) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class CapturingHandler implements FlowCallbackHandler {
|
||||
final List<FlowCallbackEvent> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void onEvent(FlowCallbackEvent event) {
|
||||
events.add(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.yunhai.flowcenter.callback;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.yunhai.flowcenter.entity.*;
|
||||
import com.yunhai.flowcenter.repository.FlwInstanceRepository;
|
||||
import com.yunhai.flowcenter.service.FlowSourcePrincipalResolver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Optional;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CallbackSourcePolicyTest {
|
||||
@Test void selfPolicyRejectsForeignSubscriptionsReusedCredentialsAndCorruptEnvelopes() throws Exception {
|
||||
String source="11111111-1111-4111-8111-111111111111";
|
||||
ObjectMapper mapper=new ObjectMapper();FlwInstanceRepository instances=mock(FlwInstanceRepository.class);
|
||||
FlowSourcePrincipalResolver resolver=mock(FlowSourcePrincipalResolver.class);
|
||||
CallbackSourcePolicy policy=new CallbackSourcePolicy(resolver,instances,mapper);
|
||||
FlwInstance instance=new FlwInstance();instance.setId(7L);instance.setSchId(1L);instance.setBizType("svc-hall");instance.setBizId("7");
|
||||
instance.setDefVersion(1);instance.setSourcePrincipalId(source);instance.setApplyRequestToken("r");instance.setApplyRound(2);instance.setApplyPayloadHash("hash");
|
||||
when(instances.findById(7L)).thenReturn(Optional.of(instance));
|
||||
FlwCallbackReg reg=new FlwCallbackReg();reg.setAppKey("100018");reg.setSourcePrincipalId(source);
|
||||
when(resolver.resolve("100018")).thenReturn(new FlowSourcePrincipalResolver.Principal(source,18,"100018","svc-hall"));
|
||||
String json="{\"eventId\":\"e\",\"event\":\"flow.completed\",\"sourcePrincipalId\":\""+source+"\",\"applyRound\":2,\"instanceId\":7,\"schId\":1,\"bizType\":\"svc-hall\",\"bizId\":\"7\",\"data\":{\"defVersion\":1,\"sourcePrincipalId\":\""+source+"\",\"requestId\":\"r\",\"canonicalHash\":\"hash\",\"applyRound\":2}}";
|
||||
assertTrue(policy.permits(reg,7L,json));
|
||||
for(String field:new String[]{"sourcePrincipalId","requestId","canonicalHash","applyRound"}){
|
||||
ObjectNode corrupt=(ObjectNode)mapper.readTree(json);((ObjectNode)corrupt.get("data")).put(field,"wrong");
|
||||
assertFalse(policy.permits(reg,7L,mapper.writeValueAsString(corrupt)),field);
|
||||
}
|
||||
ObjectNode corrupt=(ObjectNode)mapper.readTree(json);corrupt.put("sourcePrincipalId","foreign");assertFalse(policy.permits(reg,7L,corrupt.toString()));
|
||||
FlwCallbackLog delivery=new FlwCallbackLog();delivery.setInstanceId(7L);delivery.setPayloadJson(json);delivery.setEventId("other");delivery.setEvent("flow.completed");delivery.setBizType("svc-hall");delivery.setBizId("7");
|
||||
assertFalse(policy.permits(reg,delivery));delivery.setEventId("e");assertTrue(policy.permits(reg,delivery));
|
||||
reg.setSourcePrincipalId("foreign");assertFalse(policy.matches(reg,instance));reg.setSourcePrincipalId(source);
|
||||
when(resolver.resolve("100018")).thenReturn(new FlowSourcePrincipalResolver.Principal("replacement",18,"100018","svc-hall"));
|
||||
assertFalse(policy.matches(reg,instance));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package com.yunhai.flowcenter.callback;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.engine.FlowEvent;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.entity.FlwStateEvent;
|
||||
import com.yunhai.flowcenter.repository.FlwDefRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwInstanceRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwStateEventRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 状态事件事实(T05;2026-10-25 R2 返修增补)规则单测:
|
||||
*
|
||||
* <ul>
|
||||
* <li>事实与状态<b>同事务</b>落库(同步监听器语义)并为事件赋稳定身份;</li>
|
||||
* <li>eventId 全链复用(事实行=投递行=重试);同事实重复发布不重复落行;</li>
|
||||
* <li>同事务事实写失败=状态事务一并失败(不吞);</li>
|
||||
* <li>URGE 站内信不入事件流;</li>
|
||||
* <li>R2:事实载荷=完整冻结信封(含 eventId/eventSeq/flowGuid),并随身份冻结到事件对象——
|
||||
* 正常分发与崩溃恢复共用同一冻结体。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@DisplayName("状态事件事实 FlwStateEventRecorder(T05/R2)")
|
||||
class FlStateEventRecoveryTest {
|
||||
|
||||
private FlwStateEventRepository eventRepository;
|
||||
private FlwInstanceRepository instanceRepository;
|
||||
private FlwDefRepository defRepository;
|
||||
private FlwStateEventRecorder recorder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
eventRepository = mock(FlwStateEventRepository.class);
|
||||
instanceRepository = mock(FlwInstanceRepository.class);
|
||||
defRepository = mock(FlwDefRepository.class);
|
||||
recorder = new FlwStateEventRecorder(eventRepository, instanceRepository, defRepository,
|
||||
new ObjectMapper());
|
||||
when(eventRepository.save(any())).thenAnswer(c -> {
|
||||
FlwStateEvent e = c.getArgument(0);
|
||||
e.setId(1L);
|
||||
return e;
|
||||
});
|
||||
|
||||
FlwInstance instance = new FlwInstance();
|
||||
instance.setId(900L);
|
||||
instance.setSchId(27L);
|
||||
instance.setDefId(55L);
|
||||
instance.setApplyRound(2);
|
||||
instance.setBizType("svc-hall");
|
||||
instance.setBizId("42");
|
||||
when(instanceRepository.findById(900L)).thenReturn(Optional.of(instance));
|
||||
when(instanceRepository.nextEventSeqForUpdate(900L)).thenReturn(5);
|
||||
when(instanceRepository.setEventSeqCounter(Mockito.eq(900L), Mockito.anyInt())).thenReturn(1);
|
||||
|
||||
FlwDef def = new FlwDef();
|
||||
def.setId(55L);
|
||||
def.setFlowGuid("fg-r2-envelope");
|
||||
when(defRepository.findById(55L)).thenReturn(Optional.of(def));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("同步监听:事实落库并赋稳定身份(eventId+实例内 seq=max+1)")
|
||||
void recordAssignsStableIdentity() {
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.SUBMITTED, 900L);
|
||||
|
||||
recorder.record(event);
|
||||
|
||||
Mockito.verify(eventRepository).save(any(FlwStateEvent.class));
|
||||
assertThat(event.getStableEventId()).isNotBlank();
|
||||
assertThat(event.getStableEventSeq()).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("同事件对象重复发布:不重复落事实、身份不变")
|
||||
void duplicatePublishKeepsIdentity() {
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
recorder.record(event);
|
||||
String first = event.getStableEventId();
|
||||
|
||||
recorder.record(event);
|
||||
|
||||
Mockito.verify(eventRepository, Mockito.times(1)).save(any(FlwStateEvent.class));
|
||||
assertThat(event.getStableEventId()).isEqualTo(first);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("URGE 站内信:不入事件流(既有口径不变)")
|
||||
void urgeSkipped() {
|
||||
recorder.record(FlowEvent.of(FlowEvent.Type.URGE, 900L));
|
||||
Mockito.verify(eventRepository, never()).save(any(FlwStateEvent.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("事实载荷快照含轮次身份(旧事件不被 AFTER_COMMIT 重读贴新轮标签)")
|
||||
void payloadCarriesRoundIdentity() throws Exception {
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.REJECTED, 900L);
|
||||
event.captureRoundIdentity(2, "tok-1");
|
||||
recorder.record(event);
|
||||
Mockito.verify(eventRepository).save(Mockito.argThat(f -> {
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode payload =
|
||||
new ObjectMapper().readTree(f.getPayloadJson());
|
||||
return payload.path("applyRound").asInt() == 2
|
||||
&& "tok-1".equals(payload.path("data").path("requestToken").asText());
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("R2:事实载荷=完整冻结信封——eventId/eventSeq/flowGuid/接收端必填四件套全部在体")
|
||||
void payloadIsFullFrozenEnvelope() throws Exception {
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.SUBMITTED, 900L);
|
||||
recorder.record(event);
|
||||
|
||||
ArgumentCaptor<FlwStateEvent> captor = ArgumentCaptor.forClass(FlwStateEvent.class);
|
||||
verify(eventRepository).save(captor.capture());
|
||||
com.fasterxml.jackson.databind.JsonNode payload =
|
||||
new ObjectMapper().readTree(captor.getValue().getPayloadJson());
|
||||
// 接收端 FlowCallbackReceiver 必填:eventId/event/bizType/bizId(缺一按脏消息 200 丢弃)
|
||||
assertThat(payload.path("eventId").asText()).isEqualTo(event.getStableEventId());
|
||||
assertThat(payload.path("event").asText()).isEqualTo("flow.submitted");
|
||||
assertThat(payload.path("bizType").asText()).isEqualTo("svc-hall");
|
||||
assertThat(payload.path("bizId").asText()).isEqualTo("42");
|
||||
// R2 新冻结字段:稳定序号 + flowGuid(原实现只在 HTTP 头/列里,消息体缺失)
|
||||
assertThat(payload.path("eventSeq").asInt()).isEqualTo(5);
|
||||
assertThat(payload.path("flowGuid").asText()).isEqualTo("fg-r2-envelope");
|
||||
// 既有信封字段不回退
|
||||
assertThat(payload.has("instanceId")).isTrue();
|
||||
assertThat(payload.has("instanceVersion")).isTrue();
|
||||
assertThat(payload.has("occurredTime")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("R2:冻结信封随身份一并赋给事件对象——分发器正常链直接复用冻结体(与恢复链同构)")
|
||||
void frozenEnvelopeAssignedToEvent() throws Exception {
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.COMPLETED, 900L);
|
||||
recorder.record(event);
|
||||
|
||||
assertThat(event.getStablePayloadJson()).isNotBlank();
|
||||
com.fasterxml.jackson.databind.JsonNode payload =
|
||||
new ObjectMapper().readTree(event.getStablePayloadJson());
|
||||
assertThat(payload.path("eventId").asText()).isEqualTo(event.getStableEventId());
|
||||
assertThat(payload.path("flowGuid").asText()).isEqualTo("fg-r2-envelope");
|
||||
|
||||
// 重复发布不换冻结体(幂等)
|
||||
String first = event.getStablePayloadJson();
|
||||
recorder.record(event);
|
||||
assertThat(event.getStablePayloadJson()).isEqualTo(first);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("R2:定义已删(def 缺席)——信封不带 flowGuid,不炸记录器(该场合分发器同样不投递)")
|
||||
void missingDefStillRecordsWithoutFlowGuid() throws Exception {
|
||||
FlwInstance instance = new FlwInstance();
|
||||
instance.setId(901L);
|
||||
instance.setSchId(27L);
|
||||
instance.setDefId(404L);
|
||||
instance.setBizType("svc-hall");
|
||||
instance.setBizId("43");
|
||||
when(instanceRepository.findById(901L)).thenReturn(Optional.of(instance));
|
||||
when(defRepository.findById(404L)).thenReturn(Optional.empty());
|
||||
when(instanceRepository.nextEventSeqForUpdate(901L)).thenReturn(1);
|
||||
when(instanceRepository.setEventSeqCounter(Mockito.eq(901L), Mockito.anyInt())).thenReturn(1);
|
||||
|
||||
FlowEvent event = FlowEvent.of(FlowEvent.Type.SUBMITTED, 901L);
|
||||
recorder.record(event);
|
||||
|
||||
ArgumentCaptor<FlwStateEvent> captor = ArgumentCaptor.forClass(FlwStateEvent.class);
|
||||
verify(eventRepository).save(captor.capture());
|
||||
com.fasterxml.jackson.databind.JsonNode payload =
|
||||
new ObjectMapper().readTree(captor.getValue().getPayloadJson());
|
||||
assertThat(payload.has("flowGuid")).isFalse();
|
||||
assertThat(payload.path("eventId").asText()).isEqualTo(event.getStableEventId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.yunhai.flowcenter.engine;
|
||||
|
||||
import com.yunhai.flowcenter.entity.FlwDeptMember;
|
||||
import com.yunhai.flowcenter.service.FlowDeptAdminService;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.base.OpenApiUserClient;
|
||||
import com.yunhai.platform.utils.exception.ErrorCode;
|
||||
import com.yunhai.platform.utils.model.BoaGroup;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** D11 人员资格终审:存在/启用/校域三查 + 部门成员逐人核验 + NOTIFY 宽容口径。 */
|
||||
@DisplayName("D11 人员资格终审(AssigneeResolver)")
|
||||
class AssigneeResolverEligibilityTest {
|
||||
|
||||
private static final long SCH = 1L;
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 全部合法:逐人返回姓名快照")
|
||||
void fixedUsersAllEligiblePasses() {
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1, 102, 1, 1), mock(FlowDeptAdminService.class));
|
||||
List<AssigneeRef> refs = resolver.resolve(SCH, usersNode(101, 102));
|
||||
assertThat(refs).extracting(AssigneeRef::getUserId).containsExactly(101, 102);
|
||||
assertThat(refs).extracting(AssigneeRef::getUserName).containsExactly("用户101", "用户102");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含已停用人员:整体拒绝,不返回部分合法结果")
|
||||
void fixedUsersAnyDisabledRejectsWholeConfig() {
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1, 9001, 0, 1), mock(FlowDeptAdminService.class));
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, usersNode(101, 9001)))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("禁用")
|
||||
.hasMessageContaining("9001");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含外校人员:整体拒绝")
|
||||
void fixedUsersAnyCrossSchoolRejectsWholeConfig() {
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1, 9002, 1, 2), mock(FlowDeptAdminService.class));
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, usersNode(101, 9002)))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不属于该学校");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含不存在人员:整体拒绝")
|
||||
void fixedUsersAnyMissingRejectsWholeConfig() {
|
||||
OpenApiUserClient client = userClient(101, 1, 1);
|
||||
when(client.getUserById("9999")).thenReturn(null);
|
||||
AssigneeResolver resolver = resolver(client, mock(FlowDeptAdminService.class));
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, usersNode(101, 9999)))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("启动前固定人预检:扫描全部审批节点,后续节点非法也整体拒绝")
|
||||
void fixedPreflightScansEveryApprovalNode() {
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1, 9002, 1, 2), mock(FlowDeptAdminService.class));
|
||||
FlowDefModel model = new FlowDefModel();
|
||||
FlowDefModel.Node first = usersNode(101);
|
||||
first.id = "n1";
|
||||
FlowDefModel.Node second = usersNode(9002);
|
||||
second.id = "n2";
|
||||
model.nodes = Arrays.asList(first, second);
|
||||
model.edges = new ArrayList<>();
|
||||
assertThatThrownBy(() -> resolver.requireEligibleFixedAssignees(SCH, model))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("n2")
|
||||
.hasMessageContaining("不属于该学校");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("部门成员:合法保留、停用/外校剔除(科室启用不等于成员合格)")
|
||||
void deptMembersAreCheckedOneByOne() {
|
||||
FlowDeptAdminService dept = mock(FlowDeptAdminService.class);
|
||||
when(dept.resolveEnabled(SCH, "d1")).thenReturn(Arrays.asList(
|
||||
member(101, "甲"), member(9001, "停用"), member(9002, "外校")));
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1, 9001, 0, 1, 9002, 1, 2), dept);
|
||||
|
||||
List<AssigneeRef> refs = resolver.resolve(SCH, deptNode("d1"));
|
||||
assertThat(refs).extracting(AssigneeRef::getUserId).containsExactly(101);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("部门成员全部不合格:明确拒绝,不产生无人可办的任务")
|
||||
void deptAllIneligibleRejects() {
|
||||
FlowDeptAdminService dept = mock(FlowDeptAdminService.class);
|
||||
when(dept.resolveEnabled(SCH, "d1")).thenReturn(Collections.singletonList(member(9001, "停用")));
|
||||
AssigneeResolver resolver = resolver(userClient(9001, 0, 1), dept);
|
||||
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, deptNode("d1")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("均不具备办理资格");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("部门解析为空:既有“无可用办理人”错误")
|
||||
void deptEmptyRejects() {
|
||||
FlowDeptAdminService dept = mock(FlowDeptAdminService.class);
|
||||
when(dept.resolveEnabled(SCH, "d1")).thenReturn(Collections.emptyList());
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, 1), dept);
|
||||
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, deptNode("d1")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("无可用办理人");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("UserBase 不可达:不可判定按失败传播,不降级成“成员不合格”")
|
||||
void deptUserBaseUnavailablePropagates() {
|
||||
FlowDeptAdminService dept = mock(FlowDeptAdminService.class);
|
||||
when(dept.resolveEnabled(SCH, "d1")).thenReturn(Collections.singletonList(member(101, "甲")));
|
||||
OpenApiUserClient client = mock(OpenApiUserClient.class);
|
||||
when(client.getUserById(anyString())).thenThrow(new IllegalStateException("down"));
|
||||
AssigneeResolver resolver = new AssigneeResolver(dept, client);
|
||||
|
||||
assertThatThrownBy(() -> resolver.resolve(SCH, deptNode("d1")))
|
||||
.isInstanceOf(BizException.class)
|
||||
.satisfies(e -> assertThat(((BizException) e).getErrorCode())
|
||||
.isEqualTo(ErrorCode.INTERNAL_SERVER_ERROR));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("NOTIFY receivers 保持宽容:停用/外校/不存在均不阻塞,姓名可空")
|
||||
void notifyReceiversStayTolerant() {
|
||||
OpenApiUserClient client = userClient(9001, 0, 1, 9002, 1, 2);
|
||||
when(client.getUserById("9999")).thenReturn(null);
|
||||
AssigneeResolver resolver = new AssigneeResolver(mock(FlowDeptAdminService.class), client);
|
||||
|
||||
FlowDefModel.Node notify = new FlowDefModel.Node();
|
||||
notify.id = "cc1";
|
||||
notify.type = FlowDefModel.TYPE_NOTIFY;
|
||||
notify.receivers = new FlowDefModel.Assignee();
|
||||
notify.receivers.type = FlowDefModel.ASSIGNEE_USERS;
|
||||
notify.receivers.userIds = Arrays.asList(9001, 9002, 9999);
|
||||
|
||||
List<AssigneeRef> refs = resolver.resolveTolerant(SCH, notify);
|
||||
assertThat(refs).extracting(AssigneeRef::getUserId).containsExactly(9001, 9002, 9999);
|
||||
assertThat(refs.get(2).getUserName()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("人员无学校归属:fail-closed 拒绝")
|
||||
void noSchoolRejected() {
|
||||
AssigneeResolver resolver = resolver(userClient(101, 1, null), mock(FlowDeptAdminService.class));
|
||||
assertThatThrownBy(() -> resolver.requireEligibleAssignee(SCH, 101))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不属于该学校");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("人员不存在:拒绝")
|
||||
void missingUserRejected() {
|
||||
OpenApiUserClient client = mock(OpenApiUserClient.class);
|
||||
when(client.getUserById(anyString())).thenReturn(null);
|
||||
AssigneeResolver resolver = new AssigneeResolver(mock(FlowDeptAdminService.class), client);
|
||||
assertThatThrownBy(() -> resolver.requireEligibleAssignee(SCH, 9999))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不存在");
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private static AssigneeResolver resolver(OpenApiUserClient client, FlowDeptAdminService dept) {
|
||||
return new AssigneeResolver(dept, client);
|
||||
}
|
||||
|
||||
/** userClient(101,1,1, 9001,0,1) = 三元组(userId,status,schoolId),schoolId=null 表示无学校。 */
|
||||
private static OpenApiUserClient userClient(Object... triples) {
|
||||
OpenApiUserClient client = mock(OpenApiUserClient.class);
|
||||
when(client.getUserById(anyString())).thenAnswer(inv -> {
|
||||
int id = Integer.parseInt(inv.getArgument(0));
|
||||
for (int i = 0; i < triples.length; i += 3) {
|
||||
if ((Integer) triples[i] == id) {
|
||||
BoaUser user = new BoaUser(id, "user" + id, "用户" + id);
|
||||
user.setStatus((Integer) triples[i + 1]);
|
||||
Integer school = (Integer) triples[i + 2];
|
||||
user.setSchool(school == null ? null : new BoaGroup(school, "学校" + school));
|
||||
return user;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
return client;
|
||||
}
|
||||
|
||||
private static FlowDefModel.Node usersNode(Integer... userIds) {
|
||||
FlowDefModel.Node node = new FlowDefModel.Node();
|
||||
node.id = "n1";
|
||||
node.type = FlowDefModel.TYPE_APPROVAL;
|
||||
node.assignee = new FlowDefModel.Assignee();
|
||||
node.assignee.type = FlowDefModel.ASSIGNEE_USERS;
|
||||
node.assignee.userIds = Arrays.asList(userIds);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static FlowDefModel.Node deptNode(String deptKey) {
|
||||
FlowDefModel.Node node = new FlowDefModel.Node();
|
||||
node.id = "n1";
|
||||
node.type = FlowDefModel.TYPE_APPROVAL;
|
||||
node.assignee = new FlowDefModel.Assignee();
|
||||
node.assignee.type = FlowDefModel.ASSIGNEE_DEPT_KEY;
|
||||
node.assignee.deptKey = deptKey;
|
||||
return node;
|
||||
}
|
||||
|
||||
private static FlwDeptMember member(Integer userId, String userName) {
|
||||
FlwDeptMember member = new FlwDeptMember();
|
||||
member.setUserId(userId);
|
||||
member.setUserName(userName);
|
||||
member.setStatus(0);
|
||||
return member;
|
||||
}
|
||||
}
|
||||
@@ -432,12 +432,58 @@ class DefValidatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void expressionMode_formVariables_passPublishTime() {
|
||||
// 表单变量(子应用运行时传)发布期不拦:缺失按 null 注入求值
|
||||
void declaredBusinessVariablesRequiredForContractExpressions() {
|
||||
FlowDefModel model = parse(expressionDef("EXPRESSION", "amount > 1000", "amount <= 1000"));
|
||||
model.variables = new java.util.ArrayList<>();
|
||||
assertTrue(assertThrows(BizException.class, () -> DefValidator.validate(model,
|
||||
new HashSet<>(Collections.singletonList("ybb")), null)).getMessage().contains("amount"));
|
||||
FlowDefModel.Variable v = new FlowDefModel.Variable(); v.key="amount"; v.type="number";
|
||||
model.variables.add(v);
|
||||
DefValidator.validate(model, new HashSet<>(Collections.singletonList("ybb")), null);
|
||||
model.variables.add(v);
|
||||
assertTrue(assertThrows(BizException.class, () -> DefValidator.validate(model,
|
||||
new HashSet<>(Collections.singletonList("ybb")), null)).getMessage().contains("重复"));
|
||||
model.variables.remove(1); v.type="any";
|
||||
assertTrue(assertThrows(BizException.class, () -> DefValidator.validate(model,
|
||||
new HashSet<>(Collections.singletonList("ybb")), null)).getMessage().contains("类型不支持"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void historicalExpressionsWithoutContractRemainCompatible() {
|
||||
DefValidator.validate(parse(expressionDef("EXPRESSION", "form.level == 'A'", "true")),
|
||||
new HashSet<>(Collections.singletonList("ybb")), null);
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest
|
||||
@org.junit.jupiter.params.provider.ValueSource(strings={
|
||||
"[{\"key\":\"schId\",\"type\":\"number\"}]",
|
||||
"[{\"key\":\"bad key\",\"type\":\"string\"}]",
|
||||
"[{\"key\":\"amount\",\"type\":\"number\",\"enum\":[\"1\"]}]",
|
||||
"[{\"key\":\"amount\",\"type\":\"string\",\"enum\":[]}]",
|
||||
"[{\"key\":\"amount\",\"type\":\"string\",\"enum\":[\"x\",\"x\"]}]",
|
||||
"[null]"
|
||||
})
|
||||
void invalidDeclarationsRejected(String declarations) throws Exception {
|
||||
FlowDefModel model = parse(expressionDef("EXPRESSION", "true", "false"));
|
||||
model.variables = new ObjectMapper().readValue("{\"variables\":"+declarations+"}",FlowDefModel.class).variables;
|
||||
assertThrows(BizException.class, () -> DefValidator.validate(model, Collections.singleton("ybb"), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directExpressionLiteralsUseTheSameValueRulesAsApply() {
|
||||
FlowDefModel model = parse(expressionDef("EXPRESSION", "true", "false"));
|
||||
FlowDefModel.Variable v = new FlowDefModel.Variable();v.key="grade";v.type="string";v.enumValues=java.util.Arrays.asList("g1","g2");
|
||||
model.variables=Collections.singletonList(v);
|
||||
for (String invalid : java.util.Arrays.asList("grade == 'g9'", "'g9' == grade", "grade != 'g9'", "grade > 3")) {
|
||||
model.edges.get(1).condition=invalid;
|
||||
assertThrows(BizException.class, () -> DefValidator.validate(model, Collections.singleton("ybb"), null));
|
||||
}
|
||||
model.edges.get(1).condition="string.contains(grade, 'grade > 3')";
|
||||
DefValidator.validate(model, Collections.singleton("ybb"), null);
|
||||
model.edges.get(1).condition="grade > 'g1'"; // 保持既有同类型比较能力,不新增运算符策略。
|
||||
DefValidator.validate(model, Collections.singleton("ybb"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expressionMode_skipsRouterKeyCheck() {
|
||||
// EXPRESSION 模式不配 routerKey(enabledRouterKeys=null 也不查注册表)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.yunhai.flowcenter.engine;
|
||||
|
||||
import com.yunhai.flowcenter.entity.*;
|
||||
import com.yunhai.flowcenter.repository.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.orm.ObjectOptimisticLockingFailureException;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** The six original recovery guarantees remain asserted against the real settlement service. */
|
||||
class FlAdvanceIntentRecoveryTest {
|
||||
FlowAdvanceService advanceService;
|
||||
FlwAdvanceIntentRepository intents;
|
||||
FlwInstanceRepository instances;
|
||||
FlwTaskRepository tasks;
|
||||
FlowEngine engine;
|
||||
FlowNodeAdvanceListener listener;
|
||||
FlwAdvanceIntent head;
|
||||
FlwInstance instance;
|
||||
FlwTask trigger;
|
||||
|
||||
@BeforeEach void setup() {
|
||||
intents=mock(FlwAdvanceIntentRepository.class);instances=mock(FlwInstanceRepository.class);
|
||||
tasks=mock(FlwTaskRepository.class);engine=mock(FlowEngine.class);
|
||||
FlwDefRepository definitions=mock(FlwDefRepository.class);
|
||||
advanceService=new FlowAdvanceService(instances,definitions,tasks,engine,intents);
|
||||
ReflectionTestUtils.setField(advanceService,"entityManager",mock(javax.persistence.EntityManager.class));
|
||||
listener=new FlowNodeAdvanceListener(advanceService,intents);
|
||||
head=new FlwAdvanceIntent();head.setId(1L);head.setInstanceId(900L);head.setNodeId("n1");
|
||||
head.setActivationTaskId(33L);head.addTask(33L);head.addTask(34L);head.addHandledTask(33L);
|
||||
head.setTriggerTaskId(33L);head.setActivationDefId(7L);head.setActivationDefVersion(1);
|
||||
instance=new FlwInstance();instance.setId(900L);instance.setStatus(10);instance.setCurrentNodes("n1");instance.setDefId(7L);instance.setDefVersion(1);
|
||||
trigger=new FlwTask();trigger.setId(33L);trigger.setInstanceId(900L);trigger.setNodeId("n1");
|
||||
trigger.setStatus(1);trigger.setEdgeName("agree");trigger.setAssigneeId(201);trigger.setAssigneeName("A");
|
||||
when(intents.save(any())).thenAnswer(inv->inv.getArgument(0));
|
||||
when(intents.findByIdForUpdate(1L)).thenReturn(Optional.of(head));
|
||||
when(intents.findByInstanceIdAndNodeIdOrderByIdDesc(900L,"n1")).thenReturn(Collections.singletonList(head));
|
||||
when(intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(900L,"n1")).thenReturn(Optional.of(head));
|
||||
when(intents.findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(anyString(),any())).thenReturn(Collections.singletonList(head));
|
||||
when(instances.findById(900L)).thenReturn(Optional.of(instance));
|
||||
when(definitions.findById(7L)).thenReturn(Optional.of(new FlwDef()));
|
||||
when(tasks.findById(33L)).thenReturn(Optional.of(trigger));
|
||||
when(tasks.findByInstanceIdAndStatus(900L,0)).thenReturn(Collections.emptyList());
|
||||
doAnswer(inv->{instance.setCurrentNodes("n2");return null;}).when(engine).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
|
||||
@Test void persistIntentCapturesAdvanceWork() {
|
||||
head.setHandledTaskIds(null);head.setTriggerTaskId(null);
|
||||
listener.persistIntent(event(33L,"agree",201));
|
||||
assertThat(head.getEdgeName()).isEqualTo("agree");assertThat(head.getAssigneeId()).isEqualTo(201);
|
||||
assertThat(head.getInstanceId()).isEqualTo(900L);assertThat(head.getNodeId()).isEqualTo("n1");
|
||||
assertThat(head.getTriggerTaskId()).isEqualTo(33L);assertThat(head.handledTask(33L)).isTrue();
|
||||
verify(intents).save(head);
|
||||
}
|
||||
|
||||
@Test void duplicateIntentSuppressed() {
|
||||
head.setEdgeName("latest");listener.persistIntent(event(33L,"old duplicate",202));
|
||||
assertThat(head.getEdgeName()).isEqualTo("latest");
|
||||
verify(intents,never()).save(any());
|
||||
}
|
||||
|
||||
@Test void successfulAdvanceMarksIntentsDone() {
|
||||
listener.onTaskHandled(event(33L,"agree",201));
|
||||
assertThat(head.getStatus()).isEqualTo("DONE");
|
||||
verify(instances).saveAndFlush(instance);
|
||||
}
|
||||
|
||||
@Test void exhaustedRetriesDeferInsteadOfDropping() {
|
||||
conflict();listener.onTaskHandled(event(33L,"agree",201));
|
||||
assertThat(head.getStatus()).isEqualTo("PENDING");assertThat(head.getAttempts()).isEqualTo(1);
|
||||
assertThat(head.getNextRetryAt()).isAfter(LocalDateTime.now());assertThat(head.getLastError()).contains("sweep");
|
||||
verify(engine,times(3)).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
|
||||
@Test void sweepExecutesAndExhausts() {
|
||||
conflict();for(int i=0;i<5;i++)listener.sweepIntents();
|
||||
assertThat(head.getStatus()).isEqualTo("PENDING");assertThat(head.getAttempts()).isEqualTo(5);
|
||||
listener.sweepIntents();assertThat(head.getStatus()).isEqualTo("EXHAUSTED");assertThat(head.getAttempts()).isEqualTo(6);
|
||||
verify(engine,times(6)).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
|
||||
@Test void sweepRecoversPendingIntent() {
|
||||
listener.sweepIntents();assertThat(head.getStatus()).isEqualTo("DONE");assertThat(head.getLastError()).isNull();
|
||||
}
|
||||
|
||||
@Test void w_lastHandlerWinsEvenWhenItsTaskIdIsSmaller() {
|
||||
head.setHandledTaskIds(null);
|
||||
listener.persistIntent(event(34L,"first",202));listener.persistIntent(event(33L,"last",201));
|
||||
trigger.setEdgeName("last");listener.sweepIntents();
|
||||
assertThat(head.getActivationTaskId()).isEqualTo(33L);assertThat(head.getTriggerTaskId()).isEqualTo(33L);
|
||||
verify(engine).continueAdvance(eq(instance),any(),eq("n1"),eq("last"),argThat(op->op.getUserId()==201));
|
||||
}
|
||||
|
||||
@Test void v_oldActivationCannotConsumeOrAdvanceItsSuccessor() {
|
||||
FlwAdvanceIntent next=new FlwAdvanceIntent();next.setId(2L);next.setTriggerTaskId(99L);
|
||||
when(intents.findByIdForUpdate(2L)).thenReturn(Optional.of(next));
|
||||
when(intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(900L,"n1")).thenReturn(Optional.of(next));
|
||||
listener.sweepIntents();assertThat(head.getStatus()).isEqualTo("DONE");assertThat(head.getLastError()).contains("STALE_ACTIVATION");
|
||||
assertThat(next.getStatus()).isEqualTo("PENDING");assertThat(instance.getCurrentNodes()).isEqualTo("n1");
|
||||
verify(engine,never()).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
|
||||
@Test void staleRevisionCannotAdvanceDeferOrOverwriteRefreshedIntent() {
|
||||
head.setRevision(2L);head.setEdgeName("fresh");
|
||||
assertThat(advanceService.tryAdvance(1L,1L)).isFalse();advanceService.defer(1L,1L,"old failure");
|
||||
assertThat(head.getEdgeName()).isEqualTo("fresh");assertThat(head.getStatus()).isEqualTo("PENDING");
|
||||
assertThat(head.getAttempts()).isZero();verify(intents,never()).save(any());
|
||||
}
|
||||
|
||||
@Test void unanchoredLegacyWorkIsHeldForAuditedBackfillNotSilentlyConsumed() {
|
||||
head.setActivationTaskId(null);
|
||||
when(intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(900L,"n1")).thenReturn(Optional.empty());
|
||||
listener.sweepIntents();assertThat(head.getStatus()).isEqualTo("EXHAUSTED");assertThat(head.getLastError()).contains("UNANCHORED");
|
||||
assertThat(instance.getCurrentNodes()).isEqualTo("n1");verify(engine,never()).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
|
||||
@Test void missingMembershipRollsBackHandlingInsteadOfGuessingANewGeneration() {
|
||||
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class,()->listener.persistIntent(event(99L,"x",201)));
|
||||
verify(intents,never()).save(any());
|
||||
}
|
||||
|
||||
private void conflict() {
|
||||
doThrow(new ObjectOptimisticLockingFailureException(FlwAdvanceIntent.class,1L)).when(engine).continueAdvance(any(),any(),anyString(),any(),any());
|
||||
}
|
||||
private FlowEvent event(Long task,String edge,Integer user) {
|
||||
Map<String,Object> data=new HashMap<>();data.put("nodeId","n1");data.put("edgeName",edge);data.put("assigneeId",user);data.put("assigneeName","A");
|
||||
return FlowEvent.of(FlowEvent.Type.TASK_HANDLED,900L,task,data);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.yunhai.flowcenter.entity.FlwBranch;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.entity.FlwTask;
|
||||
import com.yunhai.flowcenter.entity.FlwAdvanceIntent;
|
||||
import com.yunhai.flowcenter.enums.FlwEnums;
|
||||
import com.yunhai.flowcenter.service.FlowInstanceService;
|
||||
import com.yunhai.flowcenter.service.FlowTaskService;
|
||||
@@ -37,6 +38,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@ActiveProfiles("test")
|
||||
class FlowEngineIT extends FlowTestSupport {
|
||||
|
||||
@org.springframework.boot.test.mock.mockito.SpyBean
|
||||
private FlowNodeAdvanceListener advanceListener;
|
||||
@org.springframework.boot.test.mock.mockito.SpyBean
|
||||
private com.yunhai.flowcenter.repository.FlwAdvanceIntentRepository intents;
|
||||
@org.springframework.boot.test.mock.mockito.MockBean
|
||||
private org.springframework.scheduling.TaskScheduler controlledScheduler;
|
||||
@Autowired private org.springframework.jdbc.core.JdbcTemplate d09Jdbc;
|
||||
@org.springframework.boot.test.mock.mockito.SpyBean private FlowAdvanceService advanceService;
|
||||
@org.springframework.boot.test.mock.mockito.SpyBean private com.yunhai.flowcenter.repository.FlwTaskRepository controlledTasks;
|
||||
@org.springframework.boot.test.mock.mockito.SpyBean private FlowEngine controlledEngine;
|
||||
|
||||
@Autowired
|
||||
private FlowInstanceService instanceService;
|
||||
@Autowired
|
||||
@@ -92,6 +104,9 @@ class FlowEngineIT extends FlowTestSupport {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
assertTrue(d09Jdbc.queryForObject("SELECT @@version", String.class).startsWith("8."));
|
||||
assertEquals(13429, d09Jdbc.queryForObject("SELECT @@port", Integer.class));
|
||||
assertEquals("fl_d09_20261026", d09Jdbc.queryForObject("SELECT DATABASE()", String.class));
|
||||
cleanDb();
|
||||
StubJudge.reset("甲线");
|
||||
}
|
||||
@@ -112,6 +127,362 @@ class FlowEngineIT extends FlowTestSupport {
|
||||
return instanceService.apply(cmd);
|
||||
}
|
||||
|
||||
@Test
|
||||
void d09W_lastHandlerWithLowerTaskIdWinsAfterRecovery() {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
mapDept("d09a",201,"First");mapDept("d09a",202,"Last");mapDept("d09b",301,"Next");
|
||||
FlwDef def=saveAndPublishDef("d09w","D09 W",multiOutletDef("d09a","d09b"));
|
||||
Long id=apply(def.getFlowGuid(),"d09-w",201,"Applicant").getInstanceId();
|
||||
List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
tasks.sort(java.util.Comparator.comparing(FlwTask::getId));
|
||||
FlwTask first=tasks.get(1),last=tasks.get(0); // Completion order deliberately reverses ID order.
|
||||
taskService.handle(SCH,first.getId(),true,"first",first.getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,last.getId(),true,"last",last.getAssigneeId(),"转乙科");
|
||||
d09Jdbc.update("UPDATE flw_advance_intent SET next_retry_at=DATE_SUB(NOW(),INTERVAL 1 SECOND) WHERE instance_id=? AND status='PENDING'",id);
|
||||
advanceListener.sweepIntents();
|
||||
assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
com.yunhai.flowcenter.entity.FlwStateEvent created=stateEventRepository.findAll().stream()
|
||||
.filter(e->id.equals(e.getInstanceId()) && "flow.task.created".equals(e.getEventType()))
|
||||
.max(java.util.Comparator.comparing(com.yunhai.flowcenter.entity.FlwStateEvent::getId)).get();
|
||||
assertTrue(created.getPayloadJson().contains("\"operatorUserId\":"+last.getAssigneeId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void d09V_claimedOldIntentCannotAdvanceRestartedDefinitionAndNewIntentTakesOver() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
mapDept("d09a",201,"A");mapDept("d09a",202,"B");mapDept("d09b",301,"Next");
|
||||
FlwDef def=saveAndPublishDef("d09v","D09 V",multiOutletDef("d09a","d09b"));
|
||||
Long id=apply(def.getFlowGuid(),"d09-v",201,"Applicant").getInstanceId();
|
||||
List<FlwTask> old=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,old.get(0).getId(),true,"old",old.get(0).getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,old.get(1).getId(),false,"reject",old.get(1).getAssigneeId(),null);
|
||||
d09Jdbc.update("UPDATE flw_advance_intent SET next_retry_at=DATE_SUB(NOW(),INTERVAL 1 SECOND) WHERE instance_id=? AND status='PENDING'",id);
|
||||
FlwDef next=saveAndPublishDef("d09v2","D09 V2",multiOutletDef("d09a","d09b"));
|
||||
next.setFlowGuid(def.getFlowGuid());next.setVersion(2);defRepository.saveAndFlush(next);
|
||||
assertEquals(id,apply(def.getFlowGuid(),"d09-v",201,"Applicant").getInstanceId());
|
||||
java.util.concurrent.CountDownLatch claimed=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{
|
||||
Object rows=d09DueFromDatabase();claimed.countDown();
|
||||
assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));return rows;
|
||||
}).when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(
|
||||
org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
java.util.concurrent.ExecutorService pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
java.util.concurrent.Future<?> stale=pool.submit(()->advanceListener.sweepIntents());
|
||||
assertTrue(claimed.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
List<FlwTask> current=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
for(FlwTask task:current)taskService.handle(SCH,task.getId(),true,"new",task.getAssigneeId(),"转乙科");
|
||||
FlwInstance before=instanceRepository.findById(id).get();
|
||||
release.countDown();stale.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwInstance after=instanceRepository.findById(id).get();
|
||||
assertEquals(before.getVersion(),after.getVersion());assertEquals(10,after.getStatus());
|
||||
assertEquals("n1",after.getCurrentNodes());assertEquals(2,after.getDefVersion());
|
||||
assertEquals(0,taskRepository.findByInstanceIdAndStatus(id,0).size());
|
||||
org.mockito.Mockito.doAnswer(inv->d09DueFromDatabase()).when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(
|
||||
org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
advanceListener.sweepIntents();
|
||||
assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
} finally {release.countDown();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
private List<com.yunhai.flowcenter.entity.FlwAdvanceIntent> d09DueFromDatabase() {
|
||||
return intents.findAll().stream().filter(i->"PENDING".equals(i.getStatus()))
|
||||
.filter(i->i.getNextRetryAt()==null || !i.getNextRetryAt().isAfter(java.time.LocalDateTime.now()))
|
||||
.limit(50).collect(java.util.stream.Collectors.toList());
|
||||
}
|
||||
|
||||
private Long d09Multi(String biz) {
|
||||
mapDept("d09a",201,"A");mapDept("d09a",202,"B");mapDept("d09b",301,"Next");
|
||||
FlwDef def=saveAndPublishDef(biz,biz,multiOutletDef("d09a","d09b"));
|
||||
return apply(def.getFlowGuid(),biz,201,"Applicant").getInstanceId();
|
||||
}
|
||||
|
||||
private FlwAdvanceIntent d09Head(Long id) {
|
||||
return intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(id,"n1").get();
|
||||
}
|
||||
|
||||
@Test void d09W_retryExhaustionRefreshesLastEdgeAndOperatorBeforeSweep() {
|
||||
Long id=d09Multi("d09-retry");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
org.mockito.Mockito.doThrow(new org.springframework.orm.ObjectOptimisticLockingFailureException(FlwInstance.class,id))
|
||||
.when(advanceService).tryAdvance(org.mockito.ArgumentMatchers.anyLong(),org.mockito.ArgumentMatchers.anyLong());
|
||||
FlwTask first=tasks.get(1),last=tasks.get(0);
|
||||
taskService.handle(SCH,first.getId(),true,"first",first.getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,last.getId(),true,"last",last.getAssigneeId(),"转乙科");
|
||||
FlwAdvanceIntent head=d09Head(id);
|
||||
assertEquals(last.getId(),head.getTriggerTaskId());assertEquals(last.getAssigneeId(),head.getAssigneeId());
|
||||
assertEquals("转乙科",head.getEdgeName());assertEquals("PENDING",head.getStatus());assertEquals(1,head.getAttempts());
|
||||
org.mockito.Mockito.verify(advanceService,org.mockito.Mockito.times(6)).tryAdvance(org.mockito.ArgumentMatchers.anyLong(),org.mockito.ArgumentMatchers.anyLong());
|
||||
org.mockito.Mockito.doCallRealMethod().when(advanceService).tryAdvance(org.mockito.ArgumentMatchers.anyLong(),org.mockito.ArgumentMatchers.anyLong());
|
||||
d09Jdbc.update("UPDATE flw_advance_intent SET next_retry_at=DATE_SUB(NOW(),INTERVAL 1 SECOND) WHERE id=?",head.getId());
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
assertEquals("DONE",intents.findById(head.getId()).get().getStatus());
|
||||
assertEquals(last.getAssigneeId(),stateEventRepository.findAll().stream()
|
||||
.filter(e->id.equals(e.getInstanceId()) && "flow.task.created".equals(e.getEventType()))
|
||||
.max(java.util.Comparator.comparing(com.yunhai.flowcenter.entity.FlwStateEvent::getId)).get().getOperatorId());
|
||||
}
|
||||
|
||||
@Test void d09_claimSnapshotCannotSettleARefreshedSameGeneration() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-snapshot");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,tasks.get(1).getId(),true,"first",tasks.get(1).getAssigneeId(),"通过");
|
||||
FlwAdvanceIntent observed=d09Head(id);
|
||||
java.util.concurrent.CountDownLatch claimed=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{Object rows=d09DueFromDatabase();claimed.countDown();assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));return rows;})
|
||||
.when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
java.util.concurrent.ExecutorService pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
java.util.concurrent.Future<?> old=pool.submit(()->advanceListener.sweepIntents());assertTrue(claimed.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
taskService.handle(SCH,tasks.get(0).getId(),true,"last",tasks.get(0).getAssigneeId(),"转乙科");
|
||||
FlwAdvanceIntent fresh=d09Head(id);assertTrue(fresh.getRevision()>observed.getRevision());
|
||||
release.countDown();old.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwAdvanceIntent preserved=d09Head(id);assertEquals(fresh.getRevision(),preserved.getRevision());
|
||||
assertEquals("PENDING",preserved.getStatus());assertEquals(tasks.get(0).getId(),preserved.getTriggerTaskId());assertEquals("转乙科",preserved.getEdgeName());
|
||||
assertEquals(0,preserved.getAttempts());assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
org.mockito.Mockito.doAnswer(inv->d09DueFromDatabase()).when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
} finally {release.countDown();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void d09_staleFailureCannotDeferOrOverwriteLastHandlerRefresh() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-defer-race");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,tasks.get(1).getId(),true,"first",tasks.get(1).getAssigneeId(),"通过");
|
||||
java.util.concurrent.CountDownLatch entered=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{entered.countDown();assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
throw new org.springframework.orm.ObjectOptimisticLockingFailureException(FlwInstance.class,id);})
|
||||
.when(advanceService).tryAdvance(org.mockito.ArgumentMatchers.anyLong(),org.mockito.ArgumentMatchers.anyLong());
|
||||
java.util.concurrent.ExecutorService pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
java.util.concurrent.Future<?> old=pool.submit(()->advanceListener.sweepIntents());assertTrue(entered.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
taskService.handle(SCH,tasks.get(0).getId(),true,"last",tasks.get(0).getAssigneeId(),"转乙科");
|
||||
FlwAdvanceIntent fresh=d09Head(id);release.countDown();old.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwAdvanceIntent preserved=d09Head(id);assertEquals(fresh.getRevision(),preserved.getRevision());assertEquals(0,preserved.getAttempts());
|
||||
assertNull(preserved.getLastError());assertEquals("PENDING",preserved.getStatus());assertEquals(tasks.get(0).getId(),preserved.getTriggerTaskId());
|
||||
org.mockito.Mockito.doCallRealMethod().when(advanceService).tryAdvance(org.mockito.ArgumentMatchers.anyLong(),org.mockito.ArgumentMatchers.anyLong());
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
} finally {release.countDown();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void d09_lockedSettlementThenLastHandlerCommitRearmsTheHead() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-settlement");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,tasks.get(1).getId(),true,"first",tasks.get(1).getAssigneeId(),"通过");
|
||||
java.util.concurrent.CountDownLatch locked=new java.util.concurrent.CountDownLatch(1),handlerEntered=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{
|
||||
if ("d09-settler".equals(Thread.currentThread().getName())) {locked.countDown();assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));}
|
||||
return controlledTasks.findAll().stream().filter(t->id.equals(t.getInstanceId()) && Integer.valueOf(0).equals(t.getStatus())).collect(java.util.stream.Collectors.toList());
|
||||
}).when(controlledTasks).findByInstanceIdAndStatus(id,0);
|
||||
FlowAdvanceService target=org.springframework.test.util.AopTestUtils.getUltimateTargetObject(advanceService);
|
||||
org.mockito.Mockito.doAnswer(inv->{handlerEntered.countDown();return inv.callRealMethod();})
|
||||
.when(target).recordHandled(org.mockito.ArgumentMatchers.any());
|
||||
java.util.concurrent.ExecutorService worker=java.util.concurrent.Executors.newSingleThreadExecutor(r->new Thread(r,"d09-settler"));
|
||||
java.util.concurrent.ExecutorService handler=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
java.util.concurrent.Future<?> settling=worker.submit(()->advanceListener.sweepIntents());assertTrue(locked.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
java.util.concurrent.Future<?> last=handler.submit(()->taskService.handle(SCH,tasks.get(0).getId(),true,"last",tasks.get(0).getAssigneeId(),"转乙科"));
|
||||
assertTrue(handlerEntered.await(20,java.util.concurrent.TimeUnit.SECONDS));assertFalse(last.isDone());
|
||||
release.countDown();settling.get(20,java.util.concurrent.TimeUnit.SECONDS);last.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwAdvanceIntent head=d09Head(id);assertEquals("PENDING",head.getStatus());assertEquals(tasks.get(0).getId(),head.getTriggerTaskId());
|
||||
assertEquals("转乙科",head.getEdgeName());assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
} finally {release.countDown();worker.shutdownNow();handler.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void d09H_oldClaimAcrossReturnBackHasNoSideEffectsAndNewGenerationTakesOver() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
mapDept("km",103,"Main");mapDept("ka",101,"A");mapDept("kb",102,"B");
|
||||
FlwDef def=saveAndPublishDef("d09h","D09 H",mainlineParallelTailDef("km","km"));
|
||||
Long id=apply(def.getFlowGuid(),"d09-h",201,"Applicant").getInstanceId();FlwTask first=tasksOf(id,103).get(0);
|
||||
taskService.handle(SCH,first.getId(),true,"first",103);
|
||||
Long oldActivationId=d09Head(id).getId();
|
||||
java.util.concurrent.CountDownLatch claimed=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{Object rows=d09DueFromDatabase();claimed.countDown();assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));return rows;})
|
||||
.when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
java.util.concurrent.ExecutorService pool=java.util.concurrent.Executors.newSingleThreadExecutor();
|
||||
try {
|
||||
java.util.concurrent.Future<?> stale=pool.submit(()->advanceListener.sweepIntents());assertTrue(claimed.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
// A competing fast worker legitimately advances the old activation before the return.
|
||||
org.mockito.Mockito.doCallRealMethod().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
java.util.Map<String,Object> data=new java.util.HashMap<>();data.put("nodeId","n1");
|
||||
advanceListener.onTaskHandled(FlowEvent.of(FlowEvent.Type.TASK_HANDLED,id,first.getId(),data));
|
||||
taskService.handle(SCH,tasksOf(id,101).get(0).getId(),true,"A",101);
|
||||
taskService.handle(SCH,tasksOf(id,102).get(0).getId(),true,"B",102);
|
||||
FlwTask tail=tasksOf(id,103).get(0);assertEquals("n3",tail.getNodeId());
|
||||
taskService.returnBack(SCH,tail.getId(),"n1","return",103);
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
FlwTask current=tasksOf(id,103).get(0);assertNotEquals(first.getId(),current.getId());
|
||||
taskService.handle(SCH,current.getId(),true,"new generation",103);
|
||||
FlwInstance before=instanceRepository.findById(id).get();List<FlwTask> beforeTasks=allTasks(id);
|
||||
release.countDown();stale.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwInstance after=instanceRepository.findById(id).get();assertEquals(before.getVersion(),after.getVersion());
|
||||
assertEquals(10,after.getStatus());assertEquals("n1",after.getCurrentNodes());assertEquals(def.getId(),after.getDefId());
|
||||
assertEquals(before.getApplyRound(),after.getApplyRound());assertEquals(beforeTasks.size(),allTasks(id).size());
|
||||
for(FlwTask t:beforeTasks)assertEquals(t.getStatus(),taskRepository.findById(t.getId()).get().getStatus());
|
||||
// Also model a historical stranded PENDING row with a CURRENT revision: only activation identity can reject it.
|
||||
FlwAdvanceIntent historical=intents.findById(oldActivationId).get();historical.setStatus("PENDING");historical=intents.saveAndFlush(historical);
|
||||
assertFalse(advanceService.tryAdvance(historical.getId(),historical.getRevision()));
|
||||
assertTrue(intents.findById(oldActivationId).get().getLastError().contains("STALE_ACTIVATION"));
|
||||
assertEquals(before.getVersion(),instanceRepository.findById(id).get().getVersion());assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
assertEquals("PENDING",d09Head(id).getStatus());
|
||||
org.mockito.Mockito.doAnswer(inv->d09DueFromDatabase()).when(intents).findTop50ByStatusAndNextRetryAtLessThanEqualOrderByCreateTimeAsc(org.mockito.ArgumentMatchers.anyString(),org.mockito.ArgumentMatchers.any());
|
||||
advanceListener.sweepIntents();assertFalse(instanceRepository.findById(id).get().getCurrentNodes().contains("n1"));
|
||||
assertEquals(2,taskRepository.findByInstanceIdAndStatus(id,0).size());
|
||||
} finally {release.countDown();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void d09V_guardedRoundAndDefinitionChangeRejectsOldPayloadWithoutLosingNewRoute() {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
mapDept("d09a",201,"A");mapDept("d09a",202,"B");mapDept("d09b",301,"Next");
|
||||
FlwDef def=saveAndPublishDef("d09round","D09 round",multiOutletDef("d09a","d09b"));
|
||||
FlowInstanceService.ApplyCommand command=new FlowInstanceService.ApplyCommand(SCH,def,"svc_item","d09-round","Title","/",null,201,"Applicant",null,"100001","notice",null);
|
||||
Long id=instanceService.applyGuarded(command,new FlowInstanceService.ApplyRetryPolicy("d09-round-1",1,false)).instanceId;
|
||||
List<FlwTask> old=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,old.get(0).getId(),true,"old",old.get(0).getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,old.get(1).getId(),false,"reject",old.get(1).getAssigneeId(),null);
|
||||
FlwAdvanceIntent stale=d09Head(id);assertEquals(1,stale.getActivationApplyRound());
|
||||
FlwDef next=saveAndPublishDef("d09round2","D09 new line",multiOutletDef("d09a","d09b").replace("转乙科","新边").replace("通过","完成"));
|
||||
next.setFlowGuid(def.getFlowGuid());next.setVersion(2);defRepository.saveAndFlush(next);
|
||||
FlowInstanceService.ApplyCommand nextCommand=new FlowInstanceService.ApplyCommand(SCH,next,"svc_item","d09-round","Title","/",null,201,"Applicant",null,"100001","notice",null);
|
||||
FlowInstanceService.GuardedOutcome restarted=instanceService.applyGuarded(nextCommand,new FlowInstanceService.ApplyRetryPolicy("d09-round-2",2,false));
|
||||
assertEquals(id,restarted.instanceId);assertEquals(2,restarted.applyRound);assertEquals("RESTARTED",restarted.branch);
|
||||
for(FlwTask task:taskRepository.findByInstanceIdAndStatus(id,0))taskService.handle(SCH,task.getId(),true,"new",task.getAssigneeId(),"新边");
|
||||
FlwInstance before=instanceRepository.findById(id).get();
|
||||
assertFalse(advanceService.tryAdvance(stale.getId(),stale.getRevision()));
|
||||
FlwInstance after=instanceRepository.findById(id).get();assertEquals(before.getVersion(),after.getVersion());
|
||||
assertEquals("n1",after.getCurrentNodes());assertEquals(10,after.getStatus());assertEquals(2,after.getApplyRound());
|
||||
assertEquals(next.getId(),after.getDefId());assertEquals(2,after.getDefVersion());assertEquals(0,taskRepository.findByInstanceIdAndStatus(id,0).size());
|
||||
assertEquals("DONE",intents.findById(stale.getId()).get().getStatus());assertTrue(intents.findById(stale.getId()).get().getLastError().contains("STALE_ACTIVATION"));
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
}
|
||||
|
||||
private FlwAdvanceIntent d09Legacy(Long id) {
|
||||
FlwAdvanceIntent legacy=new FlwAdvanceIntent();legacy.setInstanceId(id);legacy.setNodeId("n1");legacy.setEdgeName("untrusted-old-edge");
|
||||
return intents.saveAndFlush(legacy); // NULL activation and NULL retry time deliberately model existing data.
|
||||
}
|
||||
|
||||
@Test void d09_nullLegacyIntentHandsOffToRegisteredSuccessorWithoutUsingOldPayload() {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-null-successor");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
for(FlwTask task:tasks)taskService.handle(SCH,task.getId(),true,"current",task.getAssigneeId(),"转乙科");
|
||||
FlwAdvanceIntent successor=d09Head(id),legacy=d09Legacy(id);FlwInstance before=instanceRepository.findById(id).get();
|
||||
assertFalse(advanceService.tryAdvance(legacy.getId(),legacy.getRevision()));
|
||||
assertEquals(before.getVersion(),instanceRepository.findById(id).get().getVersion());assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
assertEquals("DONE",intents.findById(legacy.getId()).get().getStatus());
|
||||
assertEquals("PENDING",intents.findById(successor.getId()).get().getStatus());
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
}
|
||||
|
||||
private void d09InstallBackfillProcedure() throws Exception {
|
||||
String sql=org.springframework.util.StreamUtils.copyToString(new org.springframework.core.io.ClassPathResource(
|
||||
"sql/20261026_d09_activation_intent_draft.sql").getInputStream(),java.nio.charset.StandardCharsets.UTF_8);
|
||||
String procedure=sql.split("-- D09_BACKFILL_BEGIN",2)[1].split("-- D09_BACKFILL_END",2)[0].trim();
|
||||
d09Jdbc.execute("DROP PROCEDURE IF EXISTS d09_backfill_activation");d09Jdbc.execute(procedure);
|
||||
}
|
||||
|
||||
@Test void d09_nullLegacyPendingCohortIsHeldThenAuditedBackfillAndRealHandlingResume() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-null-pending");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
intents.delete(d09Head(id));FlwAdvanceIntent legacy=d09Legacy(id);
|
||||
advanceListener.sweepIntents();assertEquals("EXHAUSTED",intents.findById(legacy.getId()).get().getStatus());
|
||||
assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());assertEquals(2,taskRepository.findByInstanceIdAndStatus(id,0).size());
|
||||
assertThrows(IllegalStateException.class,()->taskService.handle(SCH,tasks.get(0).getId(),true,"must roll back",tasks.get(0).getAssigneeId(),"通过"));
|
||||
assertEquals(0,taskRepository.findById(tasks.get(0).getId()).get().getStatus());
|
||||
d09InstallBackfillProcedure();
|
||||
assertThrows(org.springframework.dao.DataAccessException.class,()->d09Jdbc.update("CALL d09_backfill_activation(?,?,?,?,?)",id,"n1","["+tasks.get(0).getId()+"]",null,"IT omitted member"));
|
||||
assertFalse(intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(id,"n1").isPresent());
|
||||
String cohort="["+tasks.get(0).getId()+","+tasks.get(1).getId()+"]";
|
||||
d09Jdbc.update("CALL d09_backfill_activation(?,?,?,?,?)",id,"n1",cohort,null,"IT audited pending cohort");
|
||||
assertEquals("DONE",intents.findById(legacy.getId()).get().getStatus());assertTrue(intents.findById(legacy.getId()).get().getLastError().contains("HANDOFF"));
|
||||
assertEquals("DONE",d09Head(id).getStatus());assertNull(d09Head(id).getTriggerTaskId());
|
||||
taskService.handle(SCH,tasks.get(1).getId(),true,"first",tasks.get(1).getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,tasks.get(0).getId(),true,"last",tasks.get(0).getAssigneeId(),"转乙科");
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
}
|
||||
|
||||
@Test void d09_nullLegacyCompletedCohortRequiresProvenLastHandlerBeforeBackfill() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-null-completed");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
taskService.handle(SCH,tasks.get(1).getId(),true,"first",tasks.get(1).getAssigneeId(),"通过");
|
||||
taskService.handle(SCH,tasks.get(0).getId(),true,"last",tasks.get(0).getAssigneeId(),"转乙科");
|
||||
intents.delete(d09Head(id));FlwAdvanceIntent legacy=d09Legacy(id);advanceListener.sweepIntents();
|
||||
assertEquals("EXHAUSTED",intents.findById(legacy.getId()).get().getStatus());assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
d09InstallBackfillProcedure();String cohort="["+tasks.get(0).getId()+","+tasks.get(1).getId()+"]";
|
||||
assertThrows(org.springframework.dao.DataAccessException.class,()->d09Jdbc.update("CALL d09_backfill_activation(?,?,?,?,?)",id,"n1",cohort,null,"IT missing last-handler evidence"));
|
||||
assertEquals("EXHAUSTED",intents.findById(legacy.getId()).get().getStatus());
|
||||
d09Jdbc.update("CALL d09_backfill_activation(?,?,?,?,?)",id,"n1",cohort,tasks.get(0).getId(),"IT witnessed lower-ID last handler");
|
||||
assertEquals(tasks.get(0).getId(),d09Head(id).getTriggerTaskId());assertEquals("PENDING",d09Head(id).getStatus());
|
||||
assertThrows(org.springframework.dao.DataAccessException.class,()->d09Jdbc.update("CALL d09_backfill_activation(?,?,?,?,?)",id,"n1",cohort,tasks.get(0).getId(),"IT cannot overwrite successor"));
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
}
|
||||
|
||||
@Test void d09_oldWorkerAlreadyPastGenerationGuardRollsBackAcrossRestart() throws Exception {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
mapDept("d09a",201,"A");mapDept("d09a",202,"B");mapDept("d09b",301,"Cancel");
|
||||
FlwDef def=saveAndPublishDef("d09-fence","D09 fence",parallelDef("d09a","d09b"));
|
||||
Long id=apply(def.getFlowGuid(),"d09-fence",201,"Applicant").getInstanceId();
|
||||
List<FlwTask> initial=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
String node=initial.stream().filter(t->t.getAssigneeId()==201).findFirst().get().getNodeId();
|
||||
for(FlwTask task:initial)if(node.equals(task.getNodeId()))taskService.handle(SCH,task.getId(),true,"old approved",task.getAssigneeId());
|
||||
FlwAdvanceIntent oldHead=intents.findFirstByInstanceIdAndNodeIdAndActivationTaskIdIsNotNullOrderByIdDesc(id,node).get();
|
||||
java.util.concurrent.CountDownLatch validated=new java.util.concurrent.CountDownLatch(1),release=new java.util.concurrent.CountDownLatch(1);
|
||||
org.mockito.Mockito.doAnswer(inv->{
|
||||
if("d09-old-guard".equals(Thread.currentThread().getName())) {validated.countDown();assertTrue(release.await(20,java.util.concurrent.TimeUnit.SECONDS));}
|
||||
return inv.callRealMethod();
|
||||
}).when(controlledEngine).continueAdvance(org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.eq(node),org.mockito.ArgumentMatchers.any(),org.mockito.ArgumentMatchers.any());
|
||||
java.util.concurrent.ExecutorService pool=java.util.concurrent.Executors.newSingleThreadExecutor(r->new Thread(r,"d09-old-guard"));
|
||||
try {
|
||||
java.util.concurrent.Future<?> old=pool.submit(()->advanceListener.sweepIntents());assertTrue(validated.await(20,java.util.concurrent.TimeUnit.SECONDS));
|
||||
FlwTask cancel=initial.stream().filter(t->t.getAssigneeId()==301).findFirst().get();
|
||||
taskService.handle(SCH,cancel.getId(),false,"reject other branch",301);
|
||||
assertEquals(30,instanceRepository.findById(id).get().getStatus());
|
||||
assertEquals(id,apply(def.getFlowGuid(),"d09-fence",201,"Applicant").getInstanceId());
|
||||
for(FlwTask task:taskRepository.findByInstanceIdAndStatus(id,0))if(node.equals(task.getNodeId()))taskService.handle(SCH,task.getId(),true,"new approved",task.getAssigneeId());
|
||||
FlwInstance before=instanceRepository.findById(id).get();List<FlwTask> tasksBefore=allTasks(id);
|
||||
java.util.List<java.util.Map<String,Object>> branchesBefore=d09Jdbc.queryForList("SELECT id,status FROM flw_branch WHERE instance_id=? ORDER BY id",id);
|
||||
release.countDown();old.get(20,java.util.concurrent.TimeUnit.SECONDS);
|
||||
FlwInstance after=instanceRepository.findById(id).get();assertEquals(before.getVersion(),after.getVersion());assertEquals(before.getCurrentNodes(),after.getCurrentNodes());
|
||||
assertEquals(10,after.getStatus());assertEquals(tasksBefore.size(),allTasks(id).size());
|
||||
for(FlwTask task:tasksBefore)assertEquals(task.getStatus(),taskRepository.findById(task.getId()).get().getStatus());
|
||||
assertEquals(branchesBefore,d09Jdbc.queryForList("SELECT id,status FROM flw_branch WHERE instance_id=? ORDER BY id",id));
|
||||
// Its failed settlement did not consume the new generation. That generation advances independently.
|
||||
advanceListener.sweepIntents();assertFalse(instanceRepository.findById(id).get().getCurrentNodes().contains(node));
|
||||
d09Jdbc.update("UPDATE flw_advance_intent SET next_retry_at=DATE_SUB(NOW(),INTERVAL 1 SECOND) WHERE id=?",oldHead.getId());
|
||||
advanceListener.sweepIntents();assertEquals("DONE",intents.findById(oldHead.getId()).get().getStatus());
|
||||
assertTrue(intents.findById(oldHead.getId()).get().getLastError().contains("STALE_ACTIVATION"));
|
||||
} finally {release.countDown();pool.shutdownNow();}
|
||||
}
|
||||
|
||||
@Test void d09_transferRemainsInItsActivationAndLowerIdLastHandlerStillWins() {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-transfer");List<FlwTask> tasks=taskRepository.findByInstanceIdAndStatus(id,0);
|
||||
FlwAdvanceIntent original=d09Head(id);FlwTask transferred=tasks.get(0),last=tasks.get(1);
|
||||
taskService.transfer(SCH,transferred.getId(),301,"transfer",transferred.getAssigneeId());
|
||||
FlwTask replacement=taskRepository.findByInstanceIdAndStatus(id,0).stream().filter(t->t.getAssigneeId()==301).findFirst().get();
|
||||
assertTrue(replacement.getId()>last.getId());assertEquals(original.getId(),d09Head(id).getId());assertTrue(d09Head(id).containsTask(replacement.getId()));
|
||||
taskService.handle(SCH,replacement.getId(),true,"first",301,"通过");
|
||||
taskService.handle(SCH,last.getId(),true,"last",last.getAssigneeId(),"转乙科");
|
||||
advanceListener.sweepIntents();assertEquals("n2",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
assertEquals(last.getId(),d09Head(id).getTriggerTaskId());assertEquals(last.getAssigneeId(),d09Head(id).getAssigneeId());
|
||||
}
|
||||
|
||||
@Test void d09_ambiguousTransferTimestampCannotGuessAcrossActivations() {
|
||||
org.mockito.Mockito.doNothing().when(advanceListener).onTaskHandled(org.mockito.ArgumentMatchers.any());
|
||||
Long id=d09Multi("d09-transfer-ambiguous");FlwInstance instance=instanceRepository.findById(id).get();
|
||||
FlwTask source=tasksOf(id,201).get(0);taskService.transfer(SCH,source.getId(),301,"old transfer",201);
|
||||
FlwTask reject=tasksOf(id,202).get(0);taskService.handle(SCH,reject.getId(),false,"reject",202);
|
||||
FlwDef def=defRepository.findById(instance.getDefId()).get();apply(def.getFlowGuid(),"d09-transfer-ambiguous",201,"Applicant");
|
||||
FlwTask current=tasksOf(id,201).get(0);int before=allTasks(id).size();
|
||||
FlowAdvanceService target=org.springframework.test.util.AopTestUtils.getUltimateTargetObject(advanceService);
|
||||
org.mockito.Mockito.doAnswer(inv->{FlowEvent event=inv.getArgument(0);
|
||||
// Force equal millisecond timestamps in two generations; a timestamp is only a candidate filter.
|
||||
d09Jdbc.update("UPDATE flw_task SET handle_time=(SELECT stamp FROM (SELECT arrive_time stamp FROM flw_task WHERE id=?) s) WHERE id=?",event.getTaskId(),source.getId());
|
||||
return inv.callRealMethod();
|
||||
}).when(target).registerTransfer(org.mockito.ArgumentMatchers.any());
|
||||
assertThrows(IllegalStateException.class,()->taskService.transfer(SCH,current.getId(),301,"ambiguous transfer",201));
|
||||
assertEquals(0,taskRepository.findById(current.getId()).get().getStatus());assertEquals(before,allTasks(id).size());
|
||||
assertFalse(d09Head(id).containsTask(source.getId()));assertEquals("n1",instanceRepository.findById(id).get().getCurrentNodes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void apply_createsInstanceAndCountersignTasks_allApprove_completes() {
|
||||
mapDept("ybb", 101, "甲");
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwRouter;
|
||||
import com.yunhai.flowcenter.service.DiagramTokenService;
|
||||
import com.yunhai.flowcenter.service.FlowRouterAdminService;
|
||||
import com.yunhai.flowcenter.service.FlowTaskService;
|
||||
import com.yunhai.flowcenter.service.OapiFlowService;
|
||||
import com.yunhai.flowcenter.support.FlowTestSupport;
|
||||
import com.yunhai.flowcenter.support.OapiSignedClient;
|
||||
@@ -52,6 +53,9 @@ class OapiFlowContractIT extends FlowTestSupport {
|
||||
@Autowired
|
||||
private OapiFlowService flowService;
|
||||
|
||||
@Autowired
|
||||
private FlowTaskService taskService;
|
||||
|
||||
@Autowired
|
||||
private FlowRouterAdminService routerAdminService;
|
||||
|
||||
@@ -431,7 +435,12 @@ class OapiFlowContractIT extends FlowTestSupport {
|
||||
assertEquals(0, finished.get("total").asInt());
|
||||
}
|
||||
|
||||
/** 办理(第三步 T-C1b):非办理人业务码拒绝不 500;同意推进+opinion 进回调 payload;拒绝必填意见 */
|
||||
/**
|
||||
* 办理(第三步 T-C1b;2026-10-25 R1 返修重写):oapi approve/reject 无可验证用户证明
|
||||
* 一律 fail-closed(即便自报办理人 ID)——缺 operatorName/非办理人/办理人本人均业务码拒绝、
|
||||
* 任务保持待办;合法办理经 <b>CAS 会话路径</b>(FlowTaskService.handle,与
|
||||
* FlowUserController 同入口)完成:同意推进 + opinion 进回调 payload、拒绝必填意见。
|
||||
*/
|
||||
@Test
|
||||
void approveAndReject_operatorChecked_opinionPropagates() throws Exception {
|
||||
mapDept("ybb", 101, "甲");
|
||||
@@ -464,12 +473,12 @@ class OapiFlowContractIT extends FlowTestSupport {
|
||||
.get("instanceId").asLong();
|
||||
Long taskId = taskRepository.findByInstanceIdAndStatus(instanceId, 0).get(0).getId();
|
||||
|
||||
// 缺 operatorName → 业务码拒绝
|
||||
// R1:oapi 缺 operatorName → 业务码拒绝(门禁先拒,fail-closed 优先于参数校验)
|
||||
ResponseEntity<JsonNode> noName = client.post(
|
||||
"/oapi/flow/task/" + taskId + "/approve?schId=1&operatorId=101", "{}", JsonNode.class);
|
||||
assertNotEquals(0, noName.getBody().get("code").asInt(), "缺 operatorName 应被拒绝");
|
||||
|
||||
// 非办理人(999)→ 业务码拒绝(code!=0,HTTP 200),任务仍在待办
|
||||
// R1:非办理人(999)自报 → 业务码拒绝(code!=0,HTTP 200),任务仍在待办
|
||||
ResponseEntity<JsonNode> forged = client.post(
|
||||
"/oapi/flow/task/" + taskId + "/approve?schId=1&operatorId=999&operatorName=路人",
|
||||
"{\"opinion\":\"越权\"}", JsonNode.class);
|
||||
@@ -478,31 +487,41 @@ class OapiFlowContractIT extends FlowTestSupport {
|
||||
assertEquals(1, taskRepository.findByInstanceIdAndStatus(instanceId, 0).size(),
|
||||
"越权后任务仍在待办");
|
||||
|
||||
// 办理人(101)同意 → 任务 1、单节点单人会签放行 → 办件 20;opinion 进回调 payload
|
||||
ResponseEntity<JsonNode> ok = client.post(
|
||||
// R1:办理人(101)本人自报 operatorId → 同样拒绝(知道办理人 ID ≠ 该用户本人在操作)
|
||||
ResponseEntity<JsonNode> selfReported = client.post(
|
||||
"/oapi/flow/task/" + taskId + "/approve?schId=1&operatorId=101&operatorName=甲",
|
||||
"{\"opinion\":\"同意,情况属实\"}", JsonNode.class);
|
||||
assertEquals(0, ok.getBody().get("code").asInt(), "办理人同意应成功");
|
||||
assertNotEquals(0, selfReported.getBody().get("code").asInt(),
|
||||
"R1:oapi 快捷审批即便自报真实办理人也不得放行");
|
||||
assertTrue(selfReported.getBody().get("msg").asText().contains("快捷审批未放行"),
|
||||
"拒绝文案须指明迁移路径(CAS 人工办理)");
|
||||
assertEquals(1, taskRepository.findByInstanceIdAndStatus(instanceId, 0).size(),
|
||||
"拒绝后任务仍在待办");
|
||||
|
||||
// 合法办理改走 CAS 会话路径(FlowUserController 同入口):同意 → 任务 1、办件 20;
|
||||
// opinion 进回调 payload
|
||||
taskService.handle(1L, taskId, true, "同意,情况属实", 101, null);
|
||||
assertEquals(1, taskRepository.findById(taskId).get().getStatus());
|
||||
assertEquals(20, instanceRepository.findById(instanceId).get().getStatus());
|
||||
assertTrue(awaitPayloadContains(receivedPayloads, "同意,情况属实"),
|
||||
"opinion 应透传到回调 payload");
|
||||
|
||||
// 第二件:拒绝无意见 → 业务码拒绝;带意见 → 任务 2、办件 30
|
||||
// 第二件:oapi 拒绝(无意见/有意见)→ R1 一律业务码拒绝(门禁先于意见必填校验);
|
||||
// 会话路径拒绝无意见 → 业务码拒绝;带意见 → 任务 2、办件 30
|
||||
Long id2 = unwrap(client.post("/oapi/flow/apply?schId=1", "{"
|
||||
+ "\"flowGuid\":\"" + def.getFlowGuid() + "\","
|
||||
+ "\"bizType\":\"svc_item\",\"bizId\":\"ap-2\",\"bizTitle\":\"驳回件\","
|
||||
+ "\"submitterId\":202,\"submitterName\":\"李四\"}", JsonNode.class).getBody())
|
||||
.get("instanceId").asLong();
|
||||
Long taskId2 = taskRepository.findByInstanceIdAndStatus(id2, 0).get(0).getId();
|
||||
ResponseEntity<JsonNode> noOpinion = client.post(
|
||||
ResponseEntity<JsonNode> oapiNoOpinion = client.post(
|
||||
"/oapi/flow/task/" + taskId2 + "/reject?schId=1&operatorId=101&operatorName=甲",
|
||||
"{}", JsonNode.class);
|
||||
assertNotEquals(0, noOpinion.getBody().get("code").asInt(), "拒绝必须填写意见");
|
||||
ResponseEntity<JsonNode> rejected = client.post(
|
||||
"/oapi/flow/task/" + taskId2 + "/reject?schId=1&operatorId=101&operatorName=甲",
|
||||
"{\"opinion\":\"材料不全\"}", JsonNode.class);
|
||||
assertEquals(0, rejected.getBody().get("code").asInt());
|
||||
assertNotEquals(0, oapiNoOpinion.getBody().get("code").asInt(), "R1:oapi 拒绝同样不放行");
|
||||
assertThrows(BizException.class,
|
||||
() -> taskService.handle(1L, taskId2, false, null, 101),
|
||||
"会话路径拒绝必须填写意见");
|
||||
taskService.handle(1L, taskId2, false, "材料不全", 101);
|
||||
assertEquals(2, taskRepository.findById(taskId2).get().getStatus());
|
||||
assertEquals(30, instanceRepository.findById(id2).get().getStatus());
|
||||
assertTrue(awaitPayloadContains(receivedPayloads, "材料不全"),
|
||||
@@ -649,7 +668,7 @@ class OapiFlowContractIT extends FlowTestSupport {
|
||||
assertEquals(0, n1.get("candidates").size(), "解析异常节点降级空候选");
|
||||
}
|
||||
|
||||
/** 合法 assigns:200 + 快照落库(姓名走 requireUserName 严格口径)+ 只为被指派人建待办 */
|
||||
/** 合法 assigns:200 + 快照落库(姓名走 requireEligibleAssignee 严格口径)+ 只为被指派人建待办 */
|
||||
@Test
|
||||
void apply_withAssigns_ok() throws Exception {
|
||||
mapDept("ybb", 101, "甲");
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.yunhai.flowcenter.oapi;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.service.FlowTaskService;
|
||||
import com.yunhai.flowcenter.service.OapiFlowService;
|
||||
import com.yunhai.flowcenter.support.FlowTestSupport;
|
||||
import com.yunhai.flowcenter.support.OapiSignedClient;
|
||||
@@ -46,6 +47,9 @@ class OapiFlowTasksByBizTest extends FlowTestSupport {
|
||||
@Autowired
|
||||
private OapiFlowService flowService;
|
||||
|
||||
@Autowired
|
||||
private FlowTaskService taskService;
|
||||
|
||||
private OapiSignedClient client;
|
||||
|
||||
@Autowired
|
||||
@@ -143,9 +147,8 @@ class OapiFlowTasksByBizTest extends FlowTestSupport {
|
||||
FlwDef def = saveAndPublishDef("bb2", "已办结", linearDef("ybb", "审核"));
|
||||
Long instanceId = applyOne(def, "done-1", "已办结通知");
|
||||
Long taskId = taskRepository.findByInstanceIdAndStatus(instanceId, 0).get(0).getId();
|
||||
assertEquals(0, client.post("/oapi/flow/task/" + taskId
|
||||
+ "/approve?schId=1&operatorId=101&operatorName=甲", "{}", JsonNode.class)
|
||||
.getBody().get("code").asInt(), "办理人同意应成功");
|
||||
// R1:oapi 快捷审批已 fail-closed,办结动作改走 CAS 会话路径(FlowTaskService.handle)
|
||||
taskService.handle(SCH, taskId, true, "同意", 101, null);
|
||||
JsonNode data = byBiz("done-1", 101);
|
||||
assertEquals(0, data.get("tasks").size(), "办结后本人无待办");
|
||||
assertEquals(20, data.get("status").asInt(), "终态可展示:回带办件状态");
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.yunhai.flowcenter.entity.FlwCc;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.entity.FlwTask;
|
||||
import com.yunhai.flowcenter.enums.FlwEnums;
|
||||
import com.yunhai.flowcenter.model.OapiModels;
|
||||
import com.yunhai.flowcenter.stub.StubUserClient;
|
||||
import com.yunhai.flowcenter.support.FlowTestSupport;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* D11 人员资格终审业务入口 IT:固定 USERS / 手选指派 / 部门解析 / 移交 / 退回重入,
|
||||
* 并证明 NOTIFY receivers 的既有宽容口径未被收紧。
|
||||
*
|
||||
* <p>真实 MySQL 隔离库(同 D09/D10 门禁:8.x / 13429 / fl_d09_20261026);每例清表。</p>
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@DisplayName("D11 人员资格终审(业务入口)")
|
||||
class D11AssigneeEligibilityIT extends FlowTestSupport {
|
||||
|
||||
@Autowired
|
||||
private OapiFlowService oapiFlowService;
|
||||
@Autowired
|
||||
private FlowTaskService taskService;
|
||||
@Autowired
|
||||
private JdbcTemplate jdbc;
|
||||
@Autowired
|
||||
private MutableStubUserClient users;
|
||||
|
||||
@org.springframework.boot.test.mock.mockito.MockBean
|
||||
private org.springframework.scheduling.TaskScheduler controlledScheduler;
|
||||
|
||||
@TestConfiguration
|
||||
static class StubConfig {
|
||||
@Bean
|
||||
@Primary
|
||||
public MutableStubUserClient stubUserClient() {
|
||||
return new MutableStubUserClient();
|
||||
}
|
||||
}
|
||||
|
||||
/** 可在用例中动态停用某人的 UserBase 桩(模拟流程启动后人员状态变化)。 */
|
||||
public static class MutableStubUserClient extends StubUserClient {
|
||||
private final Set<Integer> disabled = ConcurrentHashMap.newKeySet();
|
||||
|
||||
void disable(Integer userId) {
|
||||
disabled.add(userId);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
disabled.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BoaUser getUserById(String userId) {
|
||||
BoaUser user = super.getUserById(userId);
|
||||
if (user != null && disabled.contains(Integer.valueOf(userId))) {
|
||||
user.setStatus(0);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BoaUser getUserInfo(int userId) {
|
||||
BoaUser user = super.getUserInfo(userId);
|
||||
if (user != null && disabled.contains(userId)) {
|
||||
user.setStatus(0);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
assertThat(jdbc.queryForObject("SELECT @@version", String.class)).startsWith("8.");
|
||||
assertThat(jdbc.queryForObject("SELECT @@port", Integer.class)).isEqualTo(13429);
|
||||
assertThat(jdbc.queryForObject("SELECT DATABASE()", String.class)).isEqualTo("fl_d09_20261026");
|
||||
cleanDb();
|
||||
users.reset();
|
||||
}
|
||||
|
||||
// ==================== 固定 USERS ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 全部合法:正常建实例与任务")
|
||||
void fixedUsersAllEligibleCreatesTasks() {
|
||||
FlwDef def = saveAndPublishDef("d11a", "固定人合法", usersDef(101, 102));
|
||||
Long instanceId = apply(def, "d11-fixed-ok").getInstanceId();
|
||||
|
||||
assertThat(instanceRepository.findById(instanceId).get().getStatus())
|
||||
.isEqualTo(FlwEnums.InstanceStatus.APPROVING.getCode());
|
||||
List<FlwTask> pending = taskRepository.findByInstanceIdAndStatus(instanceId, 0);
|
||||
assertThat(pending).extracting(FlwTask::getAssigneeId).containsExactlyInAnyOrder(101, 102);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含不存在人员:整体拒绝,零实例零任务")
|
||||
void fixedUsersMissingRejectsZeroState() {
|
||||
assertFixedRejected(usersDef(101, 9999), "d11-fixed-missing", "不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含已停用人员:整体拒绝,零实例零任务")
|
||||
void fixedUsersDisabledRejectsZeroState() {
|
||||
assertFixedRejected(usersDef(101, 9001), "d11-fixed-disabled", "禁用");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 含外校人员:整体拒绝,零实例零任务")
|
||||
void fixedUsersCrossSchoolRejectsZeroState() {
|
||||
assertFixedRejected(usersDef(101, 9002), "d11-fixed-cross", "不属于该学校");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定 USERS 合法与非法混排:整体 fail-closed,不静默过滤")
|
||||
void fixedUsersMixedRejectsWholeConfig() {
|
||||
assertFixedRejected(usersDef(101, 102, 9001), "d11-fixed-mixed", "禁用");
|
||||
assertThat(taskRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("固定人非法位于后续节点:启动前预检即整体拒绝,不留下卡单")
|
||||
void fixedUsersInvalidAtLaterNodeRejectedAtStart() {
|
||||
FlwDef def = saveAndPublishDef("d11b", "后续固定人非法", twoFixedNodesDef(101, 9001));
|
||||
assertThatThrownBy(() -> apply(def, "d11-fixed-later"))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("n2")
|
||||
.hasMessageContaining("禁用");
|
||||
assertZeroState("d11-fixed-later");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("v3 受理边界:prepareFormal 对非法固定 USERS 预检拒绝,零实例零任务")
|
||||
void formalPrepareRejectsFixedUsersBeforeInstanceCreation() {
|
||||
FlwDef def = saveAndPublishDef("d11k", "正式固定人拒绝", usersDef(101, 9001));
|
||||
com.yunhai.flowcenter.model.FormalApplyModels.Request request =
|
||||
new com.yunhai.flowcenter.model.FormalApplyModels.Request();
|
||||
request.setRequestId("req-d11-fixed");
|
||||
request.setFlowGuid(def.getFlowGuid());
|
||||
request.setBizType("d11");
|
||||
request.setBizId("d11-formal-fixed");
|
||||
request.setSubmitterId(201);
|
||||
request.setSubmitterName("提交人");
|
||||
FlowSourcePrincipalResolver.Principal source = new FlowSourcePrincipalResolver.Principal(
|
||||
"11111111-1111-4111-8111-111111111111", 18, "100018", "svc-hall");
|
||||
|
||||
assertThatThrownBy(() -> oapiFlowService.prepareFormal(SCH, source, request))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("9001")
|
||||
.hasMessageContaining("禁用");
|
||||
assertZeroState("d11-formal-fixed");
|
||||
}
|
||||
|
||||
// ==================== 手选指派 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("手选合法人员:落快照并只给被指派人建待办")
|
||||
void manualAssignEligiblePasses() {
|
||||
mapDept("d11", 101, "甲");
|
||||
FlwDef def = saveAndPublishDef("d11c", "手选合法", assignableDeptDef("d11"));
|
||||
OapiModels.ApplyResultVo result = apply(def, "d11-manual-ok", 101);
|
||||
|
||||
FlwInstance instance = instanceRepository.findById(result.getInstanceId()).get();
|
||||
assertThat(instance.getAssignJson()).contains("\"userId\":101");
|
||||
List<FlwTask> pending = taskRepository.findByInstanceIdAndStatus(result.getInstanceId(), 0);
|
||||
assertThat(pending).hasSize(1);
|
||||
assertThat(pending.get(0).getAssigneeId()).isEqualTo(101);
|
||||
assertThat(pending.get(0).getAssigneeName()).isEqualTo("用户101");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("手选已停用/外校/不存在人员:逐人资格终审拒绝,零实例")
|
||||
void manualAssignIneligibleRejected() {
|
||||
mapDept("d11", 101, "甲");
|
||||
mapDept("d11", 9001, "停用");
|
||||
mapDept("d11", 9002, "外校");
|
||||
FlwDef def = saveAndPublishDef("d11d", "手选拒绝", assignableDeptDef("d11"));
|
||||
|
||||
assertThatThrownBy(() -> apply(def, "d11-manual-disabled", 9001))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("禁用");
|
||||
assertZeroState("d11-manual-disabled");
|
||||
assertThatThrownBy(() -> apply(def, "d11-manual-cross", 9002))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("不属于该学校");
|
||||
assertZeroState("d11-manual-cross");
|
||||
assertThatThrownBy(() -> apply(def, "d11-manual-missing", 9999))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("不存在");
|
||||
assertZeroState("d11-manual-missing");
|
||||
}
|
||||
|
||||
// ==================== 部门解析 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("部门含非法成员:合法成员保留、非法成员不建任务")
|
||||
void deptFiltersIneligibleMembers() {
|
||||
mapDept("d11", 101, "甲");
|
||||
mapDept("d11", 9001, "停用");
|
||||
mapDept("d11", 9002, "外校");
|
||||
FlwDef def = saveAndPublishDef("d11e", "部门过滤", deptDef("d11"));
|
||||
|
||||
Long instanceId = apply(def, "d11-dept-partial").getInstanceId();
|
||||
List<FlwTask> pending = taskRepository.findByInstanceIdAndStatus(instanceId, 0);
|
||||
assertThat(pending).extracting(FlwTask::getAssigneeId).containsExactly(101);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("部门成员全部不合格:明确拒绝,零实例零任务")
|
||||
void deptAllIneligibleRejected() {
|
||||
mapDept("d11", 9001, "停用");
|
||||
mapDept("d11", 9002, "外校");
|
||||
FlwDef def = saveAndPublishDef("d11f", "部门全非法", deptDef("d11"));
|
||||
|
||||
assertThatThrownBy(() -> apply(def, "d11-dept-all-bad"))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("均不具备办理资格");
|
||||
assertZeroState("d11-dept-all-bad");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("部门解析为空:沿用既有“无可用办理人”拒绝")
|
||||
void deptEmptyRejected() {
|
||||
FlwDef def = saveAndPublishDef("d11g", "部门为空", deptDef("nobody"));
|
||||
assertThatThrownBy(() -> apply(def, "d11-dept-empty"))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("无可用办理人");
|
||||
assertZeroState("d11-dept-empty");
|
||||
}
|
||||
|
||||
// ==================== 移交 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("移交目标非法:原任务保持待办、不产生替换待办;合法目标才完成移交")
|
||||
void transferRejectsIneligibleTargetWithoutHalfState() {
|
||||
mapDept("d11", 101, "甲");
|
||||
FlwDef def = saveAndPublishDef("d11h", "移交终审", deptDef("d11"));
|
||||
Long instanceId = apply(def, "d11-transfer").getInstanceId();
|
||||
FlwTask task = taskRepository.findByInstanceIdAndStatus(instanceId, 0).get(0);
|
||||
int beforeCount = taskRepository.findByInstanceIdOrderByIdAsc(instanceId).size();
|
||||
|
||||
for (Integer bad : Arrays.asList(9001, 9002, 9999)) {
|
||||
assertThatThrownBy(() -> taskService.transfer(SCH, task.getId(), bad, "bad", 101))
|
||||
.isInstanceOf(BizException.class);
|
||||
assertThat(taskRepository.findById(task.getId()).get().getStatus())
|
||||
.isEqualTo(FlwEnums.TaskStatus.PENDING.getCode());
|
||||
assertThat(taskRepository.findByInstanceIdAndStatus(instanceId, 0)).hasSize(1);
|
||||
assertThat(taskRepository.findByInstanceIdOrderByIdAsc(instanceId)).hasSize(beforeCount);
|
||||
assertThat(instanceRepository.findById(instanceId).get().getCurrentNodes()).isEqualTo("n1");
|
||||
}
|
||||
|
||||
taskService.transfer(SCH, task.getId(), 102, "合法移交", 101);
|
||||
assertThat(taskRepository.findById(task.getId()).get().getStatus())
|
||||
.isEqualTo(FlwEnums.TaskStatus.TRANSFERRED.getCode());
|
||||
List<FlwTask> pending = taskRepository.findByInstanceIdAndStatus(instanceId, 0);
|
||||
assertThat(pending).hasSize(1);
|
||||
assertThat(pending.get(0).getAssigneeId()).isEqualTo(102);
|
||||
}
|
||||
|
||||
// ==================== 退回重入 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("退回目标固定人已停用:退回整体回滚,原任务仍待办")
|
||||
void returnBackToNowIneligibleFixedUserRollsBack() {
|
||||
FlwDef def = saveAndPublishDef("d11i", "退回资格终审",
|
||||
linearThreeFixedDef(101, 102, 101));
|
||||
Long instanceId = apply(def, "d11-return").getInstanceId();
|
||||
FlwTask n1 = taskRepository.findByInstanceIdAndStatus(instanceId, 0).get(0);
|
||||
taskService.handle(SCH, n1.getId(), true, "ok", 101);
|
||||
FlwTask n2 = taskRepository.findByInstanceIdAndStatus(instanceId, 0).get(0);
|
||||
assertThat(n2.getNodeId()).isEqualTo("n2");
|
||||
int beforeCount = taskRepository.findByInstanceIdOrderByIdAsc(instanceId).size();
|
||||
users.disable(101);
|
||||
|
||||
assertThatThrownBy(() -> taskService.returnBack(SCH, n2.getId(), "n1", "重审", 102))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("禁用");
|
||||
assertThat(taskRepository.findById(n2.getId()).get().getStatus())
|
||||
.isEqualTo(FlwEnums.TaskStatus.PENDING.getCode());
|
||||
assertThat(taskRepository.findByInstanceIdOrderByIdAsc(instanceId)).hasSize(beforeCount);
|
||||
assertThat(taskRepository.findByInstanceIdAndStatus(instanceId, 0)).hasSize(1);
|
||||
assertThat(instanceRepository.findById(instanceId).get().getCurrentNodes()).isEqualTo("n2");
|
||||
}
|
||||
|
||||
// ==================== NOTIFY 宽容 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("NOTIFY receivers 停用/外校/不存在:照常落抄送行并推进,不被审批资格校验收紧")
|
||||
void notifyReceiversRemainTolerant() {
|
||||
mapDept("d11", 101, "甲");
|
||||
FlwDef def = saveAndPublishDef("d11j", "抄送宽容", notifyInvalidUsersDef("d11"));
|
||||
Long instanceId = apply(def, "d11-notify").getInstanceId();
|
||||
|
||||
List<FlwCc> ccs = ccRepository.findByInstanceIdOrderByIdAsc(instanceId);
|
||||
assertThat(ccs).extracting(FlwCc::getUserId).containsExactly(9001, 9002, 9999);
|
||||
assertThat(ccs.get(2).getUserName()).isEmpty();
|
||||
assertThat(instanceRepository.findById(instanceId).get().getCurrentNodes()).isEqualTo("n1");
|
||||
assertThat(taskRepository.findByInstanceIdAndStatus(instanceId, 0)).hasSize(1);
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private void assertFixedRejected(String contentJson, String bizId, String messagePart) {
|
||||
FlwDef def = saveAndPublishDef("d11-" + bizId, "固定人拒绝", contentJson);
|
||||
assertThatThrownBy(() -> apply(def, bizId))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining(messagePart);
|
||||
assertZeroState(bizId);
|
||||
}
|
||||
|
||||
private void assertZeroState(String bizId) {
|
||||
assertThat(instanceRepository.findBySchIdAndBizTypeAndBizId(SCH, "d11", bizId)).isEmpty();
|
||||
assertThat(taskRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
private OapiModels.ApplyResultVo apply(FlwDef def, String bizId) {
|
||||
return apply(def, bizId, (Integer[]) null);
|
||||
}
|
||||
|
||||
private OapiModels.ApplyResultVo apply(FlwDef def, String bizId, Integer... userIds) {
|
||||
OapiModels.ApplyBody body = new OapiModels.ApplyBody();
|
||||
body.setFlowGuid(def.getFlowGuid());
|
||||
body.setBizType("d11");
|
||||
body.setBizId(bizId);
|
||||
body.setBizTitle("D11 " + bizId);
|
||||
body.setSubmitterId(201);
|
||||
body.setSubmitterName("提交人");
|
||||
if (userIds != null && userIds.length > 0) {
|
||||
OapiModels.AssignItem item = new OapiModels.AssignItem();
|
||||
item.setNodeId("n1");
|
||||
item.setUserIds(Arrays.asList(userIds));
|
||||
body.setAssigns(Collections.singletonList(item));
|
||||
}
|
||||
return oapiFlowService.apply(SCH, null, body);
|
||||
}
|
||||
|
||||
private String usersDef(Integer... userIds) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 固定人\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"审批\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":" + ids(userIds) + "},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"n1\"},{\"from\":\"n1\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private String twoFixedNodesDef(Integer n1User, Integer n2User) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 后续固定人\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"首审\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":[" + n1User + "]},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"n2\",\"type\":\"APPROVAL\",\"name\":\"复审\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":[" + n2User + "]},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"n1\"},{\"from\":\"n1\",\"to\":\"n2\"},"
|
||||
+ "{\"from\":\"n2\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private String linearThreeFixedDef(Integer n1User, Integer n2User, Integer n3User) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 三节点\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"首审\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":[" + n1User + "]},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"n2\",\"type\":\"APPROVAL\",\"name\":\"复审\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":[" + n2User + "]},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"n3\",\"type\":\"APPROVAL\",\"name\":\"终审\","
|
||||
+ "\"assignee\":{\"type\":\"USERS\",\"userIds\":[" + n3User + "]},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"n1\"},{\"from\":\"n1\",\"to\":\"n2\"},"
|
||||
+ "{\"from\":\"n2\",\"to\":\"n3\"},{\"from\":\"n3\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private String deptDef(String tag) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 部门\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"审批\","
|
||||
+ "\"assignee\":{\"type\":\"DEPT_KEY\",\"deptKey\":\"" + dk(tag) + "\"},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"n1\"},{\"from\":\"n1\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private String assignableDeptDef(String tag) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 手选\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"审批\","
|
||||
+ "\"assignee\":{\"type\":\"DEPT_KEY\",\"deptKey\":\"" + dk(tag) + "\"},"
|
||||
+ "\"countersign\":\"ANY\",\"assignPolicy\":{\"mode\":\"MULTI\",\"min\":1,\"max\":2}},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"n1\"},{\"from\":\"n1\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private String notifyInvalidUsersDef(String tag) {
|
||||
return "{"
|
||||
+ "\"code\":\"d11\",\"name\":\"D11 抄送宽容\",\"start\":\"start\","
|
||||
+ "\"nodes\":["
|
||||
+ "{\"id\":\"start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"cc1\",\"type\":\"NOTIFY\",\"name\":\"抄送\","
|
||||
+ "\"receivers\":{\"type\":\"USERS\",\"userIds\":[9001,9002,9999]}},"
|
||||
+ "{\"id\":\"n1\",\"type\":\"APPROVAL\",\"name\":\"审批\","
|
||||
+ "\"assignee\":{\"type\":\"DEPT_KEY\",\"deptKey\":\"" + dk(tag) + "\"},\"countersign\":\"ALL\"},"
|
||||
+ "{\"id\":\"end\",\"type\":\"END\"}"
|
||||
+ "],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"cc1\"},{\"from\":\"cc1\",\"to\":\"n1\"},"
|
||||
+ "{\"from\":\"n1\",\"to\":\"end\"}],"
|
||||
+ "\"settings\":{\"rejectPolicy\":\"END_REJECTED\"}}";
|
||||
}
|
||||
|
||||
private static String ids(Integer... userIds) {
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
for (int i = 0; i < userIds.length; i++) {
|
||||
if (i > 0) sb.append(',');
|
||||
sb.append(userIds[i]);
|
||||
}
|
||||
return sb.append(']').toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* SDK 快捷审批 ActorContext 门禁单测(2026-10-25 T07 建立;同日 R1 返修重写):
|
||||
* 仅凭 appKey/operatorId 不构成用户授权——用户证明(Codex C.2 ActorContext 委托)落地前
|
||||
* 快捷审批无条件不放行:<b>不存在放行配置</b>(原 require-user-proof 灰度已废除,
|
||||
* 未配置/false 同样拒绝)。标准 iframe/CAS 人工办理不经本门。
|
||||
*/
|
||||
@DisplayName("SDK 快捷审批 ActorContext 门禁(T07/R1 fail-closed)")
|
||||
class FlActorContextGateTest {
|
||||
|
||||
private static void assertRejected(Long schId, Long taskId, Integer operatorId) {
|
||||
assertThatThrownBy(() -> new FlowActorContextGate().requireActorProof(schId, taskId, operatorId))
|
||||
.as("schId=%s taskId=%s operatorId=%s 应被拒绝", schId, taskId, operatorId)
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("快捷审批未放行")
|
||||
.hasMessageContaining("appKey/operatorId")
|
||||
.hasMessageContaining("人工办理页");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无配置(默认构造):oapi 审批(自报 operatorId)一律拒绝并指明 CAS 迁移路径")
|
||||
void unconfiguredGate_rejectsOperatorOnlyApprovals() {
|
||||
assertRejected(1L, 33L, 201);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("伪造/任意 operatorId(含真实办理人 ID):同样拒绝——知道办理人 ID 不等于该用户本人在操作")
|
||||
void forgedOrGenuineOperatorId_bothRejected() {
|
||||
assertRejected(1L, 33L, 999); // 伪造他人
|
||||
assertRejected(1L, 33L, 201); // 即便自报的就是真实 assigneeId
|
||||
assertRejected(1L, 33L, null); // 缺参不绕过(fail-closed 优先于参数校验)
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("任务/学校不匹配或缺席:拒绝口径一致——门禁先于任务校验,不泄露任务存在性")
|
||||
void mismatchedTaskOrSchool_stillRejected() {
|
||||
assertRejected(2L, 404L, 201); // 跨校/不存在任务
|
||||
assertRejected(null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("门禁无放行分支:不存在任何入参组合通过(CAS 会话路径不经本门,保持人工办理可用)")
|
||||
void noPassThroughBranch_exists() {
|
||||
FlowActorContextGate gate = new FlowActorContextGate();
|
||||
long[] schIds = {1L, 2L, 0L};
|
||||
Long[] taskIds = {1L, 33L, 999L};
|
||||
Integer[] operators = {1, 101, 999, null};
|
||||
for (long sch : schIds) {
|
||||
for (Long task : taskIds) {
|
||||
for (Integer op : operators) {
|
||||
assertThatThrownBy(() -> gate.requireActorProof(sch, task, op))
|
||||
.as("sch=%s task=%s op=%s", sch, task, op)
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.engine.FlowDefModel;
|
||||
import com.yunhai.flowcenter.model.OapiModels;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.base.OpenApiUserClient;
|
||||
import com.yunhai.platform.utils.model.BoaUser;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* T06 发起终审规则单测:required 指派全覆盖(空 assigns 不绕过)、禁用账号拒绝、
|
||||
* EXPRESSION 变量缺失/显式 null 零实例。
|
||||
*/
|
||||
@DisplayName("发起终审:required 指派覆盖 + 禁用人员 + 变量缺失(T06)")
|
||||
class FlApplyAssignAndVariableTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
// ==================== required 覆盖 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("空 assigns + 存在必选指派节点:全部缺失(空 assigns 不绕过 required)")
|
||||
void emptyAssignsWithRequiredNodesIsMissing() throws Exception {
|
||||
FlowDefModel model = FlowDefModel.parse(mapper, defJson(true, false));
|
||||
List<String> missing = OapiFlowService.missingRequiredAssignNodes(model, null);
|
||||
assertThat(missing).containsExactly("n-assign-1");
|
||||
assertThat(OapiFlowService.missingRequiredAssignNodes(model, Collections.emptyList()))
|
||||
.containsExactly("n-assign-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("提交项只覆盖部分必选节点:缺失的逐一点名(不只遍历请求里出现的项)")
|
||||
void partialCoverageIsMissing() throws Exception {
|
||||
FlowDefModel model = FlowDefModel.parse(mapper, defJson(true, true));
|
||||
OapiModels.AssignItem onlyFirst = new OapiModels.AssignItem();
|
||||
onlyFirst.setNodeId("n-assign-1");
|
||||
onlyFirst.setUserIds(java.util.Collections.singletonList(101));
|
||||
List<String> missing = OapiFlowService.missingRequiredAssignNodes(model, java.util.Collections.singletonList(onlyFirst));
|
||||
assertThat(missing).containsExactly("n-assign-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无必选节点 + 空 assigns:放行(既有宽松回退 D3 不变)")
|
||||
void noRequiredNodesEmptyAssignsPasses() throws Exception {
|
||||
FlowDefModel model = FlowDefModel.parse(mapper, defJson(false, false));
|
||||
assertThat(OapiFlowService.missingRequiredAssignNodes(model, null)).isEmpty();
|
||||
}
|
||||
|
||||
// ==================== 变量终审 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("EXPRESSION 引用的业务变量缺失:拒绝(零实例,不等运行期 nil)")
|
||||
void missingExpressionVariableRejected() throws Exception {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel model = modelWithCondition("flowAmount > 100");
|
||||
assertThat(validator.referencedBusinessKeys(model)).containsExactly("flowAmount");
|
||||
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(model, "{\"other\":1}"))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("flowAmount");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("变量为显式 null:拒绝(缺失键与 null 是同一种'没有值')")
|
||||
void nullVariableRejected() throws Exception {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel model = modelWithCondition("flowAmount > 100");
|
||||
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(model, "{\"flowAmount\":null}"))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("flowAmount");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("变量齐备:放行;flow.* 内置键不参与本查")
|
||||
void presentVariablesPassAndBuiltinsIgnored() throws Exception {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel model = modelWithCondition("flowAmount > 100 && flow.submitterId != null");
|
||||
|
||||
validator.requireVariablesPresent(model, "{\"flowAmount\":200}");
|
||||
validator.requireVariablesPresent(model, null);
|
||||
}
|
||||
|
||||
// ==================== 禁用人员终审 ====================
|
||||
|
||||
private FlowDefModel contract(String declarations) {
|
||||
return FlowDefModel.parse(mapper, "{\"nodes\":[],\"edges\":[],\"variables\":" + declarations + "}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredUnknownAndOptionalNullRules() {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel m = contract("[{\"key\":\"reason\",\"type\":\"string\",\"required\":true},"
|
||||
+ "{\"key\":\"optional\",\"type\":\"number\"}]");
|
||||
validator.requireVariablesPresent(m, "{\"reason\":\"ok\",\"optional\":null}");
|
||||
for (String bad : java.util.Arrays.asList("{}", "{\"reason\":null}", "{\"reason\":\"\"}",
|
||||
"{\"reason\":\" \\t\"}", "{\"reason\":\"ok\",\"extra\":1}",
|
||||
"{\"reason\":\"ok\",\"optional\":\"\"}", "[]", "null", "invalid")) {
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(m, bad)).isInstanceOf(BizException.class);
|
||||
}
|
||||
validator.requireVariablesPresent(contract("[]"), null);
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(contract("[]"), "{\"x\":1}"))
|
||||
.isInstanceOf(BizException.class);
|
||||
validator.requireVariablesPresent(contract("[{\"key\":\"text\",\"type\":\"string\"}]"), "{\"text\":\"\"}");
|
||||
validator.requireVariablesPresent(contract("[{\"key\":\"date\",\"type\":\"date\"},"
|
||||
+ "{\"key\":\"grade\",\"type\":\"string\",\"enum\":[\"g1\"]}]"), "{\"date\":\"\",\"grade\":\"\"}");
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest
|
||||
@org.junit.jupiter.params.provider.CsvSource(delimiter = '|', value = {
|
||||
"number|12.5|\"12.5\"", "money|0.01|\"0.01\"", "boolean|true|\"true\"",
|
||||
"date|\"2024-02-29\"|\"2025-02-29\"",
|
||||
"datetime|\"2026-10-26T12:30:00\"|\"2026-10-26 12:30:00\"",
|
||||
"datetime|\"2026-10-26T12:30:00+08:00\"|\"2026-10-26T25:30:00Z\"",
|
||||
"string|\"ok\"|123", "stringArray|[\"x\"]|[1]",
|
||||
"fileArray|[{\"id\":1,\"fileName\":\"a.pdf\",\"key\":\"form/a\"}]|[{\"id\":1}]",
|
||||
"userArray|[{\"id\":101,\"name\":\"A\"}]|[101]"
|
||||
})
|
||||
void realJsonShapesAreCheckedWithoutCoercion(String type, String good, String bad) {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel model = contract("[{\"key\":\"value\",\"type\":\"" + type + "\",\"required\":true}]");
|
||||
validator.requireVariablesPresent(model, "{\"value\":" + good + "}");
|
||||
for (String invalid : java.util.Arrays.asList(bad, "\"\"", "null", "[]")) {
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(model, "{\"value\":" + invalid + "}"))
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void optionalReferencedVariableStillNeedsValueAndLegacyKeepsOldBehavior() throws Exception {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
FlowDefModel m = modelWithCondition("flowAmount > 100");
|
||||
validator.requireVariablesPresent(m, "{\"flowAmount\":\"\",\"extra\":1}"); // 历史行为
|
||||
m.variables = contract("[{\"key\":\"flowAmount\",\"type\":\"number\",\"required\":false}]").variables;
|
||||
for (String bad : java.util.Arrays.asList("{}", "{\"flowAmount\":null}", "{\"flowAmount\":\"\"}")) {
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(m, bad)).isInstanceOf(BizException.class);
|
||||
}
|
||||
validator.requireVariablesPresent(m, "{\"flowAmount\":200}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scalarAndArrayEnumUseFrozenValues() {
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
for (String type : java.util.Arrays.asList("string", "stringArray")) {
|
||||
FlowDefModel model = contract("[{\"key\":\"grade\",\"type\":\"" + type + "\",\"enum\":[\"g1\",\"g2\"]}]");
|
||||
validator.requireVariablesPresent(model, "{\"grade\":" + (type.equals("string") ? "\"g1\"" : "[\"g1\",\"g2\"]") + "}");
|
||||
assertThatThrownBy(() -> validator.requireVariablesPresent(model,
|
||||
"{\"grade\":" + (type.equals("string") ? "\"g9\"" : "[\"g1\",\"g9\"]") + "}"))
|
||||
.isInstanceOf(BizException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void v2SameTokenUsesAcceptedDefinitionBeforeCurrentContractAndVersionChecks() {
|
||||
com.yunhai.flowcenter.repository.FlwDefRepository defs = mock(com.yunhai.flowcenter.repository.FlwDefRepository.class);
|
||||
com.yunhai.flowcenter.repository.FlwInstanceRepository instances = mock(com.yunhai.flowcenter.repository.FlwInstanceRepository.class);
|
||||
com.yunhai.flowcenter.engine.FlowEngine engine = mock(com.yunhai.flowcenter.engine.FlowEngine.class);
|
||||
FlowInstanceService lifecycle = new FlowInstanceService(instances, defs,
|
||||
mock(com.yunhai.flowcenter.repository.FlwTaskRepository.class),
|
||||
mock(com.yunhai.flowcenter.repository.FlwBranchRepository.class), engine,
|
||||
mock(org.springframework.context.ApplicationEventPublisher.class));
|
||||
OapiFlowService service = new OapiFlowService(defs, instances,
|
||||
mock(com.yunhai.flowcenter.repository.FlwTaskRepository.class),
|
||||
mock(com.yunhai.flowcenter.repository.FlwCcRepository.class),
|
||||
mock(com.yunhai.flowcenter.repository.FlwCallbackRegRepository.class), lifecycle,
|
||||
mock(FlowTaskService.class), engine, mock(com.yunhai.flowcenter.engine.AssigneeResolver.class), mapper,
|
||||
mock(OpenApiUserClient.class), mock(com.yunhai.platform.openapi.base.OpenApiAppClient.class),
|
||||
mock(DiagramTokenService.class), mock(org.springframework.beans.factory.ObjectProvider.class));
|
||||
com.yunhai.flowcenter.entity.FlwDef old = new com.yunhai.flowcenter.entity.FlwDef();
|
||||
old.setId(9L); old.setFlowGuid("g"); old.setVersion(1); old.setContentJson("{\"nodes\":[],\"edges\":[],\"variables\":[]}");
|
||||
com.yunhai.flowcenter.entity.FlwDef current = new com.yunhai.flowcenter.entity.FlwDef();
|
||||
current.setId(10L); current.setFlowGuid("g"); current.setVersion(2);
|
||||
current.setContentJson("{\"nodes\":[],\"edges\":[],\"variables\":[{\"key\":\"newRequired\",\"type\":\"string\",\"required\":true}]}");
|
||||
when(defs.findById(9L)).thenReturn(java.util.Optional.of(old));
|
||||
when(defs.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(1L,"g",1)).thenReturn(java.util.Optional.of(current));
|
||||
com.yunhai.flowcenter.entity.FlwInstance row = new com.yunhai.flowcenter.entity.FlwInstance();
|
||||
row.setId(500L); row.setDefId(9L); row.setSchId(1L); row.setStatus(30);
|
||||
row.setSubmitterId(201); row.setApplyAppKey("app"); row.setApplyRequestToken("token"); row.setApplyRound(1);
|
||||
FlowInstanceService.ApplyCommand original = new FlowInstanceService.ApplyCommand(1L, old, "biz", "7", null, null,
|
||||
null, 201, null, null, "app", null, null);
|
||||
row.setApplyPayloadHash(ReflectionTestUtils.invokeMethod(service, "payloadHash", original));
|
||||
when(instances.findBySchIdAndBizTypeAndBizId(1L,"biz","7")).thenReturn(java.util.Optional.of(row));
|
||||
when(instances.findById(500L)).thenReturn(java.util.Optional.of(row));
|
||||
com.yunhai.flowcenter.model.FlowApplyRetryModels.ApplyRequestV2 request = new com.yunhai.flowcenter.model.FlowApplyRetryModels.ApplyRequestV2();
|
||||
request.setFlowGuid("g"); request.setBizType("biz"); request.setBizId("7"); request.setSubmitterId(201);
|
||||
request.setRequestToken("token"); request.setExpectedDefVersion(1);
|
||||
assertThat(service.applyV2(1L,"app",request).getBranch()).isEqualTo("SAME_REQUEST");
|
||||
request.setBizTitle("different payload");
|
||||
assertThatThrownBy(() -> service.applyV2(1L,"app",request)).isInstanceOf(BizException.class);
|
||||
request.setBizTitle(null); request.setFlowGuid("other");
|
||||
assertThatThrownBy(() -> service.applyV2(1L,"app",request)).isInstanceOf(BizException.class);
|
||||
Mockito.verify(instances, Mockito.never()).save(Mockito.any());
|
||||
Mockito.verifyNoInteractions(engine);
|
||||
Mockito.verify(defs, Mockito.never()).findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(Mockito.any(),Mockito.any(),Mockito.any());
|
||||
// 新请求仍过当前契约;v1/v2 均在任何实例/任务写入之前拒绝,手工构造也不能跳过校验。
|
||||
request.setFlowGuid("g"); request.setRequestToken("fresh"); request.setExpectedDefVersion(null);
|
||||
assertThatThrownBy(() -> service.applyV2(1L,"app",request))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("newRequired");
|
||||
assertThatThrownBy(() -> service.apply(1L,"app",request))
|
||||
.isInstanceOf(BizException.class).hasMessageContaining("newRequired");
|
||||
Mockito.verify(instances, Mockito.never()).save(Mockito.any());
|
||||
Mockito.verifyNoInteractions(engine);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("禁用账号(status=0):拒绝(存在≠可办理)")
|
||||
void disabledUserRejected() {
|
||||
com.yunhai.flowcenter.engine.AssigneeResolver resolver =
|
||||
new com.yunhai.flowcenter.engine.AssigneeResolver(
|
||||
mock(com.yunhai.flowcenter.service.FlowDeptAdminService.class),
|
||||
userClient(0));
|
||||
assertThatThrownBy(() -> resolver.requireEligibleAssignee(1L, 101))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("禁用");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("status=null(存量下发未知态):fail-closed 拒绝")
|
||||
void unknownStatusUserRejected() {
|
||||
com.yunhai.flowcenter.engine.AssigneeResolver resolver =
|
||||
new com.yunhai.flowcenter.engine.AssigneeResolver(
|
||||
mock(com.yunhai.flowcenter.service.FlowDeptAdminService.class),
|
||||
userClient(null));
|
||||
assertThatThrownBy(() -> resolver.requireEligibleAssignee(1L, 101))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("禁用");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("正常账号(status=1)且属于本校:放行")
|
||||
void activeUserPasses() {
|
||||
com.yunhai.flowcenter.engine.AssigneeResolver resolver =
|
||||
new com.yunhai.flowcenter.engine.AssigneeResolver(
|
||||
mock(com.yunhai.flowcenter.service.FlowDeptAdminService.class),
|
||||
userClient(1));
|
||||
assertThat(resolver.requireEligibleAssignee(1L, 101).getName()).isEqualTo("甲");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("正常账号但属于外校:拒绝(校域终审)")
|
||||
void crossSchoolUserRejected() {
|
||||
OpenApiUserClient client = mock(OpenApiUserClient.class);
|
||||
BoaUser user = new BoaUser();
|
||||
user.setId(101);
|
||||
user.setName("甲");
|
||||
user.setStatus(1);
|
||||
user.setSchool(new com.yunhai.platform.utils.model.BoaGroup(2, "外校"));
|
||||
when(client.getUserById(Mockito.anyString())).thenReturn(user);
|
||||
com.yunhai.flowcenter.engine.AssigneeResolver resolver =
|
||||
new com.yunhai.flowcenter.engine.AssigneeResolver(
|
||||
mock(com.yunhai.flowcenter.service.FlowDeptAdminService.class), client);
|
||||
assertThatThrownBy(() -> resolver.requireEligibleAssignee(1L, 101))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不属于该学校");
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private OpenApiUserClient userClient(Integer status) {
|
||||
OpenApiUserClient client = mock(OpenApiUserClient.class);
|
||||
BoaUser user = new BoaUser();
|
||||
user.setId(101);
|
||||
user.setName("甲");
|
||||
user.setStatus(status);
|
||||
user.setSchool(new com.yunhai.platform.utils.model.BoaGroup(1, "测试学校"));
|
||||
when(client.getUserById(Mockito.anyString())).thenReturn(user);
|
||||
return client;
|
||||
}
|
||||
|
||||
/** 一个 START + required 指派节点(one/two 个)+ END 的最小定义 */
|
||||
private String defJson(boolean oneRequired, boolean twoRequired) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{\"name\":\"t\",\"start\":\"n-start\",\"nodes\":[");
|
||||
sb.append("{\"id\":\"n-start\",\"type\":\"START\",\"name\":\"开始\"},");
|
||||
sb.append("{\"id\":\"n-assign-1\",\"type\":\"APPROVAL\",\"name\":\"审批一\",")
|
||||
.append("\"assignee\":{\"type\":\"USERS\",\"userIds\":[101]},")
|
||||
.append("\"assignPolicy\":{\"mode\":\"MULTI\",\"required\":").append(oneRequired).append("}},");
|
||||
if (twoRequired) {
|
||||
sb.append("{\"id\":\"n-assign-2\",\"type\":\"APPROVAL\",\"name\":\"审批二\",")
|
||||
.append("\"assignee\":{\"type\":\"USERS\",\"userIds\":[102]},")
|
||||
.append("\"assignPolicy\":{\"mode\":\"MULTI\",\"required\":true}},");
|
||||
}
|
||||
sb.append("{\"id\":\"n-end\",\"type\":\"END\",\"name\":\"结束\"}],");
|
||||
sb.append("\"edges\":[{\"from\":\"n-start\",\"to\":\"n-assign-1\",\"name\":\"提交\"},")
|
||||
.append("{\"from\":\"n-assign-1\",\"to\":\"")
|
||||
.append(twoRequired ? "n-assign-2" : "n-end").append("\",\"name\":\"通过\"}");
|
||||
if (twoRequired) {
|
||||
sb.append(",{\"from\":\"n-assign-2\",\"to\":\"n-end\",\"name\":\"通过\"}");
|
||||
}
|
||||
sb.append("]}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** START → CONDITION(EXPRESSION) → END,条件含给定表达式 */
|
||||
private FlowDefModel modelWithCondition(String condition) throws Exception {
|
||||
String json = "{\"name\":\"t\",\"start\":\"n-start\",\"nodes\":["
|
||||
+ "{\"id\":\"n-start\",\"type\":\"START\",\"name\":\"开始\"},"
|
||||
+ "{\"id\":\"n-cond\",\"type\":\"CONDITION\",\"name\":\"判断\",\"judgeMode\":\"EXPRESSION\"},"
|
||||
+ "{\"id\":\"n-end\",\"type\":\"END\",\"name\":\"结束\"}],"
|
||||
+ "\"edges\":["
|
||||
+ "{\"from\":\"n-start\",\"to\":\"n-cond\",\"name\":\"提交\"},"
|
||||
+ "{\"from\":\"n-cond\",\"to\":\"n-end\",\"name\":\"高额\",\"condition\":\"" + condition + "\"}"
|
||||
+ "]}";
|
||||
return FlowDefModel.parse(mapper, json);
|
||||
}
|
||||
}
|
||||
@@ -138,18 +138,66 @@ class FlApplyRecoveryTest {
|
||||
@Test
|
||||
@DisplayName("10/20 命中不同 token:仍是纯幂等返回(既有语义逐字不变)")
|
||||
void approvingOrCompletedStayIdempotent() {
|
||||
// T04(2026-10-25)改判:带 token 的请求撞在途/通过件且 token 不符 = 另一份命令 →
|
||||
// CONFLICT(不把他人命令的成功当自己的,审计 P0-2);无 token 的存量调用方保持 IDEMPOTENT。
|
||||
FlwInstance approving = instance(900L, FlwEnums.InstanceStatus.APPROVING.getCode(), TOKEN_A, 1, "100018");
|
||||
when(instanceRepository.findBySchIdAndBizTypeAndBizId(SCH, BIZ_TYPE, BIZ_ID))
|
||||
.thenReturn(Optional.of(approving));
|
||||
assertThat(service.applyGuarded(cmd(TOKEN_B), policy(TOKEN_B, 2, false)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.CONFLICT);
|
||||
// 存量无 token:幂等回读不变
|
||||
FlowInstanceService.ApplyCommand legacy = cmd(null);
|
||||
assertThat(service.applyGuarded(legacy, policy(null, null, false)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.IDEMPOTENT);
|
||||
|
||||
FlwInstance completed = instance(900L, FlwEnums.InstanceStatus.COMPLETED.getCode(), TOKEN_A, 1, "100018");
|
||||
assertThat(service.applyGuarded(cmd(TOKEN_B), policy(TOKEN_B, 2, false)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.IDEMPOTENT);
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.CONFLICT);
|
||||
verify(flowEngine, never()).startAdvance(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("同 token 但载荷指纹不一致:CONFLICT(同 ID 不同载荷是两份命令,T04)")
|
||||
void sameTokenDifferentPayloadIsConflict() {
|
||||
FlwInstance existing = instance(900L, FlwEnums.InstanceStatus.REJECTED.getCode(), TOKEN_A, 1, "100018");
|
||||
existing.setApplyPayloadHash("hash-a");
|
||||
when(instanceRepository.findBySchIdAndBizTypeAndBizId(SCH, BIZ_TYPE, BIZ_ID))
|
||||
.thenReturn(Optional.of(existing));
|
||||
|
||||
FlowInstanceService.ApplyCommand replay = cmd(TOKEN_A);
|
||||
replay.payloadHash = "hash-b";
|
||||
assertThat(service.applyGuarded(replay, policy(TOKEN_A, 1, false)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.CONFLICT);
|
||||
|
||||
FlowInstanceService.ApplyCommand identical = cmd(TOKEN_A);
|
||||
identical.payloadHash = "hash-a";
|
||||
assertThat(service.applyGuarded(identical, policy(TOKEN_A, 1, false)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.SAME_REQUEST);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("expectedPrevRound 命中行轮次:服务端只分配 N+1,不信客户端 attempt(T04)")
|
||||
void serverAllocatesNextRoundFromExpectedPrev() {
|
||||
FlwInstance existing = instance(900L, FlwEnums.InstanceStatus.REJECTED.getCode(), TOKEN_A, 2, "100018");
|
||||
when(instanceRepository.findBySchIdAndBizTypeAndBizId(SCH, BIZ_TYPE, BIZ_ID))
|
||||
.thenReturn(Optional.of(existing));
|
||||
|
||||
// 客户端谎报 attempt=99:服务端按 expectedPrev=2 分配第 3 轮
|
||||
FlowInstanceService.GuardedOutcome outcome = service.applyGuarded(
|
||||
cmd(TOKEN_B), new FlowInstanceService.ApplyRetryPolicy(TOKEN_B, 99, false, 2));
|
||||
assertThat(outcome.branch).isEqualTo(FlowApplyRetryModels.Branch.RESTARTED);
|
||||
assertThat(outcome.applyRound).isEqualTo(3);
|
||||
|
||||
// expectedPrev 与行轮次不符:STALE_ROUND 不重启(restart 会原地改 token,这里换新实例)
|
||||
when(instanceRepository.findBySchIdAndBizTypeAndBizId(SCH, BIZ_TYPE, BIZ_ID))
|
||||
.thenReturn(Optional.of(
|
||||
instance(901L, FlwEnums.InstanceStatus.REJECTED.getCode(), TOKEN_A, 2, "100018")));
|
||||
assertThat(service.applyGuarded(cmd(TOKEN_B),
|
||||
new FlowInstanceService.ApplyRetryPolicy(TOKEN_B, 99, false, 1)).branch)
|
||||
.isEqualTo(FlowApplyRetryModels.Branch.STALE_ROUND);
|
||||
verify(flowEngine, org.mockito.Mockito.times(1)).startAdvance(any(), any());
|
||||
}
|
||||
|
||||
// ==================== 轮次守卫 ====================
|
||||
|
||||
@Test
|
||||
@@ -306,7 +354,9 @@ class FlApplyRecoveryTest {
|
||||
when(regs.findBySchIdAndFlowGuidAndStatus(SCH, FLOW_GUID, 0)).thenReturn(java.util.Collections.singletonList(reg));
|
||||
com.yunhai.flowcenter.callback.CallbackDispatcher dispatcher = new com.yunhai.flowcenter.callback.CallbackDispatcher(
|
||||
instanceRepository, defRepository, regs, mock(com.yunhai.flowcenter.repository.FlwCallbackLogRepository.class),
|
||||
store, mock(com.yunhai.flowcenter.callback.CallbackPushService.class), new com.yunhai.flowcenter.callback.CallbackProperties(), mapper);
|
||||
store, mock(com.yunhai.flowcenter.callback.CallbackPushService.class), new com.yunhai.flowcenter.callback.CallbackProperties(), mapper,
|
||||
mock(com.yunhai.flowcenter.repository.FlwStateEventRepository.class),
|
||||
mock(com.yunhai.flowcenter.callback.CallbackFactStore.class));
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(dispatcher, "pushExecutor", mock(java.util.concurrent.ExecutorService.class));
|
||||
dispatcher.onFlowEvent(event);
|
||||
ArgumentCaptor<com.yunhai.flowcenter.entity.FlwCallbackLog> log = ArgumentCaptor.forClass(com.yunhai.flowcenter.entity.FlwCallbackLog.class);
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.engine.AssigneeResolver;
|
||||
import com.yunhai.flowcenter.engine.FlowEngine;
|
||||
import com.yunhai.flowcenter.entity.FlwDef;
|
||||
import com.yunhai.flowcenter.enums.FlwEnums;
|
||||
import com.yunhai.flowcenter.model.FlowApplyRetryModels;
|
||||
import com.yunhai.flowcenter.model.OapiModels;
|
||||
import com.yunhai.flowcenter.repository.FlwCallbackRegRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwCcRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwDefRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwInstanceRepository;
|
||||
import com.yunhai.flowcenter.repository.FlwTaskRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.base.OpenApiAppClient;
|
||||
import com.yunhai.platform.openapi.base.OpenApiUserClient;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 线级停发与发布封存的单测(2026-10-25 T03):
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>线级停发</b>:整线停止新发起/预览;不存在"停发后回退旧版"(停发不是降级);
|
||||
* 在途实例不经新发起解析路径,天然不受影响;恢复只归零标志,不改发布内容。</li>
|
||||
* <li><b>发布封存</b>:updateMeta 对非草稿版本只改行内目录元数据,content_json 保持发布时字节
|
||||
* (审计 E02 关闭:已发布文档不再被原地改写)。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@DisplayName("线级停发/恢复 + 发布封存(T03)")
|
||||
class FlDefLineOfflineTest {
|
||||
|
||||
private static final Long SCH = 1L;
|
||||
private static final String GUID = "g-line";
|
||||
|
||||
private FlwDefRepository defRepository;
|
||||
private FlwDefAdminServiceSpy adminService;
|
||||
private OapiFlowService oapiService;
|
||||
private FlwInstanceRepository instances;
|
||||
private com.yunhai.flowcenter.service.FlowInstanceService instanceService;
|
||||
|
||||
/** 仅暴露 protected/私有依赖注入的薄壳:真实 FlowDefAdminService 构造依赖过多,用 spy 隔离外部协作 */
|
||||
static class FlwDefAdminServiceSpy {
|
||||
final FlwDefRepository defRepository;
|
||||
FlwDefAdminServiceSpy(FlwDefRepository defRepository) {
|
||||
this.defRepository = defRepository;
|
||||
}
|
||||
int offlineLine(Long schId, String flowGuid) {
|
||||
if (flowGuid == null || flowGuid.trim().isEmpty()
|
||||
|| !defRepository.findFirstBySchIdAndFlowGuidOrderByVersionDesc(schId, flowGuid.trim())
|
||||
.isPresent()) {
|
||||
throw new BizException(com.yunhai.platform.utils.exception.ErrorCode.PARAM_ERROR,
|
||||
"流程线不存在:" + flowGuid);
|
||||
}
|
||||
return defRepository.updateLineOffline(schId, flowGuid.trim(), 1);
|
||||
}
|
||||
int enableLine(Long schId, String flowGuid) {
|
||||
if (flowGuid == null || flowGuid.trim().isEmpty()
|
||||
|| !defRepository.findFirstBySchIdAndFlowGuidOrderByVersionDesc(schId, flowGuid.trim())
|
||||
.isPresent()) {
|
||||
throw new BizException(com.yunhai.platform.utils.exception.ErrorCode.PARAM_ERROR,
|
||||
"流程线不存在:" + flowGuid);
|
||||
}
|
||||
return defRepository.updateLineOffline(schId, flowGuid.trim(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings("unchecked")
|
||||
void setUp() {
|
||||
defRepository = mock(FlwDefRepository.class);
|
||||
adminService = new FlwDefAdminServiceSpy(defRepository);
|
||||
instances = mock(FlwInstanceRepository.class);
|
||||
instanceService = mock(FlowInstanceService.class);
|
||||
oapiService = new OapiFlowService(defRepository, instances,
|
||||
mock(FlwTaskRepository.class), mock(FlwCcRepository.class),
|
||||
mock(FlwCallbackRegRepository.class), instanceService, mock(FlowTaskService.class),
|
||||
mock(FlowEngine.class), mock(AssigneeResolver.class), new ObjectMapper(),
|
||||
mock(OpenApiUserClient.class), mock(OpenApiAppClient.class),
|
||||
mock(DiagramTokenService.class), mock(ObjectProvider.class));
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidOrderByVersionDesc(eq(SCH), eq(GUID)))
|
||||
.thenReturn(Optional.of(def(9, 3, 0)));
|
||||
}
|
||||
|
||||
// ==================== 线级停发/恢复(管理面委托) ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("offlineLine:批量置 1;enableLine:批量归零")
|
||||
void lineOfflineDelegatesBulkUpdate() {
|
||||
when(defRepository.updateLineOffline(SCH, GUID, 1)).thenReturn(3);
|
||||
assertThat(adminService.offlineLine(SCH, GUID)).isEqualTo(3);
|
||||
verify(defRepository).updateLineOffline(SCH, GUID, 1);
|
||||
|
||||
when(defRepository.updateLineOffline(SCH, GUID, 0)).thenReturn(3);
|
||||
assertThat(adminService.enableLine(SCH, GUID)).isEqualTo(3);
|
||||
verify(defRepository).updateLineOffline(SCH, GUID, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("不存在的流程线:拒绝且不出更新")
|
||||
void unknownLineRejected() {
|
||||
assertThatThrownBy(() -> adminService.offlineLine(SCH, "g-nope"))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("流程线不存在");
|
||||
verify(defRepository, never()).updateLineOffline(anyLong(), anyString(), anyInt());
|
||||
}
|
||||
|
||||
// ==================== 新发起/预览的线级守卫 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("线停发:applyV2 新发起被拒且不建实例(不回退旧版)")
|
||||
void applyRejectedWhenLineOffline() {
|
||||
FlwDef offline = def(9, 3, 1);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq(GUID), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(offline));
|
||||
|
||||
FlowApplyRetryModels.ApplyRequestV2 body = new FlowApplyRetryModels.ApplyRequestV2();
|
||||
body.setFlowGuid(GUID);
|
||||
body.setBizType("svc-hall");
|
||||
body.setBizId("42");
|
||||
body.setSubmitterId(7);
|
||||
|
||||
assertThatThrownBy(() -> oapiService.applyV2(SCH, "100018", body))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("停发");
|
||||
verify(instanceService, never()).applyGuarded(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("线在线:新发起照常解析最高已发布版")
|
||||
void applyPassesWhenLineOnline() {
|
||||
FlwDef online = def(9, 3, 0);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq(GUID), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(online));
|
||||
when(instanceService.applyGuarded(any(), any()))
|
||||
.thenReturn(new FlowInstanceService.GuardedOutcome(
|
||||
500L, false, FlowApplyRetryModels.Branch.CREATED, 1));
|
||||
|
||||
FlowApplyRetryModels.ApplyRequestV2 body = new FlowApplyRetryModels.ApplyRequestV2();
|
||||
body.setFlowGuid(GUID);
|
||||
body.setBizType("svc-hall");
|
||||
body.setBizId("42");
|
||||
body.setSubmitterId(7);
|
||||
|
||||
FlowApplyRetryModels.ApplyResultV2 vo = oapiService.applyV2(SCH, "100018", body);
|
||||
assertThat(vo.getInstanceId()).isEqualTo(500L);
|
||||
ArgumentCaptor<FlowInstanceService.ApplyCommand> cmd =
|
||||
ArgumentCaptor.forClass(FlowInstanceService.ApplyCommand.class);
|
||||
verify(instanceService).applyGuarded(cmd.capture(), any());
|
||||
assertThat(cmd.getValue().def.getId()).isEqualTo(9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("预览同口径:线停发拒绝(选人预览不是新发起旁路)")
|
||||
void previewRejectedWhenLineOffline() {
|
||||
FlwDef offline = def(9, 3, 1);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq(GUID), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(offline));
|
||||
|
||||
assertThatThrownBy(() -> oapiService.applyPreview(SCH, GUID, 7))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("停发");
|
||||
}
|
||||
|
||||
// ==================== 发布封存(updateMeta) ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("updateMeta 对已发布版本:行 name/appKey 可改,content_json 保持发布字节")
|
||||
void updateMetaFreezesPublishedDocument() throws Exception {
|
||||
FlowDefAdminService service = newFlowDefAdminService();
|
||||
FlwDef published = def(9, 3, FlwEnums.DefStatus.PUBLISHED.getCode());
|
||||
published.setName("旧名");
|
||||
String originalJson = published.getContentJson();
|
||||
when(defRepository.findById(9L)).thenReturn(Optional.of(published));
|
||||
when(defRepository.save(any())).thenAnswer(c -> c.getArgument(0));
|
||||
ReflectionTestUtils.setField(service, "appRepository", appRepo(true));
|
||||
|
||||
FlwDef saved = service.updateMeta(SCH, 9L, "新名", null);
|
||||
|
||||
assertThat(saved.getName()).isEqualTo("新名");
|
||||
assertThat(saved.getContentJson()).isEqualTo(originalJson);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("updateMeta 对草稿:content_json 顶层 name 照旧同步(草稿文档可变)")
|
||||
void updateMetaStillSyncsDraftDocument() throws Exception {
|
||||
FlowDefAdminService service = newFlowDefAdminService();
|
||||
FlwDef draft = def(9, 3, 0);
|
||||
draft.setStatus(FlwEnums.DefStatus.DRAFT.getCode());
|
||||
draft.setName("旧名");
|
||||
draft.setContentJson("{\"name\":\"旧名\",\"nodes\":[],\"edges\":[]}");
|
||||
when(defRepository.findById(9L)).thenReturn(Optional.of(draft));
|
||||
when(defRepository.save(any())).thenAnswer(c -> c.getArgument(0));
|
||||
ReflectionTestUtils.setField(service, "appRepository", appRepo(true));
|
||||
|
||||
FlwDef saved = service.updateMeta(SCH, 9L, "新名", null);
|
||||
|
||||
assertThat(saved.getContentJson()).contains("\"新名\"");
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private FlowDefAdminService newFlowDefAdminService() {
|
||||
// 依赖协作全部 mock(构造器形参多,反射装配与生产 Spring 无关,只测本类逻辑)
|
||||
return new FlowDefAdminService(
|
||||
defRepository,
|
||||
mock(com.yunhai.flowcenter.repository.FlwRouterRepository.class),
|
||||
mock(com.yunhai.flowcenter.repository.FlwCallbackRegRepository.class),
|
||||
appRepo(true),
|
||||
mock(com.yunhai.flowcenter.repository.FlwInstanceRepository.class),
|
||||
mock(FlowDeptAdminService.class),
|
||||
mock(FlowEngine.class),
|
||||
new ObjectMapper(),
|
||||
mock(FormCenterSchemaClient.class));
|
||||
}
|
||||
|
||||
private com.yunhai.flowcenter.repository.FlwAppRepository appRepo(boolean enabled) {
|
||||
com.yunhai.flowcenter.repository.FlwAppRepository repo =
|
||||
mock(com.yunhai.flowcenter.repository.FlwAppRepository.class);
|
||||
when(repo.isEnabledApp(anyLong(), anyString())).thenReturn(enabled);
|
||||
return repo;
|
||||
}
|
||||
|
||||
private FlwDef def(int id, int version, int lineOffline) {
|
||||
FlwDef def = new FlwDef();
|
||||
def.setId((long) id);
|
||||
def.setSchId(SCH);
|
||||
def.setFlowGuid(GUID);
|
||||
def.setCode("leave");
|
||||
def.setName("请假");
|
||||
def.setVersion(version);
|
||||
def.setStatus(FlwEnums.DefStatus.PUBLISHED.getCode());
|
||||
def.setLineOffline(lineOffline);
|
||||
def.setContentJson("{\"nodes\":[], \"edges\":[], \"start\":\"n1\"}");
|
||||
return def;
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,7 @@ class FlFormBindingTest {
|
||||
f.put("key", key);
|
||||
f.put("type", type);
|
||||
f.put("required", Boolean.FALSE);
|
||||
if ("select".equals(type)) f.put("enum", Arrays.asList("g1", "g2"));
|
||||
return f;
|
||||
}
|
||||
|
||||
@@ -328,6 +329,7 @@ class FlFormBindingTest {
|
||||
@DisplayName("未关联表单的流程:一次都不碰表单中心")
|
||||
void noBindingNoCall() {
|
||||
FlwDef def = draft(null, null);
|
||||
def.setContentJson("{\"variables\":[{\"key\":\"days\",\"type\":\"number\"},{\"key\":\"grade\",\"type\":\"string\"}]," + FLOW_JSON.substring(1));
|
||||
when(defRepository.findById(9L)).thenReturn(Optional.of(def));
|
||||
|
||||
service.publish(SCH, 9L);
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.entity.FlwInstance;
|
||||
import com.yunhai.flowcenter.entity.FlwUsageGrant;
|
||||
import com.yunhai.flowcenter.enums.FlwEnums;
|
||||
import com.yunhai.flowcenter.repository.FlwUsageGrantRepository;
|
||||
import com.yunhai.platform.apistd.BizException;
|
||||
import com.yunhai.platform.openapi.base.OpenApiAppClient;
|
||||
import com.yunhai.platform.openapi.core.YschOpenCall;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 应用使用许可闸与恢复感知判定的单测(2026-10-25 T01)。
|
||||
*
|
||||
* <p>钉住的不变量:</p>
|
||||
* <ul>
|
||||
* <li><b>新发起必须有生效许可</b>:无行/已撤销/主体解析失败/未在学校开通/核验不可达——五路全拒;</li>
|
||||
* <li><b>已受理命令回执可恢复</b>:同 token、retryOnly 探询、在途/通过幂等、陈旧轮次四类
|
||||
* 回执分支不触许可闸(P0-3 收口顺序:认证 → 回执 → 未命中才查资格);</li>
|
||||
* <li><b>appKey 不是主体</b>:appKey 可重置/复用,许可与审计挂 UserBase 稳定主键 appId。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@DisplayName("应用使用许可闸 FlowUsageGrantGuard + apply 恢复感知判定(T01)")
|
||||
class FlUsageGrantTest {
|
||||
|
||||
private static final long SCH = 27L;
|
||||
private static final String FLOW = "fg-1";
|
||||
private static final String APP_KEY = "100018";
|
||||
|
||||
private FlwUsageGrantRepository grantRepository;
|
||||
private OpenApiAppClient appClient;
|
||||
private YschOpenCall openCall;
|
||||
private UserBaseActivationClient activationClient;
|
||||
private FlowUsageGrantGuard guard;
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
grantRepository = mock(FlwUsageGrantRepository.class);
|
||||
appClient = mock(OpenApiAppClient.class);
|
||||
openCall = mock(YschOpenCall.class);
|
||||
activationClient = new UserBaseActivationClient(openCall);
|
||||
guard = new FlowUsageGrantGuard(grantRepository, activationClient);
|
||||
ReflectionTestUtils.setField(guard, "appClient", appClient);
|
||||
ReflectionTestUtils.setField(activationClient, "enforce", true);
|
||||
}
|
||||
|
||||
// ==================== Guard:新发起资格 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("enforce 关闭:直通且不出站(灰度期存量行为不变)")
|
||||
void enforceOffPassesThrough() {
|
||||
ReflectionTestUtils.setField(activationClient, "enforce", false);
|
||||
|
||||
assertThat(guard.requireNewApplyGrant(SCH, FLOW, APP_KEY)).isNull();
|
||||
verify(grantRepository, never()).findBySchIdAndFlowGuidAndAppId(anyLong(), anyString(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无许可行:拒绝新发起")
|
||||
void noGrantRowRejected() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> guard.requireNewApplyGrant(SCH, FLOW, APP_KEY))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("使用许可");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("许可已撤销(enabled=0):拒绝新发起")
|
||||
void revokedGrantRejected() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001))
|
||||
.thenReturn(Optional.of(grant(5001, 0)));
|
||||
|
||||
assertThatThrownBy(() -> guard.requireNewApplyGrant(SCH, FLOW, APP_KEY))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("使用许可");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("有生效许可且该校开通:放行并返回稳定主体 appId")
|
||||
void grantedAndActivatedPasses() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001))
|
||||
.thenReturn(Optional.of(grant(5001, 1)));
|
||||
stubActivation(5001, true);
|
||||
|
||||
assertThat(guard.requireNewApplyGrant(SCH, FLOW, APP_KEY)).isEqualTo(5001);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("持本地许可但未在学校开通(平台 schId=0 平台资源同口径):拒绝")
|
||||
void grantedButNotActivatedRejected() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001))
|
||||
.thenReturn(Optional.of(grant(5001, 1)));
|
||||
stubActivation(5001, false);
|
||||
|
||||
assertThatThrownBy(() -> guard.requireNewApplyGrant(SCH, FLOW, APP_KEY))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("开通");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("UserBase 资格核验不可达:fail-closed 拒绝(不降级为仅本地 grant 即放行)")
|
||||
void activationUnreachableFailClosed() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001))
|
||||
.thenReturn(Optional.of(grant(5001, 1)));
|
||||
when(openCall.get(anyString(), anyString(), any(), any()))
|
||||
.thenThrow(new RuntimeException("connection refused"));
|
||||
|
||||
assertThatThrownBy(() -> guard.requireNewApplyGrant(SCH, FLOW, APP_KEY))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("不可用");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("appKey 解析不出稳定主体:拒绝(凭据索引不构成主体)")
|
||||
void unresolvablePrincipalRejected() {
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> guard.requireNewApplyGrant(SCH, FLOW, APP_KEY))
|
||||
.isInstanceOf(BizException.class)
|
||||
.hasMessageContaining("主体");
|
||||
}
|
||||
|
||||
// ==================== apply 恢复感知判定(OapiFlowService 纯函数) ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("v1 判定:在途/通过=回执放行;无实例/终态件=需许可")
|
||||
void legacyApplyReceiptDecision() {
|
||||
assertThat(OapiFlowService.legacyApplyIsReceiptOnly(null)).isFalse();
|
||||
assertThat(OapiFlowService.legacyApplyIsReceiptOnly(
|
||||
instance(FlwEnums.InstanceStatus.APPROVING.getCode()))).isTrue();
|
||||
assertThat(OapiFlowService.legacyApplyIsReceiptOnly(
|
||||
instance(FlwEnums.InstanceStatus.COMPLETED.getCode()))).isTrue();
|
||||
assertThat(OapiFlowService.legacyApplyIsReceiptOnly(
|
||||
instance(FlwEnums.InstanceStatus.REJECTED.getCode()))).isFalse();
|
||||
assertThat(OapiFlowService.legacyApplyIsReceiptOnly(
|
||||
instance(FlwEnums.InstanceStatus.WITHDRAWN.getCode()))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("v2 判定:同 token/retryOnly/在途/陈旧轮次=回执;无实例或更高轮次=新申报")
|
||||
void guardedApplyReceiptDecision() {
|
||||
FlwInstance terminal = instance(FlwEnums.InstanceStatus.REJECTED.getCode());
|
||||
terminal.setApplyRequestToken("tok-a");
|
||||
terminal.setApplyRound(2);
|
||||
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(null, "tok-a", 3, false)).isFalse();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(terminal, "tok-a", 9, false)).isTrue();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(terminal, "tok-b", 9, true)).isTrue();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(
|
||||
instance(FlwEnums.InstanceStatus.APPROVING.getCode()), "tok-b", 9, false)).isTrue();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(terminal, "tok-b", 2, false)).isTrue();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(terminal, "tok-b", 3, false)).isFalse();
|
||||
assertThat(OapiFlowService.guardedApplyIsReceiptOnly(terminal, null, null, false)).isTrue();
|
||||
}
|
||||
|
||||
// ==================== 管理面:授予/撤销 ====================
|
||||
|
||||
@Test
|
||||
@DisplayName("授予:appKey 当场解析成稳定主体落库;重申复用同一行")
|
||||
void grantResolvesPrincipalAndUpserts() {
|
||||
// 本测主体解析与 upsert,不开资格闸(开通闸已由 Guard 用例钉住)
|
||||
ReflectionTestUtils.setField(activationClient, "enforce", false);
|
||||
FlowUsageGrantAdminService admin =
|
||||
new FlowUsageGrantAdminService(grantRepository, activationClient);
|
||||
ReflectionTestUtils.setField(admin, "appClient", appClient);
|
||||
when(appClient.getAppByKey(APP_KEY)).thenReturn(registration(5001));
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001)).thenReturn(Optional.empty());
|
||||
when(grantRepository.save(any())).thenAnswer(c -> c.getArgument(0));
|
||||
|
||||
FlwUsageGrant saved = admin.grant(SCH, FLOW, APP_KEY, "首次授权", "admin");
|
||||
|
||||
assertThat(saved.getAppId()).isEqualTo(5001);
|
||||
assertThat(saved.getEnabled()).isEqualTo(1);
|
||||
assertThat(saved.getAppKeySnapshot()).isEqualTo(APP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("撤销:enabled=0 行保留(审计与幂等判据不删)")
|
||||
void revokeKeepsRow() {
|
||||
FlowUsageGrantAdminService admin =
|
||||
new FlowUsageGrantAdminService(grantRepository, activationClient);
|
||||
FlwUsageGrant existing = grant(5001, 1);
|
||||
when(grantRepository.findBySchIdAndFlowGuidAndAppId(SCH, FLOW, 5001))
|
||||
.thenReturn(Optional.of(existing));
|
||||
when(grantRepository.save(any())).thenAnswer(c -> c.getArgument(0));
|
||||
|
||||
FlwUsageGrant saved = admin.revoke(SCH, FLOW, 5001, "违规使用", "admin");
|
||||
|
||||
assertThat(saved.getEnabled()).isEqualTo(0);
|
||||
assertThat(saved.getId()).isNotNull();
|
||||
}
|
||||
|
||||
// ==================== fixtures ====================
|
||||
|
||||
private JsonNode registration(int appId) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("id", appId);
|
||||
row.put("appKey", APP_KEY);
|
||||
row.put("appName", "测试应用");
|
||||
return mapper.valueToTree(row);
|
||||
}
|
||||
|
||||
private void stubActivation(int appId, boolean activated) {
|
||||
Map<String, Object> vo = new HashMap<>();
|
||||
vo.put("appId", appId);
|
||||
vo.put("schoolId", SCH);
|
||||
vo.put("activated", activated);
|
||||
Mockito.when(openCall.get(anyString(), anyString(), any(), any()))
|
||||
.thenReturn(mapper.valueToTree(vo));
|
||||
}
|
||||
|
||||
private FlwUsageGrant grant(int appId, int enabled) {
|
||||
FlwUsageGrant g = new FlwUsageGrant();
|
||||
g.setId(71L);
|
||||
g.setSchId(SCH);
|
||||
g.setFlowGuid(FLOW);
|
||||
g.setAppId(appId);
|
||||
g.setAppKeySnapshot(APP_KEY);
|
||||
g.setEnabled(enabled);
|
||||
return g;
|
||||
}
|
||||
|
||||
private FlwInstance instance(int status) {
|
||||
FlwInstance i = new FlwInstance();
|
||||
i.setId(900L);
|
||||
i.setSchId(SCH);
|
||||
i.setStatus(status);
|
||||
return i;
|
||||
}
|
||||
}
|
||||
+114
-6
@@ -202,16 +202,124 @@ class FlowDefAdminServicePublishContractTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyDefWithoutFormUuidSkipsSnapshotEntirely() {
|
||||
void newUnboundVersionCannotOmitVariables() {
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(draft(null)));
|
||||
|
||||
FlwDef published = service.publish(SCH, 9L);
|
||||
|
||||
assertEquals(FlwEnums.DefStatus.PUBLISHED.getCode(), published.getStatus());
|
||||
assertEquals(JSON, published.getContentJson(), "存量线 content_json 一字不动");
|
||||
assertTrue(assertThrows(BizException.class, () -> service.publish(SCH, 9L))
|
||||
.getMessage().contains("必须声明 variables"));
|
||||
verify(defRepository, never()).save(any());
|
||||
verify(schemaClient, never()).fetchSchema(anyLong(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void draftCannotBypassPublishContractThroughOfflineAndEnable() {
|
||||
FlwDef d = draft(null);
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
assertThrows(BizException.class, () -> service.offline(SCH, 9L));
|
||||
assertThrows(BizException.class, () -> service.enable(SCH, 9L));
|
||||
assertEquals(FlwEnums.DefStatus.DRAFT.getCode(), d.getStatus());
|
||||
verify(defRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unboundDeclarationsUseSameRulesAsFrozenFcDeclarations() throws Exception {
|
||||
FlwDef bound = draft("FU1");
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(bound));
|
||||
when(schemaClient.fetchSchema(SCH, "FU1", 3)).thenReturn(snapshot());
|
||||
String published = service.publish(SCH, 9L).getContentJson();
|
||||
FlwDef unbound = draft(null);
|
||||
unbound.setContentJson(published);
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(unbound));
|
||||
service.publish(SCH, 9L);
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
for (FlwDef d : Arrays.asList(bound, unbound)) {
|
||||
com.yunhai.flowcenter.engine.FlowDefModel model = com.yunhai.flowcenter.engine.FlowDefModel.parse(mapper, d.getContentJson());
|
||||
validator.requireVariablesPresent(model, "{\"days\":4,\"grade\":\"g1\",\"reason\":\"ok\"}");
|
||||
for (String bad : Arrays.asList("{\"days\":4,\"grade\":\"g1\"}",
|
||||
"{\"days\":4,\"grade\":\"g9\",\"reason\":\"ok\"}",
|
||||
"{\"days\":\"4\",\"grade\":\"g1\",\"reason\":\"ok\"}",
|
||||
"{\"days\":4,\"grade\":\"g1\",\"reason\":\"ok\",\"extra\":1}")) {
|
||||
assertThrows(BizException.class, () -> validator.requireVariablesPresent(model, bad));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void enableUsesFrozenContractAndDoesNotReplaceItFromRemoteSchema() {
|
||||
FlwDef d = draft("FU1");
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
when(schemaClient.fetchSchema(SCH, "FU1", 3)).thenReturn(snapshot());
|
||||
service.publish(SCH, 9L);
|
||||
String frozen = d.getContentJson();
|
||||
d.setStatus(FlwEnums.DefStatus.DISABLED.getCode());
|
||||
Map<String, Object> changed = snapshot();
|
||||
changed.put("fields", Arrays.asList(field("other", "text", true, null)));
|
||||
when(schemaClient.fetchSchema(SCH, "FU1", 3)).thenReturn(changed);
|
||||
service.enable(SCH, 9L);
|
||||
assertEquals(frozen, d.getContentJson());
|
||||
d.setStatus(FlwEnums.DefStatus.DISABLED.getCode());
|
||||
d.setContentJson(frozen.replace("grade == 'g1'", "grade == 'g9'"));
|
||||
assertThrows(BizException.class, () -> service.enable(SCH, 9L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void historicalDisabledVersionWithoutDeclarationsCanBeEnabledUnchanged() {
|
||||
FlwDef d = draft(null);
|
||||
d.setStatus(FlwEnums.DefStatus.DISABLED.getCode());
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
service.enable(SCH, 9L);
|
||||
assertEquals(JSON, d.getContentJson());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fcVariablesAreDerivedEvenIfDraftTriesToSupplyEmptyDeclarations() throws Exception {
|
||||
FlwDef d = draft("FU1");
|
||||
d.setContentJson(JSON.replaceFirst("\\{", "{\"variables\":[],"));
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
when(schemaClient.fetchSchema(SCH, "FU1", 3)).thenReturn(snapshot());
|
||||
service.publish(SCH, 9L);
|
||||
JsonNode vars = mapper.readTree(d.getContentJson()).path("variables");
|
||||
assertEquals(3, vars.size());
|
||||
assertEquals("number", vars.get(0).path("type").asText());
|
||||
assertTrue(vars.get(2).path("required").asBoolean());
|
||||
assertEquals("g1", vars.get(1).path("enum").get(0).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allFcTypesPreserveActualSerializedShapes() {
|
||||
java.util.ArrayList<Map<String, Object>> fields = new java.util.ArrayList<>();
|
||||
for (String type : Arrays.asList("text", "textarea", "phone", "number", "date", "select", "radio",
|
||||
"checkbox", "multiselect", "upload", "image", "address", "user", "users")) {
|
||||
fields.add(field(type, type, false, Arrays.asList("select", "radio", "checkbox", "multiselect").contains(type)
|
||||
? Arrays.asList("v1", "v2") : null));
|
||||
}
|
||||
Map<String, Object> snap = snapshot(); snap.put("fields", fields);
|
||||
FlwDef d = draft("FU1");
|
||||
d.setContentJson(JSON.replace("days > 3 && schId > 0", "schId > 0").replace("grade == 'g1'", "true"));
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
when(schemaClient.fetchSchema(SCH, "FU1", 3)).thenReturn(snap);
|
||||
service.publish(SCH, 9L);
|
||||
com.yunhai.flowcenter.engine.FlowDefModel model = com.yunhai.flowcenter.engine.FlowDefModel.parse(mapper, d.getContentJson());
|
||||
ApplyVariableValidator validator = new ApplyVariableValidator(mapper);
|
||||
validator.requireVariablesPresent(model, "{\"text\":\"ok\",\"textarea\":\"ok\",\"phone\":\"123\",\"number\":1.5,"
|
||||
+ "\"date\":\"2024-02-29\",\"select\":\"v1\",\"radio\":\"v2\",\"checkbox\":[\"v1\"],\"multiselect\":[\"v2\"],"
|
||||
+ "\"upload\":[{\"id\":1,\"fileName\":\"a.pdf\",\"key\":\"form/a\"}],\"image\":[],\"address\":[\"广东省\"],"
|
||||
+ "\"user\":[{\"id\":101,\"name\":\"A\"}],\"users\":[]}");
|
||||
validator.requireVariablesPresent(model, "{\"date\":\"\",\"select\":\"\",\"number\":null,\"checkbox\":[]}");
|
||||
assertThrows(BizException.class, () -> validator.requireVariablesPresent(model, "{\"checkbox\":[\"forged\"]}"));
|
||||
assertThrows(BizException.class, () -> validator.requireVariablesPresent(model, "{\"number\":\"\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unboundEmptyDeclarationsCannotHideExpressionReferencesAndNullCannotOptOut() {
|
||||
for (String variables : Arrays.asList("[]", "null")) {
|
||||
FlwDef d = draft(null);
|
||||
d.setContentJson("{\"variables\":" + variables + "," + JSON.substring(1));
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(d));
|
||||
assertThrows(BizException.class, () -> service.publish(SCH, 9L));
|
||||
}
|
||||
verify(defRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void schemaUnavailableBlocksPublishAsRetryableBizError() {
|
||||
when(defRepository.findById(9L)).thenReturn(java.util.Optional.of(draft("FU1")));
|
||||
|
||||
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -64,7 +65,9 @@ class FlowDefAdminServiceUpdateMetaTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void 三不变_contentJson仅顶层name() throws Exception {
|
||||
void 已发布版本_contentJson封存_仅行内元数据可改() throws Exception {
|
||||
// T03(2026-10-25)发布封存:执行文档不可变——行 name 照改(目录元数据),
|
||||
// content_json 顶层 name 保持发布时字节(旧断言"同步改 JSON"已按新原则作废)
|
||||
String json = "{\"code\":\"work-leave\",\"name\":\"旧名\",\"start\":\"start\","
|
||||
+ "\"nodes\":[{\"id\":\"start\",\"type\":\"START\"}],"
|
||||
+ "\"edges\":[{\"from\":\"start\",\"to\":\"end\"}]}";
|
||||
@@ -79,23 +82,36 @@ class FlowDefAdminServiceUpdateMetaTest {
|
||||
assertEquals("work-leave", saved.getCode());
|
||||
assertEquals("新名称", saved.getName());
|
||||
assertEquals("100008", saved.getAppKey());
|
||||
assertEquals("新名称", new ObjectMapper().readTree(saved.getContentJson()).path("name").asText());
|
||||
// 结构零改动:节点/边/其余顶层字段原样保留
|
||||
// 发布字节冻结:文档内 name 不随目录改名漂移
|
||||
assertEquals("旧名", new ObjectMapper().readTree(saved.getContentJson()).path("name").asText());
|
||||
assertEquals("work-leave", new ObjectMapper().readTree(saved.getContentJson()).path("code").asText());
|
||||
assertTrue(saved.getContentJson().contains("\"type\":\"START\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contentJson无顶层name_补写() throws Exception {
|
||||
void 已发布版本_无顶层name_不补写() throws Exception {
|
||||
// 发布封存:缺顶层 name 的已发布文档维持原样,不补写
|
||||
FlwDef def = published("{\"code\":\"c\",\"start\":\"start\",\"nodes\":[],\"edges\":[]}");
|
||||
when(defRepository.findById(9L)).thenReturn(Optional.of(def));
|
||||
|
||||
FlwDef saved = service.updateMeta(SCH, 9L, "补写名", null);
|
||||
|
||||
assertEquals("补写名", new ObjectMapper().readTree(saved.getContentJson()).path("name").asText());
|
||||
assertFalse(new ObjectMapper().readTree(saved.getContentJson()).has("name"));
|
||||
assertNull(saved.getAppKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 草稿版本_contentJson顶层name仍同步() throws Exception {
|
||||
// 草稿文档可变:顶层 name 同步保留(与发布封存互为边界)
|
||||
FlwDef def = published("{\"code\":\"c\",\"name\":\"旧名\",\"start\":\"start\",\"nodes\":[],\"edges\":[]}");
|
||||
def.setStatus(0); // DRAFT
|
||||
when(defRepository.findById(9L)).thenReturn(Optional.of(def));
|
||||
|
||||
FlwDef saved = service.updateMeta(SCH, 9L, "草稿新名", null);
|
||||
|
||||
assertEquals("草稿新名", new ObjectMapper().readTree(saved.getContentJson()).path("name").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void appKey白名单外_被拦() {
|
||||
when(appRepository.isEnabledApp(SCH, "888888")).thenReturn(false);
|
||||
|
||||
+36
-50
@@ -29,8 +29,8 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* F5-4 僵尸逃生门(useLatestDef):v1 表达式必失败挂起 → 默认重跑仍按 v1 快照(行为逐字不变);
|
||||
* useLatestDef=true 改取当前已发布最高版本 v2 → 快照刷新 + trace 留痕 + 引擎按 v2 续走;
|
||||
* T03 在途锁版(2026-10-25):默认重跑按 v1 快照(行为逐字不变);useLatestDef=true 已按
|
||||
* "在途实例固定原版本"原则停用——显式拒绝并说明替代路径,不静默切换;
|
||||
* 在途 CONDITION 节点在新定义不存在时报人类可读业务错。锚定 128/129 僵尸案例。
|
||||
*/
|
||||
@DisplayName("reroute useLatestDef(F5-4 僵尸逃生门)")
|
||||
@@ -116,57 +116,43 @@ class FlowRouterAdminServiceRerouteDefTest {
|
||||
assertTrue(e.getMessage().contains("判断仍失败"), "v1 必失败场景默认重跑仍失败挂起(逃生门入口即为此)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void useLatestDefSwitchesToV2AndRefreshesSnapshotWithTrace() {
|
||||
FlwDef v1 = def(11L, 1, V1);
|
||||
FlwDef v2 = def(12L, 2, V2_WITH_COND);
|
||||
FlwInstance instance = parkedInstance(v1);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq("g-zombie"), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(v2));
|
||||
// ==================== T03 在途锁版(2026-10-25):useLatestDef 旁路停用 ====================
|
||||
|
||||
service.reroute(SCH, 500L, true);
|
||||
@Test
|
||||
void useLatestDefIsRejectedByDesign() {
|
||||
// 在途实例固定原版本(主方案 §1.3 / T03):新发布版只影响新申报,不再提供"切最新版续走"旁路;
|
||||
// 挂起件按原定义重跑,修复后的表达式按原版本重新发布生效
|
||||
FlwDef v1 = def(11L, 1, V1);
|
||||
parkedInstance(v1);
|
||||
|
||||
BizException e = assertThrows(BizException.class, () -> service.reroute(SCH, 500L, true));
|
||||
assertTrue(e.getMessage().contains("在途换版已停用"),
|
||||
"useLatestDef=true 必须显式拒绝并给出替代路径说明,不能静默忽略");
|
||||
verify(flowEngine, never()).rerouteCondition(any(), any(), any());
|
||||
verify(defRepository, never())
|
||||
.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(any(), any(), any());
|
||||
verify(taskRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void useLatestDefRejectionHappensBeforeAnyLookup() {
|
||||
// 显式拒绝发生在任何查询之前:即使办件 id 不存在也是同一个"已停用"错(不泄存在性、不误查)
|
||||
BizException e = assertThrows(BizException.class, () -> service.reroute(SCH, 99999L, true));
|
||||
assertTrue(e.getMessage().contains("在途换版已停用"));
|
||||
verify(instanceRepository, never()).findById(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultRerouteStillWorksAfterLockdown() {
|
||||
// 旁路停用不影响默认路径:按原版本快照重跑照常
|
||||
FlwDef v1 = def(11L, 1, V1);
|
||||
FlwInstance instance = parkedInstance(v1);
|
||||
|
||||
service.reroute(SCH, 500L, false);
|
||||
|
||||
ArgumentCaptor<FlwDef> defCap = ArgumentCaptor.forClass(FlwDef.class);
|
||||
verify(flowEngine).rerouteCondition(any(), defCap.capture(), eq("n1"));
|
||||
assertEquals(12L, defCap.getValue().getId(), "useLatestDef=true 引擎按 v2 续走");
|
||||
assertEquals(12L, instance.getDefId(), "定义快照三列同步刷新(R4 同语义)");
|
||||
assertEquals(Integer.valueOf(2), instance.getDefVersion());
|
||||
ArgumentCaptor<FlwTask> trace = ArgumentCaptor.forClass(FlwTask.class);
|
||||
verify(taskRepository).save(trace.capture());
|
||||
assertEquals(FlwEnums.TaskStatus.NODE_REROUTE_DEF, trace.getValue().getNodeId(),
|
||||
"trace 落保留节点 id 的留痕行");
|
||||
assertTrue(trace.getValue().getNodeName().contains("v1→v2"), "留痕行载明版本迁移");
|
||||
verify(instanceRepository).save(instance);
|
||||
}
|
||||
|
||||
@Test
|
||||
void useLatestDefWithSameVersionIsNoopRefresh() {
|
||||
FlwDef v1 = def(11L, 1, V1);
|
||||
FlwInstance instance = parkedInstance(v1);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq("g-zombie"), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(v1));
|
||||
|
||||
service.reroute(SCH, 500L, true);
|
||||
|
||||
verify(flowEngine).rerouteCondition(any(), eq(v1), eq("n1"));
|
||||
verify(taskRepository, never()).save(any());
|
||||
assertEquals(11L, instance.getDefId(), "已是最新版不落留痕行、不刷新");
|
||||
}
|
||||
|
||||
@Test
|
||||
void useLatestDefRejectsWhenNodeMissingInNewDef() {
|
||||
FlwDef v1 = def(11L, 1, V1);
|
||||
// v2 把 n1 改型为 APPROVAL:在途 CONDITION 节点在新定义不存在
|
||||
FlwDef v2 = def(12L, 2, V2);
|
||||
parkedInstance(v1);
|
||||
when(defRepository.findFirstBySchIdAndFlowGuidAndStatusOrderByVersionDesc(
|
||||
eq(SCH), eq("g-zombie"), eq(FlwEnums.DefStatus.PUBLISHED.getCode())))
|
||||
.thenReturn(Optional.of(v2));
|
||||
|
||||
BizException e = assertThrows(BizException.class, () -> service.reroute(SCH, 500L, true));
|
||||
assertTrue(e.getMessage().contains("最新已发布定义中不存在"), "节点在新定义缺失要报人类可读错,不是笼统的无需重跑");
|
||||
verify(flowEngine, never()).rerouteCondition(any(), any(), any());
|
||||
assertEquals(11L, defCap.getValue().getId(), "锁版后默认重跑仍按原版本(v1)");
|
||||
assertEquals(11L, instance.getDefId(), "定义快照零刷新");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.callback.FlwStateEventRecorder;
|
||||
import com.yunhai.flowcenter.engine.FlowEvent;
|
||||
import com.yunhai.flowcenter.entity.*;
|
||||
import com.yunhai.flowcenter.model.FormalApplyModels;
|
||||
import com.yunhai.flowcenter.repository.*;
|
||||
import com.yunhai.flowcenter.stub.StubUserClient;
|
||||
import com.yunhai.flowcenter.support.FlowTestSupport;
|
||||
import com.yunhai.flowcenter.support.OapiSignedClient;
|
||||
import com.yunhai.platform.openapi.base.OpenApiAppClient;
|
||||
import com.yunhai.platform.openapi.base.OpenApiUserClient;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.boot.test.mock.mockito.SpyBean;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Real MySQL constraints/transactions/concurrency and signed FL HTTP; UB is an explicit offline boundary. */
|
||||
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT,properties="flow-center.formal-command.enabled=true")
|
||||
@ActiveProfiles("test")
|
||||
class FormalApplyCommandIT extends FlowTestSupport {
|
||||
static final String A="11111111-1111-4111-8111-111111111111", B="22222222-2222-4222-8222-222222222222";
|
||||
@Autowired FormalApplyCommandService service;
|
||||
@Autowired FormalPayloadCanonicalizer hashes;
|
||||
@Autowired FlwApplyCommandRepository commands;
|
||||
@Autowired FlwBizCoordinateRepository coordinates;
|
||||
@Autowired FlwCommandSourceRepository sources;
|
||||
@Autowired FlwUsageGrantRepository grants;
|
||||
@Autowired FlwStateEventRepository facts;
|
||||
@Autowired FlowInstanceService lifecycle;
|
||||
@Autowired FlowDefAdminService definitions;
|
||||
@MockBean FormCenterSchemaClient schemaClient;
|
||||
@Autowired TransactionTemplate tx;
|
||||
@Autowired ObjectMapper mapper;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired ApplicationEventPublisher events;
|
||||
@MockBean OpenApiAppClient apps;
|
||||
@MockBean OpenApiUserClient users;
|
||||
@MockBean UserBaseActivationClient activation;
|
||||
@SpyBean FlwStateEventRecorder recorder;
|
||||
@LocalServerPort int port;
|
||||
FlwDef def;
|
||||
|
||||
@BeforeEach void setup() throws Exception {
|
||||
int dbPort = jdbc.queryForObject("SELECT @@port",Integer.class);
|
||||
assertTrue(dbPort == 13326 || dbPort == 13429,"Only dedicated isolated database ports are allowed");
|
||||
if (dbPort == 13429) {
|
||||
assertTrue(jdbc.queryForObject("SELECT @@version",String.class).startsWith("8."));
|
||||
assertEquals("c:/users/chenx/.zcode/tmp/fl-d09-zcode-mysql8/",
|
||||
jdbc.queryForObject("SELECT @@datadir",String.class).replace('\\','/').toLowerCase());
|
||||
assertEquals("fl_d09_20261026",jdbc.queryForObject("SELECT DATABASE()",String.class));
|
||||
}
|
||||
commands.deleteAll();coordinates.deleteAll();sources.deleteAll();grants.deleteAll();facts.deleteAll();cleanDb();
|
||||
when(apps.getAppByKey(anyString())).thenAnswer(inv -> mapper.readTree("{\"id\":"+("100018".equals(inv.getArgument(0))?18:19)+",\"sourcePrincipalId\":\""+("100018".equals(inv.getArgument(0))?A:B)+"\",\"appCode\":\"svc-hall\"}"));
|
||||
when(users.getUserById(anyString())).thenAnswer(inv -> new StubUserClient().getUserById(inv.getArgument(0)));
|
||||
when(activation.isAppActivatedStrict(anyInt(),anyLong())).thenReturn(true);
|
||||
mapDept("a",101,"A");def=saveAndPublishDef("formal","formal",linearDef("a","Review"));
|
||||
grant(A,18);grant(B,19);
|
||||
}
|
||||
void grant(String source,int app) {
|
||||
FlwUsageGrant g=new FlwUsageGrant();g.setSchId(1L);g.setFlowGuid(def.getFlowGuid());g.setAppId(app);
|
||||
g.setSourcePrincipalId(source);g.setEnabled(1);grants.saveAndFlush(g);
|
||||
}
|
||||
FormalApplyModels.Request request(String id) {
|
||||
FormalApplyModels.Request r=new FormalApplyModels.Request();r.setRequestId(id);r.setFlowGuid(def.getFlowGuid());
|
||||
r.setBizType("svc-hall");r.setBizId("7");r.setSubmitterId(201);r.setSubmitterName("User");r.setExpectedPreviousRound(0);return r;
|
||||
}
|
||||
|
||||
FlwDef publishContract(boolean bound, String declarations) {
|
||||
FlwDef next = new FlwDef();
|
||||
org.springframework.beans.BeanUtils.copyProperties(def, next, "id");
|
||||
next.setVersion(def.getVersion()+1); next.setStatus(0);
|
||||
next.setContentJson(linearDef("a","Review").replaceFirst("\\{", "{\"variables\":"+declarations+","));
|
||||
if (bound) {
|
||||
next.setFormUuid("d10-form"); next.setFormVersion(1);
|
||||
Map<String,Object> snapshot = new LinkedHashMap<>();
|
||||
snapshot.put("formUuid","d10-form"); snapshot.put("formVersion",1);
|
||||
List<Map<String,Object>> fields = new ArrayList<>();
|
||||
Map<String,Object> amount = new LinkedHashMap<>(); amount.put("key","amount"); amount.put("type","number"); amount.put("required",true);
|
||||
Map<String,Object> grade = new LinkedHashMap<>(); grade.put("key","grade"); grade.put("type","select"); grade.put("enum",Arrays.asList("g1","g2"));
|
||||
fields.add(amount); fields.add(grade); snapshot.put("fields",fields);
|
||||
when(schemaClient.fetchSchema(1L,"d10-form",1)).thenReturn(snapshot);
|
||||
} else { next.setFormUuid(null); next.setFormVersion(null); }
|
||||
next=defRepository.saveAndFlush(next);
|
||||
def=definitions.publish(1L,next.getId());
|
||||
return def;
|
||||
}
|
||||
static final String D10_VARS="[{\"key\":\"amount\",\"type\":\"number\",\"required\":true},{\"key\":\"grade\",\"type\":\"string\",\"enum\":[\"g1\",\"g2\"]}]";
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest
|
||||
@org.junit.jupiter.params.provider.ValueSource(booleans={false,true})
|
||||
void d10ValidInputsUsePublishedUnboundAndFcContracts(boolean bound) throws Exception {
|
||||
FlwDef published=publishContract(bound,D10_VARS);
|
||||
FormalApplyModels.Request r=request("valid");r.setFormData(mapper.readValue("{\"amount\":12.5,\"grade\":\"g1\"}",Map.class));
|
||||
String hash=hashes.hash(r);
|
||||
FormalApplyModels.Receipt accepted=service.submit(1L,"100018",r);
|
||||
assertEquals("ACCEPTED",accepted.getState());assertEquals(published.getVersion(),accepted.getDefVersion());
|
||||
assertEquals(hash,accepted.getCanonicalHash());assertEquals(1,accepted.getCanonicalVersion());
|
||||
assertEquals(1,instanceRepository.count());assertEquals(2,taskRepository.count());
|
||||
}
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest
|
||||
@org.junit.jupiter.params.provider.ValueSource(strings={"{}","{\"amount\":null}","{\"amount\":\"\"}","{\"amount\":\" \"}",
|
||||
"{\"amount\":\"12\"}","{\"amount\":true}","{\"amount\":12,\"grade\":\"g9\"}","{\"amount\":12,\"extra\":1}"})
|
||||
void d10ValidationRejectionIsDurableWithZeroInstancesOrTasks(String data) throws Exception {
|
||||
publishContract(false,D10_VARS);
|
||||
FormalApplyModels.Request r=request("invalid");r.setFormData(mapper.readValue(data,Map.class));
|
||||
FormalApplyModels.Receipt rejected=service.submit(1L,"100018",r);
|
||||
assertEquals("VALIDATION_REJECTED",rejected.getRejectCode());assertEquals("REJECTED",rejected.getState());
|
||||
assertEquals(0,instanceRepository.count());assertEquals(0,taskRepository.count());assertEquals(1,commands.count());
|
||||
// 新定义放宽后,原拒绝仍保持原事实,不重新受理。
|
||||
publishContract(false,"[]");
|
||||
doThrow(new IllegalStateException("UB unavailable")).when(users).getUserById(anyString());
|
||||
FormalApplyModels.Receipt replay=service.submit(1L,"100018",r);
|
||||
assertEquals(rejected.getRejectCode(),replay.getRejectCode());assertEquals(rejected.getRejectDetail(),replay.getRejectDetail());
|
||||
assertEquals(rejected.getCanonicalHash(),replay.getCanonicalHash());assertEquals(0,instanceRepository.count());assertEquals(0,taskRepository.count());
|
||||
r.setBizTitle("changed");
|
||||
assertThrows(RuntimeException.class,()->service.submit(1L,"100018",r));assertEquals(1,commands.count());
|
||||
}
|
||||
|
||||
@Test void d10AcceptedReplaySurvivesNewRequiredVariableAndFingerprintStaysFrozen() throws Exception {
|
||||
FlwDef original=publishContract(false,D10_VARS);
|
||||
FormalApplyModels.Request r=request("stable");r.setFormData(mapper.readValue("{\"amount\":12,\"grade\":\"g1\"}",Map.class));
|
||||
FormalApplyModels.Receipt accepted=service.submit(1L,"100018",r);
|
||||
def=original;
|
||||
publishContract(false,"[{\"key\":\"newRequired\",\"type\":\"boolean\",\"required\":true}]");
|
||||
FormalApplyModels.Receipt replay=service.submit(1L,"100018",r);
|
||||
assertEquals(accepted.getInstanceId(),replay.getInstanceId());assertEquals(original.getVersion(),replay.getDefVersion());
|
||||
assertEquals(accepted.getCanonicalHash(),replay.getCanonicalHash());assertEquals(1,replay.getCanonicalVersion());
|
||||
assertEquals(1,commands.count());assertEquals(1,instanceRepository.count());assertEquals(2,taskRepository.count());
|
||||
}
|
||||
|
||||
@Test void d10ConcurrentValidAndInvalidInputCannotBypassContract() throws Exception {
|
||||
publishContract(false,D10_VARS);
|
||||
FormalApplyModels.Request valid=request("valid");valid.setFormData(mapper.readValue("{\"amount\":12}",Map.class));
|
||||
FormalApplyModels.Request invalid=request("invalid");invalid.setBizId("8");
|
||||
ExecutorService pool=Executors.newFixedThreadPool(2);CountDownLatch go=new CountDownLatch(1);
|
||||
try {
|
||||
Future<FormalApplyModels.Receipt> a=pool.submit(()->{go.await();return service.submit(1L,"100018",valid);});
|
||||
Future<FormalApplyModels.Receipt> b=pool.submit(()->{go.await();return service.submit(1L,"100018",invalid);});go.countDown();
|
||||
assertEquals("ACCEPTED",a.get(20,TimeUnit.SECONDS).getState());assertEquals("VALIDATION_REJECTED",b.get(20,TimeUnit.SECONDS).getRejectCode());
|
||||
assertEquals(1,instanceRepository.count());assertEquals(2,taskRepository.count());assertEquals(2,commands.count());
|
||||
} finally { pool.shutdownNow(); }
|
||||
}
|
||||
@Test void duplicateAndConflictingRequestAndBusyCoordinateAreDifferentFacts() {
|
||||
FormalApplyModels.Request r=request("r1");FormalApplyModels.Receipt first=service.submit(1L,"100018",r);
|
||||
assertEquals("ACCEPTED",first.getState());assertEquals(1,first.getRound());
|
||||
assertEquals(first.getInstanceId(),service.submit(1L,"100018",r).getInstanceId());
|
||||
r.setBizTitle("changed");assertThrows(RuntimeException.class,()->service.submit(1L,"100018",r));
|
||||
FormalApplyModels.Receipt busy=service.submit(1L,"100018",request("r2"));assertEquals("REJECTED",busy.getState());assertEquals("IN_FLIGHT",busy.getRejectCode());
|
||||
assertEquals(1,instanceRepository.count());assertEquals(2,commands.count());
|
||||
}
|
||||
@Test void sameRequestIdOnDifferentCoordinatesStillConflicts() {
|
||||
service.submit(1L,"100018",request("r1"));FormalApplyModels.Request changed=request("r1");changed.setBizId("8");
|
||||
assertThrows(RuntimeException.class,()->service.submit(1L,"100018",changed));assertEquals(1,commands.count());
|
||||
}
|
||||
@Test void twoLegitimateApplicationsNeverShareInstanceOrReceipt() {
|
||||
FormalApplyModels.Receipt a=service.submit(1L,"100018",request("r"));
|
||||
assertEquals("NOT_FOUND",service.query(1L,"100019","r",null).getState());
|
||||
FormalApplyModels.Receipt b=service.submit(1L,"100019",request("r"));
|
||||
assertNotEquals(a.getInstanceId(),b.getInstanceId());assertEquals(2,instanceRepository.count());
|
||||
}
|
||||
@Test void receiptReplaySurvivesGrantRevocationDefinitionChangesAndUserLookupFailure() {
|
||||
FormalApplyModels.Request r=request("r");FormalApplyModels.Receipt a=service.submit(1L,"100018",r);
|
||||
FlwUsageGrant g=grants.findBySchIdAndFlowGuidAndAppId(1L,def.getFlowGuid(),18).get();g.setEnabled(0);grants.saveAndFlush(g);
|
||||
def.setStatus(0);def.setLineOffline(1);defRepository.saveAndFlush(def);
|
||||
doThrow(new IllegalStateException("UB unavailable")).when(users).getUserById(anyString());
|
||||
assertEquals(a.getInstanceId(),service.submit(1L,"100018",r).getInstanceId());
|
||||
FormalApplyModels.Request other=request("other");other.setBizId("8");assertEquals("USAGE_DENIED",service.submit(1L,"100018",other).getRejectCode());
|
||||
assertEquals(a.getInstanceId(),service.query(1L,"100018","r",hashes.hash(r)).getInstanceId());
|
||||
}
|
||||
@Test void missingFirstAndWrongPreviousAnchorsAreDurableRejections() {
|
||||
FormalApplyModels.Request invalid=request("missing");invalid.setExpectedPreviousRound(null);
|
||||
assertEquals("PRECONDITION_FAILED",service.submit(1L,"100018",invalid).getRejectCode());
|
||||
assertEquals("REJECTED",service.query(1L,"100018","missing",null).getState());
|
||||
assertEquals(0,instanceRepository.count());
|
||||
}
|
||||
@Test void explicitResubmissionCreatesNewInstanceAndLateOldReleaseCannotFreeIt() {
|
||||
FormalApplyModels.Receipt first=service.submit(1L,"100018",request("first"));lifecycle.withdraw(1L,first.getInstanceId());
|
||||
FormalApplyModels.Request wrong=request("wrong");wrong.setExpectedPreviousRound(1);
|
||||
assertEquals("PRECONDITION_FAILED",service.submit(1L,"100018",wrong).getRejectCode());
|
||||
FormalApplyModels.Request next=request("next");next.setExpectedPreviousRound(1);next.setExpectedPreviousInstanceId(first.getInstanceId());
|
||||
FormalApplyModels.Receipt second=service.submit(1L,"100018",next);
|
||||
assertEquals(2,second.getRound());assertNotEquals(first.getInstanceId(),second.getInstanceId());
|
||||
tx.executeWithoutResult(t -> events.publishEvent(FlowEvent.of(FlowEvent.Type.WITHDRAWN,first.getInstanceId(),null,Collections.emptyMap())));
|
||||
assertEquals(second.getInstanceId(),tx.execute(t -> coordinates.lock(1L,A,"svc-hall","7").get().getActiveInstanceId()));
|
||||
assertEquals(40,service.query(1L,"100018","first",null).getStatus());
|
||||
}
|
||||
@Test void concurrentSameCommandReturnsExactlyOneInstance() throws Exception { concurrent(true); }
|
||||
@Test void concurrentDifferentCommandsPersistOneAcceptanceAndOneRejection() throws Exception { concurrent(false); }
|
||||
void concurrent(boolean same) throws Exception {
|
||||
ExecutorService pool=Executors.newFixedThreadPool(2);CountDownLatch go=new CountDownLatch(1);
|
||||
try {
|
||||
Future<FormalApplyModels.Receipt> a=pool.submit(()->{go.await();return service.submit(1L,"100018",request("a"));});
|
||||
Future<FormalApplyModels.Receipt> b=pool.submit(()->{go.await();return service.submit(1L,"100018",request(same?"a":"b"));});go.countDown();
|
||||
FormalApplyModels.Receipt x=a.get(20,TimeUnit.SECONDS),y=b.get(20,TimeUnit.SECONDS);
|
||||
assertEquals(1,instanceRepository.count());
|
||||
if(same){assertEquals("ACCEPTED",x.getState());assertEquals(x.getInstanceId(),y.getInstanceId());assertEquals(1,commands.count());}
|
||||
else {assertEquals(new HashSet<>(Arrays.asList("ACCEPTED","REJECTED")),new HashSet<>(Arrays.asList(x.getState(),y.getState())));assertEquals(2,commands.count());}
|
||||
} finally {pool.shutdownNow();}
|
||||
}
|
||||
@Test void eventPersistenceFailureRollsBackCommandInstanceAndPointer() {
|
||||
doThrow(new IllegalStateException("injected event persistence failure")).when(recorder).record(any());
|
||||
assertThrows(RuntimeException.class,()->service.submit(1L,"100018",request("r")));
|
||||
assertEquals(0,commands.count());assertEquals(0,instanceRepository.count());assertEquals(0,coordinates.count());
|
||||
}
|
||||
@Test void unavailableAuthorityDoesNotBecomeDeterministicRejection() {
|
||||
when(activation.isAppActivatedStrict(anyInt(),anyLong())).thenThrow(new IllegalStateException("network"));
|
||||
assertThrows(RuntimeException.class,()->service.submit(1L,"100018",request("r")));
|
||||
assertEquals("NOT_FOUND",service.query(1L,"100018","r",null).getState());assertEquals(0,instanceRepository.count());
|
||||
}
|
||||
@Test void signedHttpExposesReceiptAndBlocksLegacyWriterAndOtherSourceReads() throws Exception {
|
||||
OapiSignedClient client=new OapiSignedClient("http://localhost:"+port,"100018","svc-hall-dev-secret-100018");
|
||||
com.fasterxml.jackson.databind.JsonNode reply=client.post("/oapi/flow/commands?schId=1",mapper.writeValueAsString(request("r")),com.fasterxml.jackson.databind.JsonNode.class).getBody();
|
||||
assertEquals("ACCEPTED",reply.path("data").path("state").asText());
|
||||
assertEquals("ACCEPTED",client.get("/oapi/flow/commands/r?schId=1",com.fasterxml.jackson.databind.JsonNode.class).getBody().path("data").path("state").asText());
|
||||
assertNotEquals(0,client.post("/oapi/flow/apply?schId=1",mapper.writeValueAsString(request("legacy")),com.fasterxml.jackson.databind.JsonNode.class).getBody().path("code").asInt());
|
||||
FormalApplyModels.Receipt other=service.submit(1L,"100019",request("other"));
|
||||
assertNotEquals(0,client.get("/oapi/flow/progress?schId=1&instanceId="+other.getInstanceId(),com.fasterxml.jackson.databind.JsonNode.class).getBody().path("code").asInt());
|
||||
}
|
||||
@Test void databaseEnforcesCommandCoordinateAndRoundUniqueness() {
|
||||
FormalApplyModels.Receipt r=service.submit(1L,"100018",request("r"));
|
||||
FlwApplyCommand duplicate=new FlwApplyCommand();org.springframework.beans.BeanUtils.copyProperties(commands.findAll().get(0),duplicate,"id");
|
||||
assertThrows(org.springframework.dao.DataIntegrityViolationException.class,()->commands.saveAndFlush(duplicate));
|
||||
FlwBizCoordinate coordinate=new FlwBizCoordinate();org.springframework.beans.BeanUtils.copyProperties(coordinates.findAll().get(0),coordinate,"id");
|
||||
assertThrows(org.springframework.dao.DataIntegrityViolationException.class,()->coordinates.saveAndFlush(coordinate));
|
||||
FlwInstance instance=new FlwInstance();org.springframework.beans.BeanUtils.copyProperties(instanceRepository.findById(r.getInstanceId()).get(),instance,"id","version");
|
||||
assertThrows(org.springframework.dao.DataIntegrityViolationException.class,()->instanceRepository.saveAndFlush(instance));
|
||||
assertEquals(1,commands.count());assertEquals(1,coordinates.count());assertEquals(1,instanceRepository.count());
|
||||
}
|
||||
@Test void terminalReleaseAndNewOccupancyAreSerializedByRealDatabaseLock() throws Exception {
|
||||
FormalApplyModels.Receipt old=service.submit(1L,"100018",request("old"));
|
||||
CountDownLatch terminalWritten=new CountDownLatch(1),commitTerminal=new CountDownLatch(1);ExecutorService pool=Executors.newFixedThreadPool(2);
|
||||
FormalApplyModels.Request next=request("next");next.setExpectedPreviousRound(1);next.setExpectedPreviousInstanceId(old.getInstanceId());
|
||||
try {
|
||||
Future<?> finish=pool.submit(()->tx.executeWithoutResult(t->{lifecycle.withdraw(1L,old.getInstanceId());terminalWritten.countDown();try{if(!commitTerminal.await(10,TimeUnit.SECONDS))throw new IllegalStateException("timeout");}catch(InterruptedException e){throw new IllegalStateException(e);}}));
|
||||
assertTrue(terminalWritten.await(10,TimeUnit.SECONDS));Future<FormalApplyModels.Receipt> begin=pool.submit(()->service.submit(1L,"100018",next));
|
||||
assertThrows(TimeoutException.class,()->begin.get(200,TimeUnit.MILLISECONDS));commitTerminal.countDown();finish.get(10,TimeUnit.SECONDS);
|
||||
FormalApplyModels.Receipt result=begin.get(10,TimeUnit.SECONDS);assertEquals("ACCEPTED",result.getState());assertEquals(2,result.getRound());
|
||||
assertEquals(result.getInstanceId(),tx.execute(t->coordinates.lock(1L,A,"svc-hall","7").get().getActiveInstanceId()));
|
||||
} finally {commitTerminal.countDown();pool.shutdownNow();}
|
||||
}
|
||||
@Test void completedDoesNotAutomaticallyQualifyForAnotherRound() {
|
||||
FormalApplyModels.Receipt first=service.submit(1L,"100018",request("first"));
|
||||
tx.executeWithoutResult(t->{FlwInstance instance=instanceRepository.findById(first.getInstanceId()).get();instance.setStatus(20);instanceRepository.saveAndFlush(instance);events.publishEvent(FlowEvent.of(FlowEvent.Type.COMPLETED,instance.getId(),null,Collections.emptyMap()));});
|
||||
FormalApplyModels.Request next=request("next");next.setExpectedPreviousInstanceId(first.getInstanceId());next.setExpectedPreviousRound(1);
|
||||
assertEquals("RESUBMIT_NOT_ALLOWED",service.submit(1L,"100018",next).getRejectCode());assertEquals(1,instanceRepository.count());
|
||||
}
|
||||
@Test void missingOrRecreatedSourceNeverInheritsHistoricalCommandsOrGrants() throws Exception {
|
||||
service.submit(1L,"100018",request("r"));
|
||||
doReturn(mapper.readTree("{\"id\":18}")).when(apps).getAppByKey("100018");
|
||||
assertThrows(RuntimeException.class,()->service.query(1L,"100018","r",null));
|
||||
doReturn(mapper.readTree("{\"id\":18,\"sourcePrincipalId\":\""+B+"\"}")).when(apps).getAppByKey("100018");
|
||||
assertEquals("NOT_FOUND",service.query(1L,"100018","r",null).getState());
|
||||
assertEquals("USAGE_DENIED",service.submit(1L,"100018",request("new")).getRejectCode());
|
||||
}
|
||||
@Test void rawKeysAreNeverSilentlyTrimmedOrAliasedByMysql() {
|
||||
FormalApplyModels.Request r=request("space");r.setBizId("7 ");
|
||||
assertThrows(RuntimeException.class,()->service.submit(1L,"100018",r));assertEquals(0,commands.count());
|
||||
}
|
||||
@Test void receiptRejectsDefinitionIdentityDriftEvenWhenVersionNumberIsEqual() {
|
||||
FormalApplyModels.Receipt result=service.submit(1L,"100018",request("r"));
|
||||
FlwDef other=saveAndPublishDef("other","Other",linearDef("a","Review"));assertEquals(def.getVersion(),other.getVersion());
|
||||
tx.executeWithoutResult(t->{FlwInstance instance=instanceRepository.findById(result.getInstanceId()).get();instance.setDefId(other.getId());instanceRepository.saveAndFlush(instance);});
|
||||
assertThrows(IllegalStateException.class,()->service.query(1L,"100018","r",null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.FlowCenterApplication;
|
||||
import com.yunhai.flowcenter.entity.*;
|
||||
import com.yunhai.flowcenter.repository.*;
|
||||
import com.yunhai.flowcenter.stub.StubUserClient;
|
||||
import com.yunhai.platform.openapi.base.*;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
/** Test-only separate JVM: real FL HTTP/engine/database/callback producer; UB stays explicitly offline. */
|
||||
public class FormalFlowHttpFixtureMain {
|
||||
public static final String GUID="eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
|
||||
public static final String SOURCE="11111111-1111-4111-8111-111111111111";
|
||||
@TestConfiguration
|
||||
static class IdentityFixtures {
|
||||
@Bean @Primary OpenApiAppClient fixtureApps(ObjectMapper mapper) throws Exception {
|
||||
OpenApiAppClient client=mock(OpenApiAppClient.class);
|
||||
when(client.getAppByKey("100018")).thenReturn(mapper.readTree("{\"id\":18,\"sourcePrincipalId\":\""+SOURCE+"\",\"appCode\":\"svc-hall\"}"));
|
||||
return client;
|
||||
}
|
||||
@Bean @Primary OpenApiUserClient fixtureUsers(){return new StubUserClient();}
|
||||
@Bean @Primary UserBaseActivationClient fixtureActivation(){
|
||||
UserBaseActivationClient client=mock(UserBaseActivationClient.class);
|
||||
when(client.isAppActivatedStrict(anyInt(),anyLong())).thenReturn(true);return client;
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
String callback=System.getenv("FL_FIXTURE_CALLBACK");
|
||||
if(callback==null || !callback.startsWith("http://127.0.0.1:"))throw new IllegalArgumentException("Isolated callback required");
|
||||
ConfigurableApplicationContext context=new SpringApplication(FlowCenterApplication.class,IdentityFixtures.class).run(args);
|
||||
JdbcTemplate jdbc=context.getBean(JdbcTemplate.class);
|
||||
if(jdbc.queryForObject("SELECT @@port",Integer.class)!=13326)throw new IllegalStateException("Unsafe database");
|
||||
if (!"fl_http_20261026".equals(jdbc.queryForObject("SELECT DATABASE()",String.class))) throw new IllegalStateException("Unsafe fixture schema");
|
||||
for (String table : jdbc.queryForList("SHOW TABLES",String.class)) {
|
||||
if (!table.matches("flw_[a-z_]+|flow_callback_(event|reg)")) throw new IllegalStateException("Unexpected table in isolated schema");
|
||||
jdbc.update("DELETE FROM `"+table+"`");
|
||||
}
|
||||
FlwDef def=new FlwDef();def.setSchId(1L);def.setFlowGuid(GUID);def.setCode("http-chain");def.setName("HTTP chain");def.setVersion(1);def.setStatus(1);
|
||||
def.setContentJson("{\"start\":\"start\",\"nodes\":[{\"id\":\"start\",\"type\":\"START\"},{\"id\":\"review\",\"type\":\"APPROVAL\",\"assignee\":{\"type\":\"USERS\",\"userIds\":[101]}},{\"id\":\"end\",\"type\":\"END\"}],\"edges\":[{\"from\":\"start\",\"to\":\"review\"},{\"from\":\"review\",\"to\":\"end\"}]}");
|
||||
context.getBean(FlwDefRepository.class).saveAndFlush(def);
|
||||
FlwUsageGrant grant=new FlwUsageGrant();grant.setSchId(1L);grant.setFlowGuid(GUID);grant.setAppId(18);grant.setSourcePrincipalId(SOURCE);grant.setEnabled(1);
|
||||
context.getBean(FlwUsageGrantRepository.class).saveAndFlush(grant);
|
||||
FlwCallbackReg reg=new FlwCallbackReg();reg.setSchId(1L);reg.setAppKey("100018");reg.setSourcePrincipalId(SOURCE);reg.setFlowGuid(GUID);
|
||||
reg.setCallbackUrl(callback);reg.setSecret("isolated-callback-secret");reg.setStatus(0);
|
||||
context.getBean(FlwCallbackRegRepository.class).saveAndFlush(reg);
|
||||
System.out.println("FL_HTTP_FIXTURE_READY");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.yunhai.flowcenter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.yunhai.flowcenter.model.FormalApplyModels;
|
||||
import com.yunhai.flowcenter.model.OapiModels;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class FormalPayloadCanonicalizerTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final FormalPayloadCanonicalizer canonicalizer = new FormalPayloadCanonicalizer(mapper);
|
||||
private FormalApplyModels.Request body() throws Exception {
|
||||
return mapper.readValue("{\"requestId\":\"r1\",\"flowGuid\":\"flow\",\"bizType\":\"svc-hall\",\"bizId\":\"7\",\"submitterId\":201,\"expectedPreviousRound\":0}", FormalApplyModels.Request.class);
|
||||
}
|
||||
@Test void keyOrderAndNumericFormattingAreEquivalent() throws Exception {
|
||||
FormalApplyModels.Request a=body(), b=body();
|
||||
a.setFormData(mapper.readValue("{\"b\":2,\"a\":1.0}",Map.class));
|
||||
b.setFormData(mapper.readValue("{\"a\":1,\"b\":2.00}",Map.class));
|
||||
assertEquals(canonicalizer.hash(a),canonicalizer.hash(b));
|
||||
}
|
||||
@Test void nullEmptyAndMissingObjectValuesAreDistinct() throws Exception {
|
||||
FormalApplyModels.Request a=body(); String none=canonicalizer.hash(a);
|
||||
a.setFormData(Collections.emptyMap()); assertNotEquals(none,canonicalizer.hash(a));
|
||||
String empty=canonicalizer.hash(a); a.setFormData(Collections.singletonMap("x",null));
|
||||
assertNotEquals(empty,canonicalizer.hash(a));
|
||||
String nil=canonicalizer.hash(a); a.setFormData(Collections.singletonMap("x",""));
|
||||
assertNotEquals(nil,canonicalizer.hash(a));
|
||||
}
|
||||
@Test void snapshotStringAndObjectAreEquivalent() throws Exception {
|
||||
FormalApplyModels.Request a=body(),b=body(); a.setBizSnapshot("{\"b\":2,\"a\":1}");
|
||||
b.setBizSnapshot(mapper.readValue("{\"a\":1,\"b\":2}",Map.class));
|
||||
assertEquals(canonicalizer.hash(a),canonicalizer.hash(b));
|
||||
}
|
||||
@Test void personnelAndNodeOrderAreSetsButDuplicatesAreRejected() throws Exception {
|
||||
FormalApplyModels.Request a=body(),b=body();
|
||||
OapiModels.AssignItem first=new OapiModels.AssignItem(); first.setNodeId("n"); first.setUserIds(Arrays.asList(3,2));
|
||||
OapiModels.AssignItem second=new OapiModels.AssignItem(); second.setNodeId("n"); second.setUserIds(Arrays.asList(2,3));
|
||||
a.setAssigns(Collections.singletonList(first)); b.setAssigns(Collections.singletonList(second));
|
||||
assertEquals(canonicalizer.hash(a),canonicalizer.hash(b));
|
||||
second.setUserIds(Arrays.asList(2,2)); assertThrows(RuntimeException.class,()->canonicalizer.hash(b));
|
||||
b.setAssigns(Arrays.asList(first,first)); assertThrows(RuntimeException.class,()->canonicalizer.hash(b));
|
||||
}
|
||||
@Test void delimitersCannotCreateOldConcatenationCollisions() throws Exception {
|
||||
FormalApplyModels.Request a=body(),b=body(); a.setBizTitle("a|b");a.setBizUrl("c");
|
||||
b.setBizTitle("a"); b.setBizUrl("b|c"); assertNotEquals(canonicalizer.hash(a),canonicalizer.hash(b));
|
||||
}
|
||||
@Test void versionAndPredecessorAndPayloadChangesChangeHashButRequestIdDoesNot() throws Exception {
|
||||
FormalApplyModels.Request a=body();String original=canonicalizer.hash(a);
|
||||
a.setRequestId("other"); assertEquals(original,canonicalizer.hash(a));
|
||||
a.setExpectedDefVersion(2); assertNotEquals(original,canonicalizer.hash(a));a.setExpectedDefVersion(null);
|
||||
a.setExpectedPreviousInstanceId(12L); assertNotEquals(original,canonicalizer.hash(a));a.setExpectedPreviousInstanceId(null);
|
||||
a.setSubmitterName("changed"); assertNotEquals(original,canonicalizer.hash(a));
|
||||
}
|
||||
@Test void ordinaryArrayOrderAndInvalidJsonAreNotSilentlyIgnored() throws Exception {
|
||||
FormalApplyModels.Request a=body(),b=body();
|
||||
a.setFormData(Collections.singletonMap("items",Arrays.asList(1,2)));b.setFormData(Collections.singletonMap("items",Arrays.asList(2,1)));
|
||||
assertNotEquals(canonicalizer.hash(a),canonicalizer.hash(b));
|
||||
a.setBizSnapshot("{} trailing"); assertThrows(RuntimeException.class,()->canonicalizer.hash(a));
|
||||
}
|
||||
@Test void frozenWireVectorMatchesShIndependentImplementation() throws Exception {
|
||||
FormalApplyModels.Request r=body();r.setBizTitle("User的Title");r.setBizUrl("/apply-detail?id=7");
|
||||
r.setBizSnapshot("{\"b\":2,\"a\":1}");r.setSubmitterName("User");
|
||||
r.setFormData(mapper.readValue("{\"n\":1.0}",Map.class));
|
||||
assertEquals("178c717d364631ba2956b549353306d713351bd9b98fd135b309d1d1574976d7",canonicalizer.hash(r));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,14 @@ public class StubUserClient implements OpenApiUserClient {
|
||||
|
||||
public static final long TEST_SCH_ID = 1L;
|
||||
|
||||
/** D11 资格终审夹具:特殊账号按固定 ID 下发,避免各 IT 各自造 UserBase 桩。 */
|
||||
public static final int DISABLED_USER_ID = 9001;
|
||||
public static final int OTHER_SCHOOL_USER_ID = 9002;
|
||||
public static final int UNKNOWN_STATUS_USER_ID = 9003;
|
||||
public static final int NO_SCHOOL_USER_ID = 9004;
|
||||
public static final int MISSING_USER_ID = 9999;
|
||||
public static final int USERBASE_UNAVAILABLE_ID = 9998;
|
||||
|
||||
@Override
|
||||
public BoaUser getUserById(String userId) {
|
||||
return buildUser(Integer.valueOf(userId));
|
||||
@@ -33,8 +41,29 @@ public class StubUserClient implements OpenApiUserClient {
|
||||
}
|
||||
|
||||
private static BoaUser buildUser(int userId) {
|
||||
if (userId == MISSING_USER_ID) {
|
||||
return null;
|
||||
}
|
||||
if (userId == USERBASE_UNAVAILABLE_ID) {
|
||||
throw new IllegalStateException("stub UserBase unavailable");
|
||||
}
|
||||
BoaUser user = new BoaUser(userId, "user" + userId, "用户" + userId);
|
||||
user.setSchool(new BoaGroup((int) TEST_SCH_ID, "测试学校"));
|
||||
if (userId == NO_SCHOOL_USER_ID) {
|
||||
user.setSchool(null);
|
||||
} else if (userId == OTHER_SCHOOL_USER_ID) {
|
||||
user.setSchool(new BoaGroup(2, "外校"));
|
||||
} else {
|
||||
user.setSchool(new BoaGroup((int) TEST_SCH_ID, "测试学校"));
|
||||
}
|
||||
// T06 禁用账号终审(2026-10-25):stub 用户按在册正常账号下发(1=正常),
|
||||
// 与 UserBase toLightBoaUser 口径对齐;个别用例自建 BoaUser 不受影响
|
||||
if (userId == DISABLED_USER_ID) {
|
||||
user.setStatus(0);
|
||||
} else if (userId == UNKNOWN_STATUS_USER_ID) {
|
||||
user.setStatus(null);
|
||||
} else {
|
||||
user.setStatus(1);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,10 @@ public abstract class FlowTestSupport {
|
||||
protected FlwRouterRepository routerRepository;
|
||||
@Autowired
|
||||
protected FlwRouteLogRepository routeLogRepository;
|
||||
@Autowired
|
||||
protected com.yunhai.flowcenter.repository.FlwStateEventRepository stateEventRepository;
|
||||
@Autowired
|
||||
protected com.yunhai.flowcenter.repository.FlwAdvanceIntentRepository advanceIntentRepository;
|
||||
|
||||
/** tag → 实际 deptKey(flw_dept.id 字符串);mapDept 注册,def helper 消费 */
|
||||
private final Map<String, String> deptKeyByTag = new HashMap<>();
|
||||
@@ -64,6 +68,11 @@ public abstract class FlowTestSupport {
|
||||
}
|
||||
|
||||
protected void cleanDb() {
|
||||
// D09: intents must not outlive the tasks/instances whose activations they describe.
|
||||
advanceIntentRepository.deleteAll();
|
||||
// 事实行先清:否则上一用例/上一轮遗留的 dispatched=0 事实会被 60s 补分发扫描
|
||||
// 按实例行复活重投(跨类注入并发推送者;FormalApplyCommandIT 此前被迫自清即此缺口)
|
||||
stateEventRepository.deleteAll();
|
||||
logRepository.deleteAll();
|
||||
regRepository.deleteAll();
|
||||
ccRepository.deleteAll();
|
||||
|
||||
Reference in New Issue
Block a user