fix: reconcile stopped native workflow resource leases

This commit is contained in:
Codex 2026-11-23 14:53:30 +08:00
parent bfb3a6fdaa
commit 649e53844f
4 changed files with 180 additions and 7 deletions

View File

@ -0,0 +1,105 @@
package cn.iocoder.yudao.module.lab.service.scanonly;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.context.TaskThreadRegistry;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.*;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException;
/** Reconcile terminated native flows through the normal physical stop confirmation.
* A terminal workflow row or a lost connection is never proof that a device stopped.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class NativeStopPendingRecovery {
private static final int BATCH_SIZE=32;
private static final long RETRY_DELAY_NANOS=TimeUnit.SECONDS.toNanos(15);
private final JdbcTemplate jdbc;
private final ScanResourceService resources;
private final TaskInstHolder tasks;
private final TaskThreadRegistry threads;
private final Set<String> inFlight=ConcurrentHashMap.newKeySet();
private final Map<String,String> warnings=new ConcurrentHashMap<>();
private final Map<String,Long> retryAfter=new ConcurrentHashMap<>();
private final ExecutorService workers=new ThreadPoolExecutor(2,2,0,TimeUnit.SECONDS,
new ArrayBlockingQueue<>(16),r->{Thread t=new Thread(r,"native-stop-recovery");t.setDaemon(true);return t;},
new ThreadPoolExecutor.AbortPolicy());
private volatile boolean closed;
private int nextOffset;
// Only selection and bounded submission run on the shared scheduler; stop RPCs may take 120 seconds.
@Scheduled(initialDelayString="${cmvr.resource.stop-recovery.poll-ms:5000}",
fixedDelayString="${cmvr.resource.stop-recovery.poll-ms:5000}")
public void scheduledRecover() { if(!closed)TenantUtils.execute(1L,this::submitPending); }
void submitPending() {
if(closed)return;
var candidates=jdbc.queryForList("""
SELECT DISTINCT o.owner_key,t.id
FROM lab_resource_occupation o JOIN te_task_inst t
ON OCTET_LENGTH(t.id)=OCTET_LENGTH(SUBSTRING(o.owner_key,8))
AND CAST(t.id AS BINARY(512))=CAST(SUBSTRING(o.owner_key,8) AS BINARY(512))
WHERE o.tenant_id=1 AND o.deleted=0 AND o.status='STOP_PENDING'
AND o.resource_type='ROBOT' AND o.owner_key LIKE 'NATIVE:%'
AND t.status IN ('2','4')
ORDER BY o.owner_key
""");
Set<String> owners=new HashSet<>();
candidates.forEach(row->owners.add(Objects.toString(row.get("owner_key"))));
warnings.keySet().removeIf(owner->!owners.contains(owner)&&!inFlight.contains(owner));
retryAfter.keySet().removeIf(owner->!owners.contains(owner)&&!inFlight.contains(owner));
if(candidates.isEmpty()){nextOffset=0;return;}
int start=Math.floorMod(nextOffset,candidates.size());
int count=Math.min(BATCH_SIZE,candidates.size());
nextOffset=(start+count)%candidates.size();
for(int i=0;i<count&&!closed;i++) {
var row=candidates.get((start+i)%candidates.size());
String owner=Objects.toString(row.get("owner_key")),inst=Objects.toString(row.get("id"));
if(!owner.equals("NATIVE:"+inst)||System.nanoTime()<retryAfter.getOrDefault(owner,0L)||!inFlight.add(owner))continue;
try { workers.execute(()->{
try { TenantUtils.execute(1L,()->recoverOwner(owner,inst)); }
catch(RuntimeException error) {
retryAfter.put(owner,System.nanoTime()+RETRY_DELAY_NANOS);
String message=Objects.toString(error.getMessage(),error.getClass().getSimpleName());
if(!message.equals(warnings.put(owner,message)))log.warn("终止流程仍待设备停止确认,占用保留: owner={}, reason={}",owner,message);
} finally { inFlight.remove(owner); }
}); } catch(RejectedExecutionException busy) { inFlight.remove(owner); }
}
}
void recoverOwner(String owner,String inst) {
if(closed||!owner.equals("NATIVE:"+inst))return;
List<Long> leaseIds=resources.leaseIds(owner);
if(leaseIds.isEmpty())return;
var robots=jdbc.queryForList("SELECT resource_id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND resource_type='ROBOT' ORDER BY resource_id",String.class,owner);
if(robots.isEmpty())return;
try(var gate=RobotResourceOperationGate.lock(robots)) {
if(!eligible(owner,inst,leaseIds,robots))return;
resources.clearOccupation(owner,"任务终止或失败后自动收尾:已重新确认本次流程全部关联设备停止",leaseIds,()->{
if(!eligible(owner,inst,leaseIds,robots))throw invalidParamException("流程状态、旧节点或占用已变化,忽略旧停止回执并保留占用");
});
warnings.remove(owner);retryAfter.remove(owner);
log.info("终止流程全部设备停止已确认,自动释放资源: owner={}",owner);
}
}
private boolean eligible(String owner,String inst,List<Long> leaseIds,List<String> robots) {
if(closed||Thread.currentThread().isInterrupted()||!resources.leaseIds(owner).equals(leaseIds))return false;
if(!jdbc.queryForList("SELECT resource_id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND resource_type='ROBOT' ORDER BY resource_id",String.class,owner).equals(robots))return false;
if(tasks.getContext(inst)!=null||!threads.getPendingNodes(inst).isEmpty()||robots.stream().anyMatch(r->tasks.isRobotLocked("robot:"+r)))return false;
if(jdbc.queryForObject("SELECT COUNT(*) FROM te_task_inst WHERE id=? AND status IN ('2','4')",Integer.class,inst)!=1)return false;
return jdbc.queryForObject("SELECT COUNT(*) FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND (status<>'STOP_PENDING' OR status IS NULL)",Integer.class,owner)==0;
}
@PreDestroy void close() { closed=true;workers.shutdownNow(); }
}

View File

@ -4,12 +4,15 @@ import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import com.cmvr.scanner.ScannerExpiredTaskRecovery;
import com.cmvr.scanner.ScannerProperties;
import com.cmvr.test.flow.context.TaskInstHolder;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/** Retry only stopped native flows whose expired scanner task has been reconciled.
* The normal release path still confirms every assigned robot before deleting leases.
@ -25,11 +28,24 @@ public class ScanExpiredScannerRecovery {
private final ScannerProperties settings;
private final ScannerExpiredTaskRecovery recovery;
private final Map<String,String> warnings=new HashMap<>();
private final AtomicBoolean inFlight=new AtomicBoolean();
private final ExecutorService workers=new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1),r->{Thread t=new Thread(r,"expired-scanner-recovery");t.setDaemon(true);return t;},
new ThreadPoolExecutor.AbortPolicy());
private volatile boolean closed;
@Scheduled(initialDelayString="${cmvr.scanner.expired-task-recovery-ms:15000}",fixedDelayString="${cmvr.scanner.expired-task-recovery-ms:15000}")
public void scheduledRecover() { TenantUtils.execute(1L,this::recoverPending); }
public void scheduledRecover() {
if(closed||!inFlight.compareAndSet(false,true))return;
try { workers.execute(()->{
try { TenantUtils.execute(1L,this::recoverPending); }
catch(RuntimeException error) { log.warn("旧扫描任务恢复检查未完成,占用保留: reason={}",error.getMessage()); }
finally { inFlight.set(false); }
}); } catch(RejectedExecutionException busy) { inFlight.set(false); }
}
void recoverPending() {
if(closed||Thread.currentThread().isInterrupted())return;
if(!settings.configured()||settings.getRobotId()==null||settings.getRobotId().isBlank())return;
// Preserve all 128 utf8mb4 characters when comparing IDs across table collations.
// An explicit binary width is also needed by H2; byte lengths exclude padding matches.
@ -45,14 +61,22 @@ public class ScanExpiredScannerRecovery {
""",settings.getRobotId());
Set<String> owners=new HashSet<>();
for(var row:candidates) {
if(closed||Thread.currentThread().isInterrupted())return;
String owner=Objects.toString(row.get("owner_key")),inst=Objects.toString(row.get("id"));owners.add(owner);
var robots=jdbc.queryForList("SELECT resource_id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND resource_type='ROBOT' ORDER BY resource_id",String.class,owner);
try(var gate=RobotResourceOperationGate.lock(robots)) {
if(closed||Thread.currentThread().isInterrupted())return;
List<Long> leaseIds=resources.leaseIds(owner);
if(leaseIds.isEmpty())continue;
if(tasks.getContext(inst)!=null||!threads.getPendingNodes(inst).isEmpty()||robots.stream().anyMatch(r->tasks.isRobotLocked("robot:"+r)))continue;
if(jdbc.queryForObject("SELECT COUNT(*) FROM te_task_inst WHERE id=? AND status IN ('2','4')",Integer.class,inst)!=1)continue;
if(jdbc.queryForObject("SELECT COUNT(*) FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND status<>'STOP_PENDING'",Integer.class,owner)!=0)continue;
if(!recovery.readyForOwner(inst))continue;
resources.clearOccupation(owner,"自动释放:旧扫描任务已失效,设备状态确定且空闲,已重新确认本流程全部机器人停止");
resources.clearOccupation(owner,"自动释放:旧扫描任务已失效,设备状态确定且空闲,已重新确认本流程全部机器人停止",leaseIds,()->{
if(closed||Thread.currentThread().isInterrupted()||tasks.getContext(inst)!=null||!threads.getPendingNodes(inst).isEmpty()||robots.stream().anyMatch(r->tasks.isRobotLocked("robot:"+r))
||!jdbc.queryForList("SELECT resource_id FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 AND resource_type='ROBOT' ORDER BY resource_id",String.class,owner).equals(robots)
||jdbc.queryForObject("SELECT COUNT(*) FROM te_task_inst WHERE id=? AND status IN ('2','4')",Integer.class,inst)!=1)throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("旧流程状态或节点已变化,占用已保留");
});
warnings.remove(owner);log.info("旧扫描任务失效后自动确认释放: owner={}",owner);
} catch(RuntimeException error) {
String message=Objects.toString(error.getMessage(),error.getClass().getSimpleName());
@ -61,4 +85,5 @@ public class ScanExpiredScannerRecovery {
}
warnings.keySet().retainAll(owners);
}
@PreDestroy void close() { closed=true;workers.shutdownNow(); }
}

View File

@ -22,7 +22,9 @@ public class ScanResourceService extends ResourceOccupationStore {
@Resource @Lazy private ScanResourceService self;
@Resource private RobotExecutionTargetResolver targets;
@Resource @Lazy private TaskInstHolder nativeTasks;
@Resource private com.cmvr.test.flow.context.TaskThreadRegistry nativeThreads;
@Resource private EdgeSystemService edgeSystem;
@Resource private org.springframework.transaction.PlatformTransactionManager transactionManager;
public void configure(LabTestTaskDO task,ScanTaskConfigDO c,ScanTaskRequests.Prepare request) {
primary();if(c.getResourcesAcquiredAt()!=null)throw invalidParamException("已进入装夹准备,请先释放准备占用后再更换配置");
@ -132,23 +134,63 @@ public class ScanResourceService extends ResourceOccupationStore {
}
/** Internal recovery must never act on a replacement lease created while polling hardware. */
void clearOccupation(String owner,String reason,List<Long> expectedLeaseIds) {
clearOccupation(owner,reason,expectedLeaseIds,null);
}
/** A recovery callback rechecks its terminal workflow and node fence after every stop RPC. */
void clearOccupation(String owner,String reason,List<Long> expectedLeaseIds,Runnable recoveryFence) {
primary();if(owner==null||!(owner.startsWith("NATIVE:")||owner.startsWith("MANUAL:"))||reason==null||reason.isBlank())throw invalidParamException("请选择试运行或人工占用并填写说明;扫描任务请从工作台停止");
var held=rows("SELECT * FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0",owner);if(held.isEmpty())throw invalidParamException("占用已经释放,请刷新");
if(expectedLeaseIds!=null&&!held.stream().map(row->number(row.get("id"))).sorted().toList().equals(expectedLeaseIds))throw invalidParamException("占用已变化,忽略旧停止处理");
if(recoveryFence!=null)recoveryFence.run();
Set<String> robots=new TreeSet<>();for(var row:held)if("ROBOT".equals(row.get("resource_type")))robots.add(row.get("resource_id").toString());
if(robots.isEmpty())throw invalidParamException("占用缺少机器人信息,无法确认设备停止,占用已保留");
try(var gate=RobotResourceOperationGate.lock(robots)) {
held=rows("SELECT * FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0",owner);
if(held.isEmpty())throw invalidParamException("该操作已停止并释放,请刷新");
if(expectedLeaseIds!=null&&!leaseIds(owner).equals(expectedLeaseIds))throw invalidParamException("占用已变化,忽略旧急停处理");
for(String robot:robots)if(nativeTasks.isRobotLocked("robot:"+robot))throw invalidParamException("流程仍在运行或暂停,请先停止流程,再确认释放");
if(expectedLeaseIds!=null&&!leaseIds(owner).equals(expectedLeaseIds))throw invalidParamException("占用已变化,忽略旧停止处理");
Set<String> lockedRobots=new TreeSet<>();for(var row:held)if("ROBOT".equals(row.get("resource_type")))lockedRobots.add(row.get("resource_id").toString());
if(!lockedRobots.equals(robots))throw invalidParamException("占用的机器人已变化,保留当前占用");
List<Long> stoppingLeaseIds=leaseIds(owner);
assertStopOwnerIdle(owner,robots);
if(recoveryFence!=null)recoveryFence.run();
for(String robot:robots) {
try { edgeSystem.stopAll(robot); }
catch(com.cmvr.common.exception.GlobalException error) {
throw invalidParamException("停止确认失败("+robot+"),占用已保留:"+error.getMessage());
}
if(Thread.currentThread().isInterrupted())throw invalidParamException("停止确认已中断,占用已保留");
if(!leaseIds(owner).equals(stoppingLeaseIds))throw invalidParamException("占用已变化,忽略旧停止回执");
assertStopOwnerIdle(owner,robots);
if(recoveryFence!=null)recoveryFence.run();
}
jdbc.update("INSERT INTO lab_resource_occupation_event(id,owner_key,action,reason,resources_json,operator_id,tenant_id) VALUES(?,?,'STOP_CONFIRMED',?,?,?,1)",
cn.hutool.core.util.IdUtil.getSnowflakeNextId(),owner,reason,com.alibaba.fastjson2.JSON.toJSONString(held),cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId());
jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1",owner);
if(Thread.currentThread().isInterrupted())throw invalidParamException("停止确认已中断,占用已保留");
if(!leaseIds(owner).equals(stoppingLeaseIds))throw invalidParamException("占用已变化,忽略旧停止回执");
assertStopOwnerIdle(owner,robots);
if(recoveryFence!=null)recoveryFence.run();
// Hold database locks only for the final audit and exact lease deletion, never across a device RPC.
new org.springframework.transaction.support.TransactionTemplate(transactionManager).executeWithoutResult(tx->{
var current=rows("SELECT * FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0 ORDER BY id FOR UPDATE",owner);
if(!current.stream().map(row->number(row.get("id"))).toList().equals(stoppingLeaseIds))throw invalidParamException("占用已变化,忽略旧停止回执");
Set<String> currentRobots=new TreeSet<>();for(var row:current)if("ROBOT".equals(row.get("resource_type")))currentRobots.add(row.get("resource_id").toString());
if(!currentRobots.equals(robots))throw invalidParamException("占用的机器人已变化,保留当前占用");
if(expectedLeaseIds!=null&&current.stream().anyMatch(row->!"STOP_PENDING".equals(row.get("status"))))throw invalidParamException("占用状态已变化,保留当前占用");
assertStopOwnerIdle(owner,robots);
if(recoveryFence!=null)recoveryFence.run();
List<Object> releaseParameters=new ArrayList<>();releaseParameters.add(owner);releaseParameters.addAll(stoppingLeaseIds);
String pending=expectedLeaseIds==null?"":" AND status='STOP_PENDING'";
int deleted=jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1 AND deleted=0"+pending+" AND id IN ("+String.join(",",Collections.nCopies(stoppingLeaseIds.size(),"?"))+")",releaseParameters.toArray());
if(deleted!=stoppingLeaseIds.size())throw invalidParamException("占用释放数量不一致,已回滚并保留占用");
jdbc.update("INSERT INTO lab_resource_occupation_event(id,owner_key,action,reason,resources_json,operator_id,tenant_id) VALUES(?,?,'STOP_CONFIRMED',?,?,?,1)",
cn.hutool.core.util.IdUtil.getSnowflakeNextId(),owner,reason,com.alibaba.fastjson2.JSON.toJSONString(current),cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId());
});
}
}
private void assertStopOwnerIdle(String owner,Set<String> robots) {
if(Thread.currentThread().isInterrupted())throw invalidParamException("停止确认已中断,占用已保留");
for(String robot:robots)if(nativeTasks.isRobotLocked("robot:"+robot))throw invalidParamException("流程仍在运行或暂停,请先停止流程,再确认释放");
if(owner.startsWith("NATIVE:")) {
String inst=owner.substring(7);
if(nativeTasks.getContext(inst)!=null||!nativeThreads.getPendingNodes(inst).isEmpty())throw invalidParamException("流程上下文或旧节点尚未退出,占用已保留");
}
}
List<Long> leaseIds(String owner) {

View File

@ -18,6 +18,7 @@ class ScanResourceServiceTest {
var source=new DriverManagerDataSource("jdbc:h2:mem:resources"+UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1","sa","");
jdbc=new JdbcTemplate(source); tx=new TransactionTemplate(new DataSourceTransactionManager(source));
service=new ScanResourceService();ReflectionTestUtils.setField(service,"jdbc",jdbc);
ReflectionTestUtils.setField(service,"transactionManager",new DataSourceTransactionManager(source));ReflectionTestUtils.setField(service,"nativeThreads",org.mockito.Mockito.mock(com.cmvr.test.flow.context.TaskThreadRegistry.class));
var numbers=org.mockito.Mockito.mock(cn.iocoder.yudao.module.lab.dal.redis.LabTaskSeqRedisDAO.class);
org.mockito.Mockito.when(numbers.nextDeviceReservationNo()).thenAnswer(i->"DR-"+UUID.randomUUID());
org.mockito.Mockito.when(numbers.nextLabReservationNo()).thenAnswer(i->"LR-"+UUID.randomUUID());