diff --git a/AGENTS.md b/AGENTS.md index ab77f2f..63272e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,3 +7,7 @@ - 用户明确要求的永久在线模拟机器人 `am-freescan-sim-robot` 和模拟设备 `am-freescan-sim-agv` 继续保留,除非用户另行要求删除。 - 2026-10-22 用户另行要求创建并保留两条全流程演示数据:前缀 `DEMO-20261022-091650`,任务 `T-20261022-0005`、`T-20261022-0006`,导入批次 `IB-20261022-0009`。对应测试用例、样品、夹具、技术资料、执行日志和输出均供用户查看,不纳入开发验证自动清理;清单见 `docs/full-flow-demo-20261022.json`。 - 不删除运行配置、凭据、来源指纹、实际业务数据或回归测试代码。不要输出 `.local/runtime.json` 中的敏感信息。 +- 2026-10-23 用户要求保留真实扫描待运行数据:前缀 `REAL-SCAN-20261023-001`,任务 `T-20261023-0001`,导入批次 `IB-20261023-0001`;清单见 `docs/real-scan-ready-20261023.json`。对应样品、夹具预设、用例、流程版本及真实扫描工位 `am-freescan-station-001` / 设备 `am-freescan-scanner-001` 不纳入验证数据清理。准备脚本不能自动执行扫描,也不能代替用户确认实物与装夹。 +- 上述真实任务的用户首次运行在 SDK 三维快照报 `scene_data_unavailable`,失败执行 `2113504832933294082` 保留;旧任务已停止并取消以释放占用。修正版为 `T-20261023-0002`(`REAL-SCAN-20261023-001-R1`,批次 `IB-20261023-0002`,流程 V3),增加独立 Trak 工程并在停止采集前请求快照,同样保留且不纳入验证清理。新任务必须重新由操作人确认收样与装夹,不能复制这些物理确认状态。 +- 2026-10-23 用户再次要求创建并保留两条现场测试任务:`T-20261023-0003`(流式预览采集)、`T-20261023-0004`(网格化及PLY/STL导出),前缀 `USER-SCAN-20261023`、批次 `IB-20261023-0003`;清单为 `docs/user-scan-two-tasks-20261023.json`。关联用例、流程版本、样品和导入文件不纳入开发验证清理;两条任务都不调用已知故障的原始场景快照接口。准备脚本为 `scripts/prepare_user_scan_pair.py`,不自动确认实物或启动设备,用户按顺序现场测试。 +- `T-20261023-0003` 被用户运行后因创建工程时仍在采集而失败,已保留失败记录并取消释放占用;对应流式测试替代任务为 `T-20261023-0005`(`USER-SCAN-20261023-STREAM-R1`,批次 `IB-20261023-0004`)。当前供用户测试的两条任务为 `0005` 和 `0004`,均绑定 V2,创建工程前先停止采集并等待成功回执;两条任务及旧失败历史全部保留,不自动清理。 diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/mapper/ResourceRobotMapper.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/mapper/ResourceRobotMapper.java index 1554473..b7eeb6e 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/mapper/ResourceRobotMapper.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/mapper/ResourceRobotMapper.java @@ -29,6 +29,8 @@ public interface ResourceRobotMapper extends BaseMapper { int updateAgvRuntimeStatus(ResourceRobot robot); + int updateHttpScannerState(ResourceRobot robot); + List lockByRobotIds(@Param("robotIds") List robotIds); int markHeartbeatExpiredOffline(@Param("id") String id, diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotExecutionTargetResolver.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotExecutionTargetResolver.java index a4ee289..cca4f65 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotExecutionTargetResolver.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/resource/service/ResourceRobotExecutionTargetResolver.java @@ -12,11 +12,14 @@ import org.springframework.stereotype.Service; public class ResourceRobotExecutionTargetResolver implements RobotExecutionTargetResolver { private final ResourceRobotEndpointResolver endpointResolver; private final ResourceRobotStateProperties stateProperties; + private final com.cmvr.scanner.ScannerResourceSynchronizer scannerResources; @Override public RobotExecutionTarget resolve(String robotId) { String normalized = StringUtils.trimToNull(robotId); - if (!stateProperties.isVirtualRobot(normalized)) { + if (scannerResources.handles(normalized)) { + scannerResources.validateTarget(normalized); + } else if (!stateProperties.isVirtualRobot(normalized)) { endpointResolver.resolve(normalized); } return new RobotExecutionTarget(normalized); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java index 5962ba7..f5142ac 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerHttpClient.java @@ -40,7 +40,7 @@ public class ScannerHttpClient { URI uri=new URI("http",null,settings.getHost(),settings.getPort(),op.route(id),null,null); HttpRequest.Builder builder=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs))) .header("Accept",op.binary()?"*/*":"application/json"); - if(op!=ScannerOperation.METADATA)builder.header("X-Api-Key",settings.getApiKey()); + if(op!=ScannerOperation.METADATA)builder.header("Authorization","Bearer "+settings.getApiKey()); if(op.control())builder.header("Content-Type","application/json; charset=utf-8") .POST(HttpRequest.BodyPublishers.ofString(body,StandardCharsets.UTF_8)); else builder.GET(); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java index 885f674..90dc018 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerMonitoringService.java @@ -108,6 +108,17 @@ public class ScannerMonitoringService { return status; } public record Frame(byte[] bytes,Map> headers) {} + public ScannerPreviewStream stream(JsonNode binding) { + status(binding); + var source=scanner.binary(ScannerOperation.PREVIEW_STREAM,null); + try{return new ScannerPreviewStream(source);} + catch(RuntimeException invalid){try{source.close();}catch(IOException ignored){}throw invalid;} + } + public long streamSequence(JsonNode binding,Frame frame) { + status(binding); // Validate the project after reading each complete frame, before publishing it. + try{return Long.parseLong(header(frame.headers(),"x-frame-sequence"));} + catch(Exception invalid){throw new ScannerException("invalid_frame","扫描流缺少有效帧编号",502);} + } public Frame image(JsonNode binding) { status(binding); try(var binary=scanner.binary(ScannerOperation.PREVIEW_IMAGE,null)) { diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerPreviewStream.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerPreviewStream.java new file mode 100644 index 0000000..cc169dc --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerPreviewStream.java @@ -0,0 +1,62 @@ +package com.cmvr.scanner; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; + +/** Bounded multipart reader; one JPEG is retained and HTTP chunking is decoded by HttpClient. */ +public final class ScannerPreviewStream implements AutoCloseable { + private final ScannerHttpClient.Binary source; + private final InputStream input; + private final String boundary; + public ScannerPreviewStream(ScannerHttpClient.Binary source) { + this.source=source; + String type=source.headers().entrySet().stream().filter(e->e.getKey().equalsIgnoreCase("content-type")) + .flatMap(e->e.getValue().stream()).findFirst().orElse(""); + var match=java.util.regex.Pattern.compile("boundary=\"?([A-Za-z0-9_-]{1,100})\"?",java.util.regex.Pattern.CASE_INSENSITIVE).matcher(type); + if(!type.toLowerCase(Locale.ROOT).startsWith("multipart/x-mixed-replace")||!match.find()) + throw new ScannerException("invalid_stream","扫描服务未返回有效MJPEG流",502); + boundary="--"+match.group(1); input=new BufferedInputStream(source.stream(),16384); + } + public ScannerMonitoringService.Frame next() throws IOException { + String line; + do {line=line();} while(line!=null&&line.isEmpty()); + if(line==null||line.equals(boundary+"--"))return null; + if(!line.equals(boundary))throw new IOException("Invalid MJPEG boundary"); + Map> headers=new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + int total=0; + while(true) { + line=line(); if(line==null)throw new EOFException("Truncated MJPEG headers"); + total+=line.length()+2; if(total>16384)throw new IOException("MJPEG headers too large"); + if(line.isEmpty())break; + int colon=line.indexOf(':'); if(colon<=0)throw new IOException("Invalid MJPEG header"); + String key=line.substring(0,colon).trim(),value=line.substring(colon+1).trim(); + if(headers.putIfAbsent(key,List.of(value))!=null)throw new IOException("Duplicate MJPEG header"); + } + int length; + try {length=Integer.parseInt(headers.getOrDefault("content-length",List.of("")).get(0));} + catch(NumberFormatException invalid){throw new IOException("Missing MJPEG length",invalid);} + if(length<4||length>8*1024*1024)throw new IOException("Invalid MJPEG length"); + if(!headers.getOrDefault("content-type",List.of("")).get(0).equalsIgnoreCase("image/jpeg"))throw new IOException("Invalid MJPEG media type"); + byte[] bytes=input.readNBytes(length); + if(bytes.length!=length)throw new EOFException("Truncated MJPEG frame"); + if((bytes[0]&255)!=255||(bytes[1]&255)!=216||(bytes[length-2]&255)!=255||(bytes[length-1]&255)!=217) + throw new IOException("Invalid JPEG frame"); + return new ScannerMonitoringService.Frame(bytes,headers); + } + private String line() throws IOException { + var bytes=new ByteArrayOutputStream(); int value; + while((value=input.read())!=-1) { + if(bytes.size()>=16384)throw new IOException("MJPEG header line too large"); + if(value=='\n') { + byte[] raw=bytes.toByteArray(); + if(raw.length==0||raw[raw.length-1]!='\r')throw new IOException("Invalid MJPEG line ending"); + return new String(raw,0,raw.length-1,StandardCharsets.US_ASCII); + } + bytes.write(value); + } + if(bytes.size()!=0)throw new EOFException("Truncated MJPEG line"); + return null; + } + @Override public void close() throws IOException {source.close();} +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerResourceSynchronizer.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerResourceSynchronizer.java new file mode 100644 index 0000000..2ff9031 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerResourceSynchronizer.java @@ -0,0 +1,100 @@ +package com.cmvr.scanner; + +import com.cmvr.common.exception.GlobalException; +import com.cmvr.resource.config.ResourceRobotStateProperties; +import com.cmvr.resource.domain.ResourceDevice; +import com.cmvr.resource.domain.ResourceRobot; +import com.cmvr.resource.mapper.ResourceDeviceMapper; +import com.cmvr.resource.mapper.ResourceRobotMapper; +import com.fasterxml.jackson.databind.JsonNode; +import cmvr.quic_edge.v1.QuicEdge.ManagedDeviceState; +import lombok.RequiredArgsConstructor; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import java.util.Date; +import java.util.UUID; + +/** HTTP stations report real status; they never advertise the HTTP port as a gRPC endpoint. */ +@Component +@RequiredArgsConstructor +public class ScannerResourceSynchronizer { + private final ScannerProperties settings; + private final ScannerHttpClient client; + private final ResourceRobotMapper robots; + private final ResourceDeviceMapper devices; + private final ResourceRobotStateProperties stateProperties; + + public boolean handles(String robotId) { + return robotId != null && !robotId.isBlank() && robotId.equals(settings.getRobotId()) + && settings.getDeviceId() != null && !settings.getDeviceId().isBlank(); + } + + @Scheduled(initialDelayString = "${cmvr.scanner.resource-initial-delay-ms:3000}", + fixedDelayString = "${cmvr.scanner.resource-refresh-ms:5000}") + public synchronized void refresh() { + if (!handles(settings.getRobotId())) return; + ResourceRobot robot = robots.selectByRobotIdentity(settings.getRobotId()); + if (robot == null || "1".equals(robot.getArchivedStatus())) return; + var matches = devices.selectByIdentity(settings.getRobotId(), settings.getDeviceId()); + if (matches.size() > 1 || (!matches.isEmpty() && !Integer.valueOf(14).equals(matches.get(0).getDeviceKind()))) return; + JsonNode status = null; + try { + status = client.json(ScannerOperation.STATUS, null, null, 3000); + } catch (ScannerException unavailable) { + // A failed read must immediately remove readiness, without sending any control command. + } + Date now = new Date(); + // During SDK work the supplier returns a compact busy response. Missing/null + // deviceOnline is unknown, not an explicit offline report. Keep the last + // measured device state, and update only the reachable HTTP station heartbeat. + boolean partialBusy = status != null && status.path("busy").asBoolean() + && !status.path("deviceOnline").isBoolean() + && !(status.path("initialized").isBoolean() && !status.path("initialized").asBoolean()) + && !"disconnected".equals(status.path("state").asText()) + && !status.path("restartRequired").asBoolean() && !status.path("stateUncertain").asBoolean(); + if (partialBusy) { + ResourceRobot update = new ResourceRobot();update.setId(robot.getId()); + update.setConnectStatus(robot.getConnectStatus());update.setStatus("3"); + update.setLastHeartbeatTime(now);update.setUpdateTime(now);robots.updateHttpScannerState(update); + return; // Do not discover a device, enable it, or refresh its last measured online time. + } + boolean online = status != null && status.path("deviceOnline").asBoolean(false); + ResourceRobot update = new ResourceRobot(); + update.setId(robot.getId()); + update.setConnectStatus(online ? "1" : "0"); + update.setStatus(!online ? "1" : status.path("scanning").asBoolean() || status.path("busy").asBoolean() ? "3" : "2"); + update.setLastHeartbeatTime(status == null ? robot.getLastHeartbeatTime() : now); + update.setUpdateTime(now); + robots.updateHttpScannerState(update); + if (matches.isEmpty() && status == null) return; + ResourceDevice device = matches.isEmpty() ? new ResourceDevice() : matches.get(0); + if (matches.isEmpty()) { + device.setId(UUID.randomUUID().toString().replace("-", "")); + device.setRobotId(settings.getRobotId()); device.setDeviceId(settings.getDeviceId()); + device.setDeviceName("FreeScan 现场扫描仪"); device.setDeviceKind(14); + device.setTypeName("FreeScan HTTP API"); device.setEnabled("1"); + device.setCreateBy("scanner-http"); device.setCreateTime(now); + } + boolean fault = status != null && (status.path("restartRequired").asBoolean() || status.path("stateUncertain").asBoolean()); + device.setOnlineStatus(online ? "1" : "0"); device.setHasError(fault ? "1" : "0"); + device.setErrorMessage(fault ? "扫描服务要求重启或设备状态不确定,请核对现场" : online ? "" : "扫描仪离线或状态查询失败"); + device.setHealthStatus(fault ? 3 : online ? 1 : 0); + ManagedDeviceState managerState = "0".equals(device.getEnabled()) ? ManagedDeviceState.MANAGED_DEVICE_STATE_DISABLED + : fault ? ManagedDeviceState.MANAGED_DEVICE_STATE_ERROR + : !online ? ManagedDeviceState.MANAGED_DEVICE_STATE_STOPPED + : status.path("scanning").asBoolean() || status.path("busy").asBoolean() + ? ManagedDeviceState.MANAGED_DEVICE_STATE_RUNNING : ManagedDeviceState.MANAGED_DEVICE_STATE_READY; + device.setManagerState(managerState.getNumber()); + device.setStatusUpdatedTime(now); if (status != null) device.setLastSeenTime(now); + device.setOfflineTime(online ? null : now); device.setUpdateBy("scanner-http"); device.setUpdateTime(now); + if (matches.isEmpty()) devices.insert(device); else devices.updateRuntimeState(device); + } + + public void validateTarget(String robotId) { + ResourceRobot robot = robots.selectByRobotIdentity(robotId); + if (!settings.configured() || robot == null || "1".equals(robot.getArchivedStatus()) + || !"1".equals(robot.getConnectStatus()) || robot.getLastHeartbeatTime() == null + || robot.getLastHeartbeatTime().before(stateProperties.heartbeatCutoff(new Date()))) + throw new GlobalException("扫描工位离线或状态已过期,请检查扫描服务连接"); + } +} diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java index 11ce6ca..320a5d6 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerService.java @@ -51,12 +51,24 @@ public class ScannerService { ScannerCommandJournal.Entry active=journal.active(client.endpointKey()); if(active!=null){requireKnown(active);refresh(active,deadline);if(journal.active(client.endpointKey())!=null)throw new ScannerException("command_busy","上一控制任务尚未结束,请先等待任务终态",409);} JsonNode status=query(ScannerOperation.STATUS,null,deadline); - if(expectedContext!=null&&(!expectedContext.path("sessionId").asText().equals(status.path("sessionId").asText())||!expectedContext.path("projectId").asText().equals(status.path("projectId").asText())))throw new ScannerException("project_changed","扫描工程已切换,不能为旧工程获取快照",409); + if(expectedContext!=null&&(!expectedContext.path("endpoint").asText(client.endpointKey()).equals(client.endpointKey())||!expectedContext.path("sessionId").asText().equals(status.path("sessionId").asText())||!expectedContext.path("projectId").asText().equals(status.path("projectId").asText())))throw new ScannerException("project_changed","扫描会话或工程已切换,不能继续原工程操作",409); if(status.path("restartRequired").asBoolean())throw new ScannerException("restart_required","设备服务要求正常重启,禁止自动重连",409); if(status.path("stateUncertain").asBoolean())throw new ScannerException("state_uncertain","设备状态不确定,请先核对任务和现场状态",409); if(status.path("busy").asBoolean())throw new ScannerException("device_busy","扫描设备正在处理其他控制任务",409); requestBudget(deadline); journal.intent(key,client.endpointKey(),op,hash,body.toString(),owner); + // Pausing an idle SDK with no project can hang Sn3DPauseScanSync. + // Only explicit, healthy device status can confirm an idempotent stop; + // pending commands and project/session checks above still apply. + if(op==ScannerOperation.SCAN_STOP&&List.of("scanning","busy","stateUncertain","restartRequired").stream() + .allMatch(field->status.path(field).isBoolean()&&!status.path(field).booleanValue())) { + ObjectNode stopped=ScannerRequestValidator.JSON.createObjectNode(); + stopped.put("state","succeeded"); + stopped.putObject("result").put("scanning",false).put("alreadyStopped",true) + .put("confirmationSource","device_status"); + journal.finish(key,true,stopped,null); + return accepted(journal.get(key)); + } JsonNode response; try {response=client.json(op,null,body.toString(),requestBudget(deadline));} catch(ScannerException error){ @@ -73,10 +85,13 @@ public class ScannerService { } finally {commandLock.unlock();} } public JsonNode executeAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs) { + return executeBoundAndWait(op,body,key,owner,timeoutMs,null); + } + public JsonNode executeBoundAndWait(ScannerOperation op,ObjectNode body,String key,String owner,long timeoutMs,JsonNode expectedContext) { long deadline=deadline(timeoutMs); ObjectNode accepted; while(true){ - try {accepted=submit(op,body,key,owner,null,deadline);break;} + try {accepted=submit(op,body,key,owner,expectedContext,deadline);break;} catch(ScannerException error){if(!Set.of("command_busy","device_busy").contains(error.scannerCode))throw error;sleep(deadline);} } return waitCommandUntil(accepted.path("commandKey").asText(),deadline); @@ -135,7 +150,9 @@ public class ScannerService { if(deadline==0)return Math.max(1,settings.getRequestTimeoutMs()); long remaining=deadline-System.nanoTime(); if(remaining<=0)throw waitTimeout(); - return Math.max(1,Math.min(settings.getRequestTimeoutMs(),TimeUnit.NANOSECONDS.toMillis(remaining))); + // HTTP timeouts use whole milliseconds; rounding down can expire the + // final query before the operation deadline and misclassify its result. + return Math.max(1,Math.min(settings.getRequestTimeoutMs(),TimeUnit.NANOSECONDS.toMillis(remaining-1)+1)); } private JsonNode query(ScannerOperation operation,String id,long deadline) { try { diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java index 731afb1..d665bcb 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerStreamingConfiguration.java @@ -15,6 +15,6 @@ public class ScannerStreamingConfiguration implements WebMvcConfigurer { @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) { if (request.isAsyncStarted()) request.getAsyncContext().setTimeout(0); } - }).addPathPatterns("/admin-api/cmvr/scanner/preview/stream"); + }).addPathPatterns("/admin-api/cmvr/scanner/preview/stream", "/admin-api/lab/execution/scanner-view/stream"); } } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerSupplementAdapter.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerSupplementAdapter.java new file mode 100644 index 0000000..546a8cb --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerSupplementAdapter.java @@ -0,0 +1,42 @@ +package com.cmvr.scanner; + +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.test.enums.ActionEnum; +import com.cmvr.test.flow.runtime.message.*; +import com.cmvr.test.flow.runtime.operator.edge.WorkcellDeviceAdapter; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +/** Only original-project continuation; never creates, loads or replaces a project. */ +@Service @RequiredArgsConstructor +public class ScannerSupplementAdapter implements WorkcellDeviceAdapter { + private final ScannerWorkflowAdapter driver; + private final ScannerService scanner; + private final ScannerMonitoringService monitoring; + private final ScannerSupplementSignals signals; + @Override public boolean supports(ActionEnum action){return action==ActionEnum.SCANNER_SUPPLEMENT_PREPARE||action==ActionEnum.SCANNER_SUPPLEMENT_WAIT;} + @Override public void validateConfiguration(String robot,String device){driver.validateConfiguration(robot,device);} + @Override public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message){ + var input=message.getInputParams();validateConfiguration(message.getRobotId(),input.getString("deviceId")); + if(message.getInstId()==null||message.getInstId().isBlank())throw new ScannerException("runtime_pending","补扫必须由任务工作台启动",409); + var expected=ScannerRequestValidator.parse(input.getString("expectedContextJson")); + var status=monitoring.status(expected); + if(message.getAction()==ActionEnum.SCANNER_SUPPLEMENT_PREPARE){ + if(status.path("scanning").asBoolean()||status.path("busy").asBoolean())throw new ScannerException("device_busy","请先停止当前采集,再开始补扫",409); + String mesh=status.path("meshState").asText(); + if(!java.util.Set.of("none","preview","confirmed").contains(mesh))throw new ScannerException("mesh_state_unknown","当前网格状态无法确认,不能补扫",409); + if(!"none".equals(mesh))scanner.executeBoundAndWait(ScannerOperation.MESH_UNDO,ScannerRequestValidator.parse("{}"), + ScannerService.hash("supplement-undo:"+message.getInstId()),"workflow:"+message.getInstId(),input.getLongValue("timeoutMs"),expected); + status=monitoring.status(expected); + if(!"none".equals(status.path("meshState").asText()))throw new ScannerException("mesh_not_cleared","原工程网格尚未撤销,不能开始补扫",409); + }else{ + long end=System.nanoTime()+java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(input.getLongValue("durationMs")); + signals.collecting(message.getInstId()); + while(System.nanoTime() guard.release(instId,ctx.getStatus()==TaskStatusEnum.SUCCESS)); + // Termination is not task success, but a confirmed physical stop is + // sufficient to release its native lease. Failed/uncertain cleanup + // keeps the durable STOP_PENDING lease for explicit confirmation. + boolean safeToRelease = ctx.getStatus() == TaskStatusEnum.SUCCESS + || (ctx.getStatus() == TaskStatusEnum.STOPPED && ctx.isDeviceStopConfirmed()); + if(occupationGuards!=null)occupationGuards.orderedStream().forEach(guard -> guard.release(instId,safeToRelease)); + // Keep context and in-memory locks if the durable release failed. + instContextMap.remove(instId, ctx); ctx.setTerminalStatus(TerminalStatusEnum.READY); ctx.setTerminalLocked(false); effectiveLockKeys(ctx).forEach(lockKey -> robotInstMap.remove(lockKey, instId)); diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/control/FlowControlService.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/control/FlowControlService.java index abe1bf9..3f3caad 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/control/FlowControlService.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/control/FlowControlService.java @@ -77,26 +77,46 @@ public class FlowControlService { stopPersistedTaskWithoutContext(instId, true); return; } - if (ctx.isStopped()) { - return; - } - // 先阻止节点继续执行,再清理设备与本地媒体会话,避免终止过程中重新登记录音/录像。 - taskInstHolder.syncStatus(instId, TaskStatusEnum.STOPPED); - if (asyncMediaAnalysisCoordinator != null) { - asyncMediaAnalysisCoordinator.cancelAll(instId); - } - taskThreadRegistry.interruptAll(instId); - // 终止必须等设备和后端媒体会话完成清理后再返回,防止立即重跑命中旧录音/录像状态。 - stopAllRobots(ctx); - deviceLifecycle.forEach(extension -> extension.afterStop(instId)); - taskInstHolder.unRegister(instId); - // 被中断的节点 状态修改成 PAUSED - for (TaskNodeExecuteContext pendingNode : taskThreadRegistry.getPendingNodes(instId)) { - String nodeId = pendingNode.getNode().getNodeId(); - nodeInstService.update(instId, nodeId, TaskStatusEnum.STOPPED); + synchronized (ctx) { + if (ctx.isStopped()) { + if (!ctx.isDeviceStopConfirmed()) throw stopUnconfirmed(); + // Retry a previously failed durable release without issuing another stop. + taskInstHolder.unRegister(instId); + return; + } + // 先阻止节点继续执行,再清理设备与本地媒体会话,避免终止过程中重新登记录音/录像。 + taskInstHolder.syncStatus(instId, TaskStatusEnum.STOPPED); + if (asyncMediaAnalysisCoordinator != null) { + asyncMediaAnalysisCoordinator.cancelAll(instId); + } + List interruptedNodes = taskThreadRegistry.getPendingNodes(instId); + taskThreadRegistry.interruptAll(instId); + // 终止必须等设备和后端媒体会话完成清理后再返回,防止立即重跑命中旧录音/录像状态。 + boolean devicesStopped = stopAllRobotsAndWait(ctx); + boolean nodesFinished = waitForInterruptedNodes(instId, interruptedNodes); + boolean lifecycleStopped = true; + for (FlowDeviceLifecycleExtension extension : deviceLifecycle) { + try { extension.afterStop(instId); } + catch (RuntimeException error) { + lifecycleStopped = false; + log.warn("终止设备会话清理未确认: instId={}, error={}", instId, error.getMessage()); + } + } + ctx.setDeviceStopConfirmed(devicesStopped && nodesFinished && lifecycleStopped); + taskInstHolder.unRegister(instId); + // 被中断的节点状态修改成 STOPPED。 + for (TaskNodeExecuteContext pendingNode : taskThreadRegistry.getPendingNodes(instId)) { + String nodeId = pendingNode.getNode().getNodeId(); + nodeInstService.update(instId, nodeId, TaskStatusEnum.STOPPED); + } + if (!ctx.isDeviceStopConfirmed()) throw stopUnconfirmed(); } } + private GlobalException stopUnconfirmed() { + return new GlobalException("流程已终止,但设备停止或旧节点退出尚未确认,资源占用已保留,请核对现场后确认停止并释放"); + } + /** Startup recovery entry: persistently closes an orphan without per-task warning logs. */ public void stopOrphaned(String instId) { TaskContext ctx = taskInstHolder.getContext(instId); @@ -335,23 +355,6 @@ public class FlowControlService { taskInstHolder.syncStatusAsResumed(instId); } - private void stopAllRobots(TaskContext context) { - List robotIds = context.getRobotIds() == null || context.getRobotIds().isEmpty() - ? Collections.singletonList(context.getRobotId()) - : context.getRobotIds(); - robotIds.stream() - .filter(robotId -> robotId != null && !robotId.isBlank()) - .distinct() - .forEach(robotId -> { - abortLocalMediaRecordings(robotId); - try { - edgeSystemService.stopAll(robotId); - } catch (RuntimeException exception) { - log.warn("终止机器人设备失败: robotId={}, error={}", robotId, exception.getMessage()); - } - }); - } - private List robotIds(TaskContext context) { return context.getRobotIds() == null || context.getRobotIds().isEmpty() ? Collections.singletonList(context.getRobotId()) : context.getRobotIds(); @@ -371,7 +374,7 @@ public class FlowControlService { edgeSystemService.stopAll(robotId); } catch (RuntimeException exception) { success = false; - log.warn("暂停机器人设备失败,恢复时将重试: robotId={}, error={}", + log.warn("停止机器人设备未确认,保留停止待确认状态: robotId={}, error={}", robotId, exception.getMessage()); } } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotTaskOccupationGuard.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotTaskOccupationGuard.java index cc3fdd2..4af01d6 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotTaskOccupationGuard.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/engine/RobotTaskOccupationGuard.java @@ -4,6 +4,7 @@ package com.cmvr.test.flow.runtime.engine; public interface RobotTaskOccupationGuard { void check(String robotId, String nativeTaskId); default void occupy(String instId, String nativeTaskId, java.util.List robotIds) {} - default void release(String instId, boolean success) {} + /** Release only after successful completion or confirmed stop; otherwise retain a pending lease. */ + default void release(String instId, boolean safeToRelease) {} default AutoCloseable manual(String robotId) { check(robotId,null);return ()->{}; } } diff --git a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/WorkcellNodeContract.java b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/WorkcellNodeContract.java index b267bac..46ced4d 100644 --- a/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/WorkcellNodeContract.java +++ b/am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/flow/runtime/operator/edge/WorkcellNodeContract.java @@ -17,14 +17,17 @@ public final class WorkcellNodeContract { ActionEnum.MOTOR_WAIT, ActionEnum.MOTOR_STOP, ActionEnum.MOTOR_STATUS); private WorkcellNodeContract() {} + private static boolean supplement(ActionEnum action) { + return action == ActionEnum.SCANNER_SUPPLEMENT_PREPARE || action == ActionEnum.SCANNER_SUPPLEMENT_WAIT; + } public static boolean supports(ActionEnum action) { - return action != null && (ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action)); + return action != null && (supplement(action) || ScannerOperation.forAction(action.getAction()) != null || MOTOR.contains(action)); } public static int deviceKind(ActionEnum action) { if (!supports(action)) throw new GlobalException("不是扫描仪或电机节点"); - return ScannerOperation.forAction(action.getAction()) != null ? 14 : 10; + return supplement(action) || ScannerOperation.forAction(action.getAction()) != null ? 14 : 10; } public static void validate(ActionEnum action, JSONObject input) { @@ -34,6 +37,16 @@ public final class WorkcellNodeContract { throw new GlobalException("timeoutMs 必须是 1 至 3600000 的整数毫秒"); } ScannerOperation scanner = ScannerOperation.forAction(action.getAction()); + if (supplement(action)) { + var context = ScannerRequestValidator.parse(required(input,"expectedContextJson")); + for (String name : java.util.List.of("sessionId","projectId","robotId","deviceId","endpoint")) + if (!context.path(name).isTextual() || context.path(name).asText().isBlank()) throw new GlobalException("补扫缺少原工程关联:"+name); + if (action == ActionEnum.SCANNER_SUPPLEMENT_WAIT) { + double duration=number(input,"durationMs"); + if(duration<1000 || duration>1800000 || duration!=Math.rint(duration))throw new GlobalException("补扫时长必须为1至1800秒"); + } + return; + } if (scanner != null) { if (scanner == ScannerOperation.TASK) scanner.route(required(input, "taskId")); else if (scanner.control()) { diff --git a/am-backend/yudao-module-cmvr/src/main/resources/mapper/resource/ResourceRobotMapper.xml b/am-backend/yudao-module-cmvr/src/main/resources/mapper/resource/ResourceRobotMapper.xml index 4b470a6..4398fe5 100644 --- a/am-backend/yudao-module-cmvr/src/main/resources/mapper/resource/ResourceRobotMapper.xml +++ b/am-backend/yudao-module-cmvr/src/main/resources/mapper/resource/ResourceRobotMapper.xml @@ -119,6 +119,12 @@ for update + + update iot_robot set connect_status=#{connectStatus}, runtime_status=#{status}, + last_heartbeat_time=#{lastHeartbeatTime}, update_by='scanner-http', update_time=#{updateTime} + where id=#{id} and coalesce(archived_status,'0')='0' + + update iot_robot set connect_status = '0', runtime_status = '1', update_by = 'heartbeat-timeout', update_time = #{offlineTime} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerIntegrationTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerIntegrationTest.java index 3017972..f70fb69 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerIntegrationTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerIntegrationTest.java @@ -30,6 +30,7 @@ public class ScannerIntegrationTest { private final AtomicInteger postDelayMs=new AtomicInteger(); private final java.util.concurrent.CountDownLatch statusEntered=new java.util.concurrent.CountDownLatch(1); private final AtomicReference session=new AtomicReference<>("S1"); + private final AtomicReference statusOverride=new AtomicReference<>(); private final List seen=new ArrayList<>(); private final String taskId="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; @@ -38,7 +39,9 @@ public class ScannerIntegrationTest { server.createContext("/",exchange->{ synchronized(seen){seen.add(exchange.getRequestMethod()+" "+exchange.getRequestURI());} assertNull(exchange.getRequestURI().getQuery()); - if(!exchange.getRequestURI().getPath().equals("/"))assertEquals("test-key",exchange.getRequestHeaders().getFirst("X-Api-Key")); + if(!exchange.getRequestURI().getPath().equals("/"))assertEquals("Bearer test-key",exchange.getRequestHeaders().getFirst("Authorization")); + else assertNull(exchange.getRequestHeaders().getFirst("Authorization")); + assertNull(exchange.getRequestHeaders().getFirst("X-Api-Key")); byte[] response;int code=200; if(exchange.getRequestMethod().equals("POST")){ assertTrue(exchange.getRequestHeaders().getFirst("Content-Type").startsWith("application/json")); @@ -53,7 +56,7 @@ public class ScannerIntegrationTest { response=("{\"taskId\":\""+(wrongTask.get()?"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb":taskId)+"\",\"state\":\""+(runningTask.get()?"running":failedTask.get()?"failed":"succeeded")+"\",\"result\":{\"projectId\":\"P1\"},\"error\":{\"code\":\"sdk_failed\",\"message\":\"device fault\"}}").getBytes(StandardCharsets.UTF_8); }else if(exchange.getRequestURI().getPath().contains("/files/")||exchange.getRequestURI().getPath().equals("/api/v1/preview/image")||exchange.getRequestURI().getPath().equals("/api/v1/preview/stream")){ response=new byte[]{1,2,3,4};exchange.getResponseHeaders().set("Content-Type","application/octet-stream");exchange.getResponseHeaders().set("X-Frame-Sequence","7"); - }else {statusEntered.countDown();delay(statusDelayMs.get());response=("{\"busy\":false,\"scanning\":"+scanning.get()+",\"sessionId\":\""+session.get()+"\",\"projectId\":\"P1\",\"stateUncertain\":false,\"restartRequired\":false}").getBytes(StandardCharsets.UTF_8);} + }else {statusEntered.countDown();delay(statusDelayMs.get());response=(statusOverride.get()!=null?statusOverride.get():"{\"busy\":false,\"scanning\":"+scanning.get()+",\"sessionId\":\""+session.get()+"\",\"projectId\":\"P1\",\"stateUncertain\":false,\"restartRequired\":false}").getBytes(StandardCharsets.UTF_8);} exchange.sendResponseHeaders(code,response.length);try(var out=exchange.getResponseBody()){out.write(response);} }); server.start(); @@ -64,6 +67,74 @@ public class ScannerIntegrationTest { journal=new ScannerCommandJournal(jdbc);service=new ScannerService(config,client,journal); } @After public void close(){if(server!=null)server.stop(0);} + @Test public void stoppedScannerWithoutAProjectConfirmsLocallyAndReplaysWithoutAnSdkTask() { + statusOverride.set("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false,\"projectId\":null}"); + var body=ScannerRequestValidator.parse("{}"); + var first=service.executeAndWait(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test",3000); + assertEquals("succeeded",first.path("state").asText()); + assertFalse(first.path("result").path("scanning").asBoolean(true)); + assertTrue(first.path("result").path("alreadyStopped").asBoolean()); + assertEquals("device_status",first.path("result").path("confirmationSource").asText()); + assertEquals("SUCCEEDED",journal.get("idle-stop-confirm").state()); + assertNull(journal.get("idle-stop-confirm").taskId());assertNull(journal.active(client.endpointKey())); + service=new ScannerService(config,client,journal);scanning.set(true);statusOverride.set(null); + assertEquals(first,service.executeAndWait(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test",3000)); + var receipt=service.submit(ScannerOperation.SCAN_STOP,body,"idle-stop-confirm","test"); + assertTrue(receipt.path("taskId").isNull());assertTrue(receipt.path("statusUrl").isNull()); + assertEquals(0,submissions.get()); // Replaying a completed stop cannot stop a later acquisition. + } + @Test public void activeAcquisitionStillRequiresTheRealSdkStopAndItsSuccessfulTask() { + scanning.set(true);failedTask.set(true); + assertEquals("sdk_failed",assertThrows(ScannerException.class,()->service.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"active-stop-error","test",3000)).scannerCode); + assertEquals(1,submissions.get());assertEquals("FAILED",journal.get("active-stop-error").state()); + scanning.set(true);failedTask.set(false); + service.executeAndWait(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"active-stop-ok","test",3000); + assertEquals(2,submissions.get());assertFalse(scanning.get());assertEquals(taskId,journal.get("active-stop-ok").taskId()); + } + @Test public void incompleteOrNonBooleanStatusCannotPretendToConfirmAnIdleStop() { + int index=0; + for(String field:List.of("scanning","busy","stateUncertain","restartRequired")) { + for(JsonNode invalid:List.of(ScannerRequestValidator.JSON.getNodeFactory().nullNode(),ScannerRequestValidator.JSON.getNodeFactory().textNode("false"))) { + var status=ScannerRequestValidator.parse("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false}"); + status.set(field,invalid);statusOverride.set(status.toString()); + var receipt=service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"incomplete-stop-"+index++,"test"); + assertEquals("ACCEPTED",receipt.path("state").asText()); + assertEquals(taskId,receipt.path("taskId").asText()); + service.waitCommand(receipt.path("commandKey").asText(),3000); + } + var missing=ScannerRequestValidator.parse(statusOverride.get());missing.remove(field);statusOverride.set(missing.toString()); + var receipt=service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"missing-stop-"+index++,"test"); + assertEquals("ACCEPTED",receipt.path("state").asText());service.waitCommand(receipt.path("commandKey").asText(),3000); + } + assertEquals(12,submissions.get()); + } + @Test public void unhealthyIdleStatusAndChangedProjectStillRejectStopBeforeAnyPost() { + for(String field:List.of("busy","stateUncertain","restartRequired")) { + var status=ScannerRequestValidator.parse("{\"scanning\":false,\"busy\":false,\"stateUncertain\":false,\"restartRequired\":false}"); + status.put(field,true);statusOverride.set(status.toString()); + assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"unsafe-stop-"+field,"test")); + assertNull(journal.get("unsafe-stop-"+field)); + } + statusOverride.set(null); + assertEquals("project_changed",assertThrows(ScannerException.class,()->service.submitBound(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"changed-idle-stop","test",ScannerRequestValidator.parse("{\"sessionId\":\"OTHER\",\"projectId\":\"P1\"}"))).scannerCode); + assertEquals(0,submissions.get()); + } + @Test public void idleStatusCannotBypassAnUnfinishedOrUncertainCommand() { + runningTask.set(true); + service.submit(ScannerOperation.CONNECT,ScannerRequestValidator.parse("{}"),"pending-initialize","test"); + assertEquals("command_busy",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"pending-idle-stop","test")).scannerCode); + journal.uncertain("pending-initialize","acceptance unknown"); + assertEquals("command_uncertain",assertThrows(ScannerException.class,()->service.submit(ScannerOperation.SCAN_STOP,ScannerRequestValidator.parse("{}"),"unknown-idle-stop","test")).scannerCode); + assertNull(journal.get("pending-idle-stop"));assertNull(journal.get("unknown-idle-stop"));assertEquals(1,submissions.get()); + } + @Test public void supplementalControlsCheckProjectAndEndpointBeforeAnyPost(){ + var expected=ScannerRequestValidator.parse("{\"endpoint\":\""+client.endpointKey()+"\",\"sessionId\":\"S1\",\"projectId\":\"P1\"}"); + session.set("OTHER"); + assertEquals("project_changed",assertThrows(ScannerException.class,()->service.executeBoundAndWait(ScannerOperation.MESH_UNDO,ScannerRequestValidator.parse("{}"),"bound-undo","workflow:inst",2000,expected)).scannerCode); + session.set("S1");expected.put("endpoint","another-endpoint"); + assertThrows(ScannerException.class,()->service.executeBoundAndWait(ScannerOperation.SCAN_START,ScannerRequestValidator.parse("{}"),"bound-start","workflow:inst",2000,expected)); + assertEquals(0,submissions.get());assertNull(journal.get("bound-undo")); + } private static void delay(int milliseconds) {try{Thread.sleep(milliseconds);}catch(InterruptedException error){Thread.currentThread().interrupt();}} @Test public void remoteWaitRejectsAnotherTasksSuccessfulResponse() { diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerMonitoringTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerMonitoringTest.java index f2304b3..f57eded 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerMonitoringTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerMonitoringTest.java @@ -59,6 +59,16 @@ public class ScannerMonitoringTest { assertThrows(ScannerException.class,()->monitoring.image(bound)); verify(scanner,never()).submit(any(),any(),anyString(),anyString()); } + @Test public void continuousFramesAreBoundToCurrentProjectAndRequireSequence() throws Exception { + var bound=capture(); + var frame=new ScannerMonitoringService.Frame(new byte[]{1},Map.of("X-Frame-Sequence",List.of("11"))); + assertEquals(11,monitoring.streamSequence(bound,frame)); + assertEquals("invalid_frame",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,new ScannerMonitoringService.Frame(new byte[0],Map.of()))).scannerCode); + when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","other-project")); + assertEquals("project_changed",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,frame)).scannerCode); + assertThrows(ScannerException.class,()->monitoring.stream(bound)); + verify(scanner,never()).binary(ScannerOperation.PREVIEW_STREAM,null); + } @Test public void snapshotAndItsFilesBelongToOneExecutionOnly() { capture(); when(scanner.submitBound(eq(ScannerOperation.SNAPSHOT),any(),anyString(),eq("workflow:inst-1"),any())).thenAnswer(invocation->{ diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerPreviewStreamTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerPreviewStreamTest.java new file mode 100644 index 0000000..3ba9907 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerPreviewStreamTest.java @@ -0,0 +1,40 @@ +package com.cmvr.scanner; + +import org.junit.Test; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import static org.junit.Assert.*; + +public class ScannerPreviewStreamTest { + private ScannerPreviewStream reader(byte[] bytes) { + InputStream fragmented=new ByteArrayInputStream(bytes) { + @Override public synchronized int read(byte[] b,int offset,int length){return super.read(b,offset,Math.min(length,3));} + }; + return new ScannerPreviewStream(new ScannerHttpClient.Binary(fragmented,Map.of("Content-Type",List.of("multipart/x-mixed-replace; boundary=scanframe")))); + } + private byte[] part(String headers,byte[] jpeg) throws IOException { + var output=new ByteArrayOutputStream(); + output.write(("--scanframe\r\nContent-Type: image/jpeg\r\n"+headers+"\r\n").getBytes(StandardCharsets.US_ASCII)); + output.write(jpeg);output.write("\r\n".getBytes(StandardCharsets.US_ASCII));return output.toByteArray(); + } + @Test public void parsesMultipleFragmentedFramesAndClosesAtFinalBoundary() throws Exception { + byte[] jpeg={(byte)255,(byte)216,13,10,(byte)255,(byte)217};var bytes=new ByteArrayOutputStream(); + bytes.write(part("Content-Length: 6\r\nX-Frame-Sequence: 20\r\n",jpeg)); + bytes.write(part("content-length: 6\r\nx-frame-sequence: 21\r\n",jpeg));bytes.write("--scanframe--\r\n".getBytes()); + try(var source=reader(bytes.toByteArray())) { + var one=source.next();assertArrayEquals(jpeg,one.bytes());assertEquals("20",one.headers().get("x-frame-sequence").get(0)); + assertArrayEquals(jpeg,source.next().bytes());assertNull(source.next()); + } + } + @Test public void rejectsOversizeDuplicateMissingAndTruncatedParts() throws Exception { + byte[] jpeg={(byte)255,(byte)216,(byte)255,(byte)217}; + for(String header:List.of("Content-Length: 99999999\r\n","Content-Length: 4\r\nContent-Length: 4\r\n","X-Frame-Sequence: 1\r\n","Content-Length: 20\r\n")) + try(var source=reader(part(header,jpeg))) {assertThrows(IOException.class,source::next);} + try(var source=reader(part("Content-Length: 4\r\n",new byte[4]))) {assertThrows(IOException.class,source::next);} + try(var source=reader(("--scanframe\r\nX-Test: "+"a".repeat(17000)).getBytes())) {assertThrows(IOException.class,source::next);} + } + @Test public void requiresMultipartAndSafeBoundary() { + assertThrows(ScannerException.class,()->new ScannerPreviewStream(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[0]),Map.of("content-type",List.of("image/jpeg"))))); + } +} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerResourceSynchronizerTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerResourceSynchronizerTest.java new file mode 100644 index 0000000..7726e95 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerResourceSynchronizerTest.java @@ -0,0 +1,106 @@ +package com.cmvr.scanner; + +import com.cmvr.common.exception.GlobalException; +import com.cmvr.resource.config.ResourceRobotStateProperties; +import com.cmvr.resource.domain.ResourceDevice; +import com.cmvr.resource.domain.ResourceRobot; +import com.cmvr.resource.mapper.ResourceDeviceMapper; +import com.cmvr.resource.mapper.ResourceRobotMapper; +import com.cmvr.resource.service.ResourceRobotEndpointResolver; +import com.cmvr.resource.service.ResourceRobotExecutionTargetResolver; +import org.junit.*; +import java.util.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class ScannerResourceSynchronizerTest { + ScannerProperties settings = new ScannerProperties(); + ScannerHttpClient client = mock(ScannerHttpClient.class); + ResourceRobotMapper robots = mock(ResourceRobotMapper.class); + ResourceDeviceMapper devices = mock(ResourceDeviceMapper.class); + ResourceRobotStateProperties state = new ResourceRobotStateProperties(); + ScannerResourceSynchronizer sync; + ResourceRobot robot; + + @Before public void setup() { + settings.setHost("localhost"); settings.setPort(18888); settings.setApiKey("test-key"); + settings.setRobotId("station"); settings.setDeviceId("scanner"); + sync = new ScannerResourceSynchronizer(settings, client, robots, devices, state); + robot = new ResourceRobot(); robot.setId("record"); robot.setRobotId("station"); + robot.setArchivedStatus("0"); robot.setConnectStatus("1"); robot.setLastHeartbeatTime(new Date()); + when(robots.selectByRobotIdentity("station")).thenReturn(robot); + when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of()); + when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenReturn( + ScannerRequestValidator.parse("{\"deviceOnline\":true,\"scanning\":false}")); + } + @Test public void discoversRealDeviceUsingOnlyBoundedStatusRead() { + sync.refresh(); + verify(client).json(ScannerOperation.STATUS, null, null, 3000); verifyNoMoreInteractions(client); + verify(robots).updateHttpScannerState(argThat(r -> "1".equals(r.getConnectStatus()) && r.getIpAddress() == null && r.getPort() == null)); + verify(devices).insert(argThat((ResourceDevice d) -> "station".equals(d.getRobotId()) && "scanner".equals(d.getDeviceId()) && d.getDeviceKind() == 14 && "1".equals(d.getOnlineStatus()) && d.getManagerState() == 4)); + } + @Test public void unavailableStatusMarksOfflineWithoutInventingDiscovery() { + when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenThrow(new ScannerException("unavailable", "offline", 503)); + sync.refresh(); + verify(robots).updateHttpScannerState(argThat(r -> "0".equals(r.getConnectStatus()))); + verify(devices, never()).insert(any(ResourceDevice.class)); + } + @Test public void respectsDisabledDeviceAndReportsUncertainStateAsFault() { + ResourceDevice device = new ResourceDevice(); device.setId("device-record"); device.setDeviceKind(14); device.setEnabled("0"); + when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of(device)); + when(client.json(ScannerOperation.STATUS, null, null, 3000)).thenReturn(ScannerRequestValidator.parse("{\"deviceOnline\":true,\"stateUncertain\":true}")); + sync.refresh(); verify(devices).updateRuntimeState(argThat(d -> "0".equals(d.getEnabled()) && "1".equals(d.getHasError()) && d.getHealthStatus() == 3)); + } + @Test public void archivedUnboundAndConflictingDevicesAreNeverOverwritten() { + robot.setArchivedStatus("1"); sync.refresh(); verifyNoInteractions(client); + robot.setArchivedStatus("0"); + ResourceDevice wrong = new ResourceDevice(); wrong.setDeviceKind(1); + when(devices.selectByIdentity("station", "scanner")).thenReturn(List.of(wrong)); sync.refresh(); verifyNoInteractions(client); + settings.setDeviceId(""); sync.refresh(); verifyNoInteractions(client); + } + @Test public void expiredOrOfflineStationCannotResolve() { + sync.validateTarget("station"); + robot.setConnectStatus("0"); assertThrows(GlobalException.class, () -> sync.validateTarget("station")); + robot.setConnectStatus("1"); robot.setLastHeartbeatTime(new Date(0)); + assertThrows(GlobalException.class, () -> sync.validateTarget("station")); + } + @Test public void httpStationDoesNotResolveAsGrpcButOtherRobotsStillDo() { + ResourceRobotEndpointResolver endpoints = mock(ResourceRobotEndpointResolver.class); + var resolver = new ResourceRobotExecutionTargetResolver(endpoints, state, sync); + assertEquals("station", resolver.resolve("station").getRobotId()); verifyNoInteractions(endpoints); + resolver.resolve("other"); verify(endpoints).resolve("other"); + } + @Test public void compactBusyResponseNeverOverwritesMeasuredDeviceOnlineState() { + for(String json:List.of("{\"busy\":true,\"state\":\"busy\"}","{\"busy\":true,\"deviceOnline\":null}")) { + clearInvocations(robots,devices); + when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse(json)); + sync.refresh(); + verify(robots).updateHttpScannerState(argThat(r->"1".equals(r.getConnectStatus())&&"3".equals(r.getStatus()))); + verify(devices,never()).updateRuntimeState(any());verify(devices,never()).insert(any(ResourceDevice.class)); + } + robot.setConnectStatus("0");sync.refresh(); + verify(robots).updateHttpScannerState(argThat(r->"0".equals(r.getConnectStatus()))); + } + @Test public void explicitOfflineDisconnectedAndFaultAreNotHiddenByBusy() { + for(String json:List.of("{\"busy\":true,\"deviceOnline\":false}","{\"busy\":true,\"initialized\":false,\"state\":\"disconnected\"}","{\"busy\":true,\"stateUncertain\":true}")) { + clearInvocations(robots,devices); + when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse(json)); + sync.refresh();verify(robots).updateHttpScannerState(argThat(r->"0".equals(r.getConnectStatus()))); + } + } + @Test public void runtimeStateUsesPlatformEnumRatherThanOnlineBoolean() { + ResourceDevice device = new ResourceDevice();device.setId("device-record");device.setDeviceKind(14);device.setEnabled("1"); + when(devices.selectByIdentity("station","scanner")).thenReturn(List.of(device)); + String[] statuses={"{\"deviceOnline\":true,\"scanning\":true}","{\"deviceOnline\":true,\"busy\":true}","{\"deviceOnline\":true,\"stateUncertain\":true}","{\"deviceOnline\":false}"}; + int[] expected={5,5,7,6}; + for(int i=0;id.getManagerState()==value)); + } + device.setEnabled("0");clearInvocations(devices); + when(client.json(ScannerOperation.STATUS,null,null,3000)).thenReturn(ScannerRequestValidator.parse("{\"deviceOnline\":true}")); + sync.refresh();verify(devices).updateRuntimeState(argThat(d->d.getManagerState()==1&&"0".equals(d.getEnabled()))); + } +} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerSupplementAdapterTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerSupplementAdapterTest.java new file mode 100644 index 0000000..fc43389 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerSupplementAdapterTest.java @@ -0,0 +1,41 @@ +package com.cmvr.scanner; + +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.test.enums.ActionEnum; +import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage; +import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract; +import org.junit.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class ScannerSupplementAdapterTest { + private final ScannerWorkflowAdapter driver=mock(ScannerWorkflowAdapter.class); + private final ScannerService scanner=mock(ScannerService.class); + private final ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class); + private final ScannerSupplementSignals signals=mock(ScannerSupplementSignals.class); + private final ScannerSupplementAdapter adapter=new ScannerSupplementAdapter(driver,scanner,monitoring,signals); + private final String context="{\"endpoint\":\"endpoint\",\"sessionId\":\"S1\",\"projectId\":\"P1\",\"robotId\":\"station\",\"deviceId\":\"scanner\"}"; + private TaskNodeExecuteMessage message(ActionEnum action){var m=new TaskNodeExecuteMessage();m.setInstId("inst");m.setRobotId("station");m.setAction(action);m.setInputParams(JSONObject.of("deviceId","scanner","timeoutMs",1000,"durationMs",1000,"expectedContextJson",context));return m;} + @Test public void completedMeshIsUndoneOnceBeforeReusingOriginalProject(){ + when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"confirmed\"}"),ScannerRequestValidator.parse("{\"meshState\":\"none\"}")); + var m=message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE);WorkcellNodeContract.validate(m.getAction(),m.getInputParams());adapter.execute(m); + verify(scanner).executeBoundAndWait(eq(ScannerOperation.MESH_UNDO),any(),anyString(),eq("workflow:inst"),eq(1000L),any());verifyNoMoreInteractions(scanner); + } + @Test public void unmeshedProjectIsNotChangedAndBusyOrForeignProjectsNeverSendControls(){ + when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"none\"}"));adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE));verifyNoInteractions(scanner); + when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{\"meshState\":\"none\",\"scanning\":true}")); + assertThrows(ScannerException.class,()->adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE)));verifyNoInteractions(scanner); + when(monitoring.status(any())).thenThrow(new ScannerException("project_changed","wrong project",409)); + assertThrows(ScannerException.class,()->adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_PREPARE)));verifyNoInteractions(scanner); + } + @Test public void manualFinishLeavesTheWaitForTheNormalStopAndExportNodes(){ + when(monitoring.status(any())).thenReturn(ScannerRequestValidator.parse("{}"));when(signals.finishRequested("inst")).thenReturn(true); + adapter.execute(message(ActionEnum.SCANNER_SUPPLEMENT_WAIT));verify(signals).collecting("inst");verify(signals).processing("inst");verifyNoInteractions(scanner); + } + @Test public void waitContractRequiresOriginalIdentityAndBoundsAcquisitionTime(){ + var m=message(ActionEnum.SCANNER_SUPPLEMENT_WAIT);WorkcellNodeContract.validate(m.getAction(),m.getInputParams()); + assertEquals(14,WorkcellNodeContract.deviceKind(m.getAction())); + m.getInputParams().put("durationMs",1800001);assertThrows(RuntimeException.class,()->WorkcellNodeContract.validate(m.getAction(),m.getInputParams())); + m.getInputParams().put("durationMs",1000);m.getInputParams().put("expectedContextJson","{}");assertThrows(RuntimeException.class,()->WorkcellNodeContract.validate(m.getAction(),m.getInputParams())); + } +} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerWorkflowReadinessTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerWorkflowReadinessTest.java new file mode 100644 index 0000000..6302251 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/scanner/ScannerWorkflowReadinessTest.java @@ -0,0 +1,45 @@ +package com.cmvr.scanner; + +import com.alibaba.fastjson2.JSONObject; +import com.cmvr.test.enums.ActionEnum; +import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage; +import org.junit.Test; +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +public class ScannerWorkflowReadinessTest { + @Test public void supplementCannotSucceedWithoutBindingItsOwnPreviewAndResults() { + var scanner=mock(ScannerService.class);var monitoring=mock(ScannerMonitoringService.class);var resources=mock(ScannerResourceSynchronizer.class); + var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner"); + var adapter=new ScannerWorkflowAdapter(scanner,settings,mock(ScannerAccessService.class),monitoring,resources); + var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_START); + message.setInputParams(JSONObject.of("deviceId","scanner","timeoutMs",120000,"requestJson","{}","expectedContextJson","{\"sessionId\":\"s\",\"projectId\":\"p\"}")); + when(scanner.executeBoundAndWait(any(),any(),anyString(),anyString(),anyLong(),any())).thenReturn(ScannerRequestValidator.parse("{\"state\":\"succeeded\"}")); + assertEquals("binding_invalid",assertThrows(ScannerException.class,()->adapter.execute(message)).scannerCode); + verify(scanner).executeBoundAndWait(any(),any(),anyString(),anyString(),anyLong(),any()); + } + @Test public void refreshesRealResourceStatusAfterCommandCompletesBeforeBindingPreview() { + var scanner=mock(ScannerService.class);var access=mock(ScannerAccessService.class); + var monitoring=mock(ScannerMonitoringService.class);var resources=mock(ScannerResourceSynchronizer.class); + var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner"); + var adapter=new ScannerWorkflowAdapter(scanner,settings,access,monitoring,resources); + var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setNodeId("create");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_CREATE_PROJECT); + var input=new JSONObject();input.put("deviceId","scanner");input.put("timeoutMs",120000);input.put("requestJson","{\"mode\":\"trak\"}");message.setInputParams(input); + when(scanner.executeAndWait(eq(ScannerOperation.CREATE_PROJECT),any(),anyString(),eq("workflow:instance"),eq(120000L))) + .thenReturn(ScannerRequestValidator.parse("{\"state\":\"succeeded\"}")); + adapter.execute(message); + var ordered=inOrder(scanner,resources,monitoring); + ordered.verify(scanner).executeAndWait(eq(ScannerOperation.CREATE_PROJECT),any(),anyString(),eq("workflow:instance"),eq(120000L)); + ordered.verify(resources).refresh();ordered.verify(monitoring).capture(eq(ScannerOperation.CREATE_PROJECT),anyString(),eq("instance"),eq("station"),eq("scanner")); + verifyNoInteractions(access); + } + @Test public void failedCommandNeverPretendsToRefreshIntoSuccess() { + var scanner=mock(ScannerService.class);var resources=mock(ScannerResourceSynchronizer.class);var monitoring=mock(ScannerMonitoringService.class); + var settings=new ScannerProperties();settings.setHost("localhost");settings.setPort(18888);settings.setApiKey("test-key");settings.setRobotId("station");settings.setDeviceId("scanner"); + var adapter=new ScannerWorkflowAdapter(scanner,settings,mock(ScannerAccessService.class),monitoring,resources); + var message=new TaskNodeExecuteMessage();message.setInstId("instance");message.setRobotId("station");message.setAction(ActionEnum.SCANNER_STOP); + var input=new JSONObject();input.put("deviceId","scanner");input.put("timeoutMs",120000);input.put("requestJson","{}");message.setInputParams(input); + when(scanner.executeAndWait(any(),any(),anyString(),anyString(),anyLong())).thenThrow(new ScannerException("sdk_timeout","timeout",504)); + assertThrows(ScannerException.class,()->adapter.execute(message));verifyNoInteractions(resources,monitoring); + } +} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/control/FlowStopOccupationTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/control/FlowStopOccupationTest.java new file mode 100644 index 0000000..383c013 --- /dev/null +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/control/FlowStopOccupationTest.java @@ -0,0 +1,81 @@ +package com.cmvr.test.flow.control; + +import com.cmvr.common.exception.GlobalException; +import com.cmvr.edge.client.service.*; +import com.cmvr.test.enums.*; +import com.cmvr.test.flow.builder.FlowNodeWrapper; +import com.cmvr.test.flow.context.*; +import com.cmvr.test.flow.runtime.engine.RobotTaskOccupationGuard; +import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher; +import com.cmvr.test.flow.runtime.message.TaskNodeExecuteContext; +import com.cmvr.test.service.*; +import org.junit.*; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.test.util.ReflectionTestUtils; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; + +public class FlowStopOccupationTest { + private TaskContext context; + private TaskContextManager manager; + private RobotTaskOccupationGuard guard; + private EdgeSystemService edge; + private TaskThreadRegistry threads; + private FlowControlService control; + + @Before public void setup() { + guard=mock(RobotTaskOccupationGuard.class); + @SuppressWarnings("unchecked") ObjectProvider provider=mock(ObjectProvider.class); + when(provider.orderedStream()).thenAnswer(call->Stream.of(guard)); + manager=new TaskContextManager();ReflectionTestUtils.setField(manager,"occupationGuards",provider); + context=new TaskContext();context.setInstId("trial-1");context.setRobotId("scanner"); + context.setRobotIds(List.of("scanner"));context.setLockKeys(List.of("robot:scanner"));context.setStatus(TaskStatusEnum.RUNNING); + manager.register(context); + var nodes=mock(ITeNodeInstService.class);var tasks=mock(ITeTaskInstService.class); + var holder=new TaskInstHolder(nodes,manager,tasks,mock(FlowExecutionEventPublisher.class)); + edge=mock(EdgeSystemService.class);when(edge.stopAll(anyString())).thenReturn("ACKNOWLEDGED"); + threads=mock(TaskThreadRegistry.class);when(threads.getPendingNodes("trial-1")).thenReturn(List.of()); + control=new FlowControlService(null,holder,nodes,threads,null,edge,mock(EdgeMicrophoneService.class),mock(EdgeCameraService.class),tasks); + } + + @Test public void acknowledgedTrialStopReleasesWithoutPretendingTaskSucceeded() { + control.stop("trial-1"); + assertEquals(TaskStatusEnum.STOPPED,context.getStatus());assertTrue(context.isDeviceStopConfirmed()); + verify(guard).release("trial-1",true);assertNull(manager.get("trial-1"));assertFalse(manager.isRobotLocked("robot:scanner")); + } + @Test public void failedPhysicalStopRetainsDurableOccupationAndReturnsActionableError() { + when(edge.stopAll("scanner")).thenThrow(new GlobalException("stop timeout")); + var error=assertThrows(GlobalException.class,()->control.stop("trial-1")); + assertTrue(error.getMessage().contains("占用已保留"));assertFalse(context.isDeviceStopConfirmed()); + verify(guard).release("trial-1",false);verify(guard,never()).release("trial-1",true); + } + @Test public void everyAssignedRobotMustAcknowledgeStop() { + context.setRobotIds(List.of("scanner","motor"));when(edge.stopAll("motor")).thenThrow(new GlobalException("offline")); + assertThrows(GlobalException.class,()->control.stop("trial-1")); + verify(edge).stopAll("scanner");verify(edge).stopAll("motor");verify(guard).release("trial-1",false); + } + @Test public void acknowledgedDeviceDoesNotReleaseWhileAnOldNodeHasNotExited() throws Exception { + var pending=mock(TaskNodeExecuteContext.class);var node=mock(FlowNodeWrapper.class); + when(node.getNodeType()).thenReturn(NodeTypeEnum.SLEEP);when(node.getNodeId()).thenReturn("wait");when(pending.getNode()).thenReturn(node); + when(pending.awaitExecutionFinished(anyLong(),eq(TimeUnit.NANOSECONDS))).thenReturn(false); + when(threads.getPendingNodes("trial-1")).thenReturn(List.of(pending)); + assertThrows(GlobalException.class,()->control.stop("trial-1")); + verify(guard).release("trial-1",false);assertFalse(context.isDeviceStopConfirmed()); + } + @Test public void durableReleaseFailureKeepsContextAndRetryDoesNotSendAnotherStop() { + doThrow(new GlobalException("database unavailable")).doNothing().when(guard).release("trial-1",true); + assertThrows(GlobalException.class,()->control.stop("trial-1")); + assertSame(context,manager.get("trial-1"));assertTrue(manager.isRobotLocked("robot:scanner")); + control.stop("trial-1"); + verify(edge,times(1)).stopAll("scanner");verify(guard,times(2)).release("trial-1",true); + assertNull(manager.get("trial-1"));assertFalse(manager.isRobotLocked("robot:scanner")); + } + @Test public void failedTaskDoesNotReuseAStopAcknowledgementToRelease() { + context.setStatus(TaskStatusEnum.FAILED);context.setDeviceStopConfirmed(true); + manager.unregister("trial-1");verify(guard).release("trial-1",false); + } +} diff --git a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/runtime/operator/edge/EdgeWorkcellOperateServiceTest.java b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/runtime/operator/edge/EdgeWorkcellOperateServiceTest.java index 69b1d76..193da0b 100644 --- a/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/runtime/operator/edge/EdgeWorkcellOperateServiceTest.java +++ b/am-backend/yudao-module-cmvr/src/test/java/com/cmvr/test/flow/runtime/operator/edge/EdgeWorkcellOperateServiceTest.java @@ -54,7 +54,7 @@ public class EdgeWorkcellOperateServiceTest { @Test public void scannerConfigurationAndIdentityAreCheckedWithoutSendingCommands() { var settings=new com.cmvr.scanner.ScannerProperties(); - var adapter=new com.cmvr.scanner.ScannerWorkflowAdapter(null,settings,null,null); + var adapter=new com.cmvr.scanner.ScannerWorkflowAdapter(null,settings,null,null,null); assertEquals("not_configured",assertThrows(com.cmvr.scanner.ScannerException.class, ()->adapter.validateConfiguration("station","scanner")).scannerCode); settings.setHost("127.0.0.1");settings.setPort(18888);settings.setApiKey("fixture"); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabScannerViewController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabScannerViewController.java index a606409..53f11bf 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabScannerViewController.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/cmvr/LabScannerViewController.java @@ -49,6 +49,25 @@ public class LabScannerViewController { frame.headers().forEach((name,values)->{if(name.toLowerCase(Locale.ROOT).startsWith("x-frame-")&&!values.isEmpty())headers.put(name,values);}); return ResponseEntity.ok().headers(headers).body(frame.bytes()); } + @GetMapping("/stream") + public ResponseEntity stream(@RequestParam Long executionId) { + views.checkStream(executionId); + Long tenant=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getRequiredTenantId(); + return ResponseEntity.ok().contentType(MediaType.parseMediaType("multipart/x-mixed-replace; boundary=scanframe")) + .cacheControl(CacheControl.noStore()).header("X-Accel-Buffering","no").body(output->{ + Long previous=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getTenantId(); + boolean ignored=cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.isIgnore(); + try { + cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(tenant); + cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(false); + views.stream(executionId,output); + }catch(ScannerException closed){/* End multipart on task/project changes; the client rechecks metadata. */} + finally { + cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setTenantId(previous); + cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.setIgnore(ignored); + } + }); + } @ExceptionHandler(ScannerException.class) public CommonResult scannerError(ScannerException error){return CommonResult.error(error.remoteStatus,error.getMessage());} } diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/scanonly/ScanOnlyTaskController.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/scanonly/ScanOnlyTaskController.java index 1facd14..35a1116 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/scanonly/ScanOnlyTaskController.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/controller/admin/scanonly/ScanOnlyTaskController.java @@ -37,6 +37,12 @@ public class ScanOnlyTaskController { public CommonResult clearOccupation(@Valid @RequestBody ScanTaskRequests.ClearOccupation request) { resources.clearOccupation(request.getOwnerKey(),request.getReason());return success(true); } @PostMapping("/start-unit") @PreAuthorize("@ss.hasPermission('lab:execution:dispatch')") public CommonResult start(@Valid @RequestBody ScanTaskRequests.Start request) { return success(service.startUnit(request)); } + @GetMapping("/supplement-option") @PreAuthorize("@ss.hasPermission('lab:task:query')") + public CommonResult> supplementOption(@RequestParam Long taskId,@RequestParam Long unitId){return success(service.supplementOption(taskId,unitId));} + @PostMapping("/supplement") @PreAuthorize("@ss.hasPermission('lab:execution:dispatch')") + public CommonResult supplement(@Valid @RequestBody ScanTaskRequests.Supplement request){return success(service.startSupplement(request));} + @PostMapping("/finish-supplement") @PreAuthorize("@ss.hasPermission('lab:execution:control')") + public CommonResult finishSupplement(@Valid @RequestBody ScanTaskRequests.FinishSupplement request){service.finishSupplement(request);return success(true);} @PostMapping("/cancel") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')") public CommonResult cancel(@Valid @RequestBody ScanTaskRequests.Task request) { service.cancel(request.getTaskId(),request.getReason()); return success(true); } @PostMapping("/confirm-stop") @PreAuthorize("@ss.hasPermission('lab:execution:cancel')") diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionFlowEngine.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionFlowEngine.java index 4bd9088..26e6b05 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionFlowEngine.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionFlowEngine.java @@ -340,7 +340,9 @@ public class DetectionFlowEngine { Files.writeString(arguments, String.join(System.lineSeparator(), command.subList(1, command.size()) .stream().map(this::launcherArgument).toList()), StandardCharsets.UTF_8); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); - Process process = new ProcessBuilder(command.get(0), "@" + arguments).redirectErrorStream(true).start(); + // Standard output is the worker's JSON protocol. JVM diagnostics belong to stderr. + Process process = new ProcessBuilder(command.get(0), "@" + arguments) + .redirectError(ProcessBuilder.Redirect.DISCARD).start(); FutureTask readOutput = new FutureTask<>(() -> process.getInputStream().readNBytes(1_100_000)); Thread reader = new Thread(readOutput, "detection-script-output"); reader.setDaemon(true); reader.start(); try { @@ -349,6 +351,7 @@ public class DetectionFlowEngine { long remaining = Math.max(0, deadline - System.nanoTime()); if (!process.waitFor(remaining, TimeUnit.NANOSECONDS)) throw new IllegalArgumentException("脚本执行超时(" + timeoutSeconds + "秒,含 JVM 冷启动)"); + if (process.exitValue() != 0) throw new IllegalArgumentException("脚本子进程异常退出,退出码:" + process.exitValue()); String text = new String(readOutput.get(2, TimeUnit.SECONDS), StandardCharsets.UTF_8); JsonNode response = read(text); if (!response.path("ok").asBoolean(false)) throw new IllegalArgumentException(response.path("error").asText("脚本执行失败")); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionScriptWorker.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionScriptWorker.java index a8c5727..f48efe0 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionScriptWorker.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/detection/DetectionScriptWorker.java @@ -15,6 +15,9 @@ public final class DetectionScriptWorker { if (bytes.length > 2_097_152) throw new IllegalArgumentException("脚本参数超过 2MB"); var request = json.readTree(new String(bytes, StandardCharsets.UTF_8)); var engine = new NashornScriptEngineFactory().getScriptEngine(new String[]{"--language=es6"}, null, className -> false); + // Script print() must not corrupt the JSON response written to System.out. + engine.getContext().setWriter(java.io.Writer.nullWriter()); + engine.getContext().setErrorWriter(java.io.Writer.nullWriter()); String wrapped = "(function(){'use strict';\n" + request.path("code").asText() + "\n;return JSON.stringify(handler(JSON.parse(" + json.writeValueAsString(request.path("params").toString()) + ")));})()"; Object result = engine.eval(wrapped); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/document/LabDocumentServiceImpl.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/document/LabDocumentServiceImpl.java index fbaf2b3..acc90f9 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/document/LabDocumentServiceImpl.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/document/LabDocumentServiceImpl.java @@ -91,6 +91,11 @@ public class LabDocumentServiceImpl implements LabDocumentService { } private Long persistReport(LabReportSaveReqVO reqVO, boolean integration) { + if (StrUtil.isBlank(reqVO.getTitle())) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException("报告标题不能为空"); + requireTextLength(reqVO.getTitle(),256,"报告标题"); + requireTextLength(reqVO.getReportType(),32,"报告类型"); + requireTextLength(reqVO.getIdempotencyKey(),64,"幂等标识"); + requireTextLength(reqVO.getExternalReportNo(),64,"外部报告编号"); String key = StrUtil.blankToDefault(reqVO.getIdempotencyKey(), UUID.randomUUID().toString()); LabReportDO existed = reportMapper.selectByIdempotencyKey(key); if (existed != null) { @@ -133,6 +138,7 @@ public class LabDocumentServiceImpl implements LabDocumentService { @Override @Transactional(rollbackFor = Exception.class) public void updateDraft(Long id, String contentHtml, String title) { + requireTextLength(title,256,"报告标题"); LabReportDO report = lockReport(id); List versions = versionMapper.selectListByReportId(id); LabReportVersionDO existingDraft = versions.stream().filter(item -> "DRAFT".equals(item.getStatus())) @@ -169,6 +175,10 @@ public class LabDocumentServiceImpl implements LabDocumentService { } } + private static void requireTextLength(String value,int maximum,String label) { + if (value != null && value.length() > maximum) throw cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.invalidParamException(label + "最多" + maximum + "个字符"); + } + @Override @Transactional(rollbackFor = Exception.class) public void publish(Long id) { diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchive.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchive.java new file mode 100644 index 0000000..9801b5a --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchive.java @@ -0,0 +1,67 @@ +package cn.iocoder.yudao.module.lab.service.execution; + +import cn.iocoder.yudao.module.lab.framework.config.LabBizProperties; +import com.cmvr.scanner.*; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import java.io.*; +import java.nio.file.*; +import java.util.*; + +/** Execution-scoped copies keep old exports stable when the vendor reuses output names. */ +@Service @RequiredArgsConstructor +public class LabScannerAssetArchive { + private final LabBizProperties properties; + private final ScannerMonitoringService monitoring; + private Path path(Long execution,String file){ + CmvrMethodBindingService.requirePrimaryTenant(); + if(execution==null||execution<=0||file==null||!file.matches("[a-fA-F0-9]{32}"))throw new ScannerException("invalid_file","成果编号无效",400); + return Path.of(properties.getArtifact().getNasRoot()).toAbsolutePath().normalize().resolve("1").resolve(execution.toString()).resolve("scanner-files").resolve(file); + } + public void archive(Long execution,String instance){ + for(JsonNode file:monitoring.assets(instance)){ + String id=file.path("fileId").asText();Path target=path(execution,id),temporary=null; + if(Files.isRegularFile(target)&&Files.isRegularFile(target.resolveSibling(id+".json")))continue; + try{ + Files.createDirectories(target.getParent());temporary=Files.createTempFile(target.getParent(),id,".part");long bytes=0; + var digest=java.security.MessageDigest.getInstance("SHA-256"); + try(var source=monitoring.asset(instance,id);var out=Files.newOutputStream(temporary)){ + byte[] buffer=new byte[65536];int n; + while((n=source.stream().read(buffer))!=-1){bytes+=n;if(bytes>100L*1024*1024)throw new IOException("单个成果超过100MiB归档限制");digest.update(buffer,0,n);out.write(buffer,0,n);} + } + if(bytes==0||file.path("bytes").asLong()>0&&bytes!=file.path("bytes").asLong())throw new IOException("成果长度与设备登记不一致"); + var metadata=(com.fasterxml.jackson.databind.node.ObjectNode)file.deepCopy();metadata.remove("binding");metadata.put("bytes",bytes);metadata.put("sha256",HexFormat.of().formatHex(digest.digest())); + Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);temporary=null; + Files.writeString(target.resolveSibling(id+".json"),metadata.toString(),java.nio.charset.StandardCharsets.UTF_8); + }catch(Exception error){throw new ScannerException("archive_failed","成果归档失败,请保留原扫描工程并重试:"+error.getMessage(),503);} + finally{if(temporary!=null)try{Files.deleteIfExists(temporary);}catch(IOException ignored){}} + } + } + /** The execution directory is the ownership boundary, independent of a live device or command lookup. */ + public List list(Long execution){ + Path directory=path(execution,"00000000000000000000000000000000").getParent(); + if(!Files.isDirectory(directory))return List.of(); + try(var entries=Files.list(directory)){ + List files=new ArrayList<>(); + for(Path metadata:entries.filter(p->p.getFileName().toString().matches("[a-fA-F0-9]{32}\\.json")).toList()){ + String id=metadata.getFileName().toString().substring(0,32);Path target=directory.resolve(id); + if(!Files.isRegularFile(target))continue; + var record=ScannerRequestValidator.JSON.readTree(Files.readString(metadata)); + if(!record.isObject()||record.path("bytes").asLong()<=0||Files.size(target)!=record.path("bytes").asLong())throw new IOException("归档长度校验失败"); + var item=(com.fasterxml.jackson.databind.node.ObjectNode)record.deepCopy();item.remove(List.of("binding","sha256"));item.put("fileId",id);item.put("archived",true);files.add(item); + } + files.sort(Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed().thenComparing(file->file.path("fileId").asText())); + return files; + }catch(IOException error){throw new ScannerException("archive_unavailable","本次执行归档不可读,请检查成果存储",503);} + } + public ScannerHttpClient.Binary open(Long execution,String file){ + Path target=path(execution,file),metadata=target.resolveSibling(file+".json"); + if(!Files.isRegularFile(target)||!Files.isRegularFile(metadata))return null; + try{ + var record=ScannerRequestValidator.JSON.readTree(Files.readString(metadata)); + if(Files.size(target)!=record.path("bytes").asLong())throw new IOException("归档长度校验失败"); + return new ScannerHttpClient.Binary(Files.newInputStream(target),Map.of("content-type",List.of("application/octet-stream"),"content-length",List.of(String.valueOf(Files.size(target))))); + }catch(IOException error){throw new ScannerException("archive_unavailable","本次执行归档不可读,请检查成果存储",503);} + } +} diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewService.java index b61335d..f94265f 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewService.java @@ -15,11 +15,13 @@ import java.util.List; @Service @RequiredArgsConstructor public class LabScannerViewService { + private static final java.util.concurrent.Semaphore STREAM_SLOTS=new java.util.concurrent.Semaphore(4); private final LabExecutionMapper executions; private final CmvrExecutionBridge bridge; private final TaskInstHolder runtime; private final ScannerProperties settings; private final ScannerMonitoringService monitoring; + private final LabScannerAssetArchive archives; public ObjectNode view(Long executionId) { LabExecutionDO execution=required(executionId); @@ -55,6 +57,28 @@ public class LabScannerViewService { var link=requiredRuntime(id); return monitoring.snapshot(link.getCmvrInstId(),key); } + public void checkStream(Long id) { + var link=requiredRuntime(id);monitoring.status(monitoring.binding(link.getCmvrInstId())); + } + public void stream(Long id,java.io.OutputStream output) throws java.io.IOException { + if(!STREAM_SLOTS.tryAcquire())throw new ScannerException("stream_busy","实时预览连接已满,请关闭其他预览窗口",429); + try { + var link=requiredRuntime(id);JsonNode binding=monitoring.binding(link.getCmvrInstId()); + long sequence=binding==null?0:binding.path("baselineSequence").asLong(); + try(var source=monitoring.stream(binding)) { + ScannerMonitoringService.Frame frame; + while((frame=source.next())!=null) { + var current=requiredRuntime(id);var latest=monitoring.binding(current.getCmvrInstId()); + if(!current.getCmvrInstId().equals(link.getCmvrInstId())||latest==null||!latest.path("commandKey").equals(binding.path("commandKey"))) + throw new ScannerException("execution_changed","扫描工程关联已变化,停止原画面流",409); + long next=monitoring.streamSequence(binding,frame);if(next<=sequence)continue;sequence=next; + String header="--scanframe\r\nContent-Type: image/jpeg\r\nContent-Length: "+frame.bytes().length+"\r\nX-Frame-Sequence: "+sequence+"\r\n\r\n"; + output.write(header.getBytes(java.nio.charset.StandardCharsets.US_ASCII));output.write(frame.bytes()); + output.write(new byte[]{13,10});output.flush(); + } + } + }finally{STREAM_SLOTS.release();} + } public ScannerCommandJournal.Entry snapshotCommand(Long id,String key) { required(id);var link=bridge.get(id); if(link==null||link.getCmvrInstId()==null)throw new ScannerException("runtime_pending","没有本次执行的工作流记录",404); @@ -62,12 +86,23 @@ public class LabScannerViewService { } public List assets(Long id) { required(id);var link=bridge.get(id); - if(link==null||link.getCmvrInstId()==null)return List.of(); - return monitoring.assets(link.getCmvrInstId()).stream().map(file->{var value=(ObjectNode)file.deepCopy();value.remove("binding");return (JsonNode)value;}).toList(); + var files=new java.util.LinkedHashMap(); + if(link!=null&&link.getCmvrInstId()!=null)for(var file:monitoring.assets(link.getCmvrInstId())) { + var value=(ObjectNode)file.deepCopy();value.remove("binding");files.put(value.path("fileId").asText(),value); + } + for(var file:archives.list(id)) { + var existing=files.get(file.path("fileId").asText()); + var value=existing==null?(ObjectNode)file.deepCopy():(ObjectNode)existing.deepCopy(); + value.setAll((ObjectNode)file);files.put(value.path("fileId").asText(),value); + } + return files.values().stream().sorted(java.util.Comparator.comparingLong((JsonNode file)->file.path("capturedAt").asLong()).reversed()).toList(); } public ScannerHttpClient.Binary asset(Long id,String fileId) { - required(id);var link=bridge.get(id); + required(id); + var archived=archives.open(id,fileId);if(archived!=null)return archived; + var link=bridge.get(id); if(link==null||link.getCmvrInstId()==null)throw new ScannerException("file_not_owned","没有本次执行的扫描文件",404); + if(monitoring.assets(link.getCmvrInstId()).stream().noneMatch(file->fileId.equals(file.path("fileId").asText())))throw new ScannerException("file_not_owned","文件不属于本次执行",404); return monitoring.asset(link.getCmvrInstId(),fileId); } private LabExecutionDO required(Long id) { diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/ScanRobotOccupationAdapter.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/ScanRobotOccupationAdapter.java index 72af75a..4a4b14d 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/ScanRobotOccupationAdapter.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/execution/ScanRobotOccupationAdapter.java @@ -26,7 +26,7 @@ public class ScanRobotOccupationAdapter implements RobotTaskOccupationGuard { resources.assertRobotAvailable(canonical,nativeTaskId); } @Override public void occupy(String instId,String nativeTaskId,java.util.List robotIds) { resources.occupyNative(instId,nativeTaskId,robotIds); } - @Override public void release(String instId,boolean success) { TenantUtils.execute(1L,()->resources.finishNative(instId,success)); } + @Override public void release(String instId,boolean safeToRelease) { TenantUtils.execute(1L,()->resources.finishNative(instId,safeToRelease)); } @Override public AutoCloseable manual(String robotId) { var robot=robots.selectByRobotIdentity(robotId);if(robot==null)robot=robots.selectById(robotId); String canonical=robot==null?robotId:robot.getRobotId(); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRules.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRules.java index 2d30f52..cf31568 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRules.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRules.java @@ -8,6 +8,14 @@ import java.util.Set; /** Physical sample lifecycle policy, independent of HTTP and persistence. */ public final class ScanOnlyRules { private ScanOnlyRules() {} + /** Keep existing short keys stable; bound longer browser/API keys to varchar(64). */ + public static String executionKey(String kind, Long taskId, String requestKey) { + if (!Set.of("SCAN", "SUPPLEMENT").contains(kind) || taskId == null || taskId <= 0 + || blank(requestKey) || requestKey.length() > 128) + throw new IllegalArgumentException("请提供有效的执行幂等标识"); + String scoped = kind + "-" + taskId + "-" + requestKey; + return scoped.length() <= 64 ? scoped : cn.hutool.crypto.digest.DigestUtil.sha256Hex(scoped); + } public static String aggregate(Collection states, boolean stopPending) { if (stopPending) return "STOP_PENDING"; if (!states.isEmpty() && states.stream().allMatch("SUCCEEDED"::equals)) return "COMPLETED"; diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java index d175c99..cb5dfe5 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskService.java @@ -17,6 +17,9 @@ public interface ScanOnlyTaskService { ScanTaskConfigDO releaseResources(ScanTaskRequests.Release request); ScanTaskConfigDO extendResources(ScanTaskRequests.Extend request); Long startUnit(ScanTaskRequests.Start request); + Map supplementOption(Long taskId,Long unitId); + Long startSupplement(ScanTaskRequests.Supplement request); + void finishSupplement(ScanTaskRequests.FinishSupplement request); void cancel(Long taskId,String reason); void confirmStop(Long taskId,String reason); void pause(Long taskId); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java index fe06698..86c7963 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceImpl.java @@ -81,6 +81,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { @Resource private SecurityFrameworkService security; @Resource private LabBizProperties properties; @Resource private LabArtifactService artifacts; + @Resource private ScanSupplementWorkflow supplements; @Resource @Lazy private ScanOnlyTaskServiceImpl self; @Override public boolean isScanTask(Long taskId) { @@ -136,7 +137,10 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { List attempts=executions.selectListByTaskId(taskId);List> rows=new ArrayList<>(); for(ScanSampleUnitDO unit:units.byTask(taskId)) { Map row=JSON.parseObject(JSON.toJSONString(unit),new TypeReference>(){}); - row.put("attempts",attempts.stream().filter(e->Objects.equals(unit.getId(),e.getSampleUnitId())).toList());rows.add(row); + row.put("attempts",attempts.stream().filter(e->Objects.equals(unit.getId(),e.getSampleUnitId())).map(e->{ + Map value=JSON.parseObject(JSON.toJSONString(e),new TypeReference>(){}); + if("SUPPLEMENT".equals(e.getExecutionType()))value.put("supplementCollecting","RUNNING".equals(e.getStatus())&&supplements.collecting(e.getId()));return value; + }).toList());rows.add(row); } return map("task",task,"config",c,"units",rows,"flowData",c.getFlowData(),"inputConfig",c.getInputConfig(), "resourceState",resources.state(c),"recommendations",recommend(c,c.getLengthMm(),c.getWidthMm(),c.getHeightMm()),"attachments",attachmentMapper.selectList(ScanAttachmentDO::getTaskId,taskId)); @@ -198,7 +202,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { public Long startUnit(ScanTaskRequests.Start request) { LabTestTaskDO task=owned(request.getTaskId(),false);ScanTaskConfigDO c=config(task.getId()); if(ScanOnlyRules.blank(request.getIdempotencyKey())||request.getIdempotencyKey().length()>128) throw invalidParamException("请提供有效的执行幂等标识"); - String key="SCAN-"+task.getId()+"-"+request.getIdempotencyKey(); + String key=ScanOnlyRules.executionKey("SCAN",task.getId(),request.getIdempotencyKey()); LabExecutionDO duplicate=executions.selectByIdempotencyKey(key); if(duplicate!=null) { if(!Objects.equals(duplicate.getSampleUnitId(),request.getUnitId())) throw invalidParamException("幂等标识已用于其他单件"); @@ -208,6 +212,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { if(Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested())) throw invalidParamException("任务正在等待停止确认或已取消"); List list=units.byTask(task.getId()); ScanSampleUnitDO unit=list.stream().filter(u->Objects.equals(u.getId(),request.getUnitId())).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务")); + if(unit.getCurrentExecutionId()!=null){var previous=executions.selectById(unit.getCurrentExecutionId());if(previous!=null&&"SUPPLEMENT".equals(previous.getExecutionType()))throw invalidParamException("补扫请使用原工程补扫入口,不能重新执行完整流程");} rules(()->ScanOnlyRules.validateStart(unit.getStatus(),Boolean.TRUE.equals(request.getLoadedConfirmed()),request.getReason())); if(list.stream().anyMatch(u->Set.of("RUNNING","PAUSED","QUEUED").contains(u.getStatus()))) throw invalidParamException("同一任务只能逐件执行,请等待当前单件结束"); // Do not skip an earlier pending/failed physical sample accidentally. @@ -242,6 +247,74 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { return id; } + @Override public Map supplementOption(Long taskId,Long unitId){ + primary();LabTestTaskDO task=required(taskId,false);ScanTaskConfigDO c=config(taskId); + try{ + var unit=units.byTask(taskId).stream().filter(u->Objects.equals(u.getId(),unitId)).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务")); + var parent=supplementParent(task,c,unit,null);var context=supplements.context(parent); + return map("available",true,"parentExecutionId",parent.getId().toString(),"parentExecutionNo",parent.getExecutionNo(),"projectId",context.path("projectId").asText(),"physicalSerial",unit.getPhysicalSerial(), + "message","将在原工程继续采集;如已有网格,将撤销当前网格后补扫,旧导出文件保留。"); + }catch(RuntimeException error){return map("available",false,"message",safeMessage(error));} + } + + private LabExecutionDO supplementParent(LabTestTaskDO task,ScanTaskConfigDO c,ScanSampleUnitDO unit,Long expected){ + if(!Set.of("COMPLETED","BLOCKED").contains(task.getStatus())||Boolean.TRUE.equals(c.getCancelRequested())||Boolean.TRUE.equals(c.getStopPending()))throw invalidParamException("请先完成当前任务或确认停止后再补扫"); + var list=units.byTask(task.getId()); + if(list.stream().anyMatch(u->!Objects.equals(u.getId(),unit.getId())&&!"SUCCEEDED".equals(u.getStatus()))||!Set.of("SUCCEEDED","FAILED").contains(unit.getStatus())||!executions.selectActiveByTaskId(task.getId()).isEmpty())throw invalidParamException("其他样件尚未完成或仍有执行,请先处理当前任务"); + if("FAILED".equals(unit.getStatus())){var latest=executions.selectById(unit.getCurrentExecutionId());if(latest==null||!"SUPPLEMENT".equals(latest.getExecutionType()))throw invalidParamException("原扫描失败,请先完成原扫描,不能作为补扫继续");} + var parent=executions.selectListByTaskId(task.getId()).stream().filter(e->Objects.equals(e.getSampleUnitId(),unit.getId())&&"SUCCEEDED".equals(e.getStatus())) + .max(Comparator.comparing(LabExecutionDO::getId)).orElseThrow(()->invalidParamException("该样件没有成功扫描记录,不能补扫")); + if(expected!=null&&!Objects.equals(parent.getId(),expected))throw invalidParamException("扫描成果已更新,请重新核对补扫来源"); + return parent; + } + + @Override @Transactional(rollbackFor=Exception.class) + public Long startSupplement(ScanTaskRequests.Supplement request){ + LabTestTaskDO task=owned(request.getTaskId(),false);ScanTaskConfigDO c=config(task.getId()); + if(ScanOnlyRules.blank(request.getIdempotencyKey())||request.getIdempotencyKey().length()>128)throw invalidParamException("请提供有效的补扫幂等标识"); + String key=ScanOnlyRules.executionKey("SUPPLEMENT",task.getId(),request.getIdempotencyKey());var duplicate=executions.selectByIdempotencyKey(key); + if(duplicate!=null){if(!"SUPPLEMENT".equals(duplicate.getExecutionType())||!Objects.equals(duplicate.getSampleUnitId(),request.getUnitId())||!Objects.equals(duplicate.getParentExecutionId(),request.getParentExecutionId())||!Objects.equals(duplicate.getReason(),request.getReason())||!Objects.equals(duplicate.getRunParams().get("supplementDurationSeconds"),request.getDurationSeconds()))throw invalidParamException("幂等标识已用于其他补扫请求");return duplicate.getId();} + if(!Boolean.TRUE.equals(request.getSampleConfirmed())||!Boolean.TRUE.equals(request.getFixtureConfirmed())||!Boolean.TRUE.equals(request.getLoadedConfirmed())||ScanOnlyRules.blank(request.getReason())||request.getReason().length()>2000)throw invalidParamException("请填写补扫原因,并重新确认原样件、装夹和现场执行条件"); + if(request.getParentExecutionId()==null)throw invalidParamException("请核对补扫来源执行"); + if(request.getDurationSeconds()==null||request.getDurationSeconds()<1||request.getDurationSeconds()>1800)throw invalidParamException("补扫时长必须为1至1800秒"); + if(!Objects.equals(c.getRevision(),request.getExpectedRevision()))throw invalidParamException("配置已更新,请刷新后重新准备补扫"); + var unit=units.byTask(task.getId()).stream().filter(u->Objects.equals(u.getId(),request.getUnitId())).findFirst().orElseThrow(()->invalidParamException("单件不属于当前任务")); + var parent=supplementParent(task,c,unit,request.getParentExecutionId());var context=supplements.context(parent); + if(!robotIds(c).contains(supplements.robotId()))throw invalidParamException("原任务资源与当前扫描工位不一致,不能补扫"); + // A completed booking has ended. Acquire a new immediate window; keep the frozen method unchanged. + // A failed supplement can retain its old IN_USE booking after stop confirmation. + // Close/reacquire it in this same transaction so a fresh window is not compared + // with the expired attempt's window and no committed occupation gap is created. + resources.release(task.getId(),false); + c.setResourcesAcquiredAt(null);c.setPlannedStartAt(null);c.setPlannedEndAt(null);c.setReservationMode("IMMEDIATE");c.setExpectedMinutes((request.getDurationSeconds()+59)/60+30); + task.setStatus("PREPARING");var checked=checks(task,c); + if(!Boolean.TRUE.equals(checked.get("passed")))throw invalidParamException("补扫资源或夹具检查未通过:{}",JSON.toJSONString(checked.get("items"))); + resources.acquire(task,c); + supplements.archive(parent);supplements.context(parent); // No mesh mutation until all original exports are safely copied. + int attempt=unit.getAttemptNo()+1;Map params=new LinkedHashMap<>(); + params.put("_cmvrRobotId",supplements.robotId());params.put("_cmvrRuntimeAssignments",List.of(supplements.assignment())); + params.put("sampleUnitId",unit.getId().toString());params.put("sampleUnitNo",unit.getUnitNo());params.put("attemptNo",attempt);params.put("physicalSerial",Objects.toString(unit.getPhysicalSerial(),"")); + params.put("supplementDurationSeconds",request.getDurationSeconds());params.put("supplementSourceExecutionNo",parent.getExecutionNo()); + var execution=LabExecutionDO.builder().executionNo(numbers.nextExecutionNo()).taskId(task.getId()).sampleUnitId(unit.getId()).attemptNo(attempt).parentExecutionId(parent.getId()).executionType("SUPPLEMENT") + .methodRefId(parent.getMethodRefId()).methodExternalId(parent.getMethodExternalId()).methodVersion(parent.getMethodVersion()).methodCode(parent.getMethodCode()).scanPlanCode(parent.getScanPlanCode()).scanPlanName(parent.getScanPlanName()) + .runParams(params).idempotencyKey(key).dispatchSyncStatus("PUBLISHED").status("QUEUED").scanStage("QUEUED").progress(BigDecimal.ZERO).latestSequence(0L).reason(request.getReason()).version(0) + .publishedAt(LocalDateTime.now()).dispatchedAt(LocalDateTime.now()).acceptedAt(LocalDateTime.now()).startedAt(LocalDateTime.now()).build(); + executions.insert(execution);supplements.freeze(execution,parent,context,request.getDurationSeconds()); + for(String robot:robotIds(c))acquire(robot,task.getId(),execution.getId()); + unit.setStatus("QUEUED");unit.setAttemptNo(attempt);unit.setCurrentExecutionId(execution.getId());units.updateById(unit); + c.setRevision(c.getRevision()+1);configs.updateById(c);task.setStatus("EXECUTING");tasks.updateById(task); + tasks.update(null,new com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper().eq(LabTestTaskDO::getId,task.getId()).set(LabTestTaskDO::getCompletedAt,null)); + audit(task,"SCAN_SUPPLEMENT_STARTED",map("unitId",unit.getId(),"executionId",execution.getId(),"sourceExecutionId",parent.getId(),"projectId",context.path("projectId").asText(),"reason",request.getReason(),"durationSeconds",request.getDurationSeconds(),"sampleConfirmed",true,"fixtureConfirmed",true)); + Long id=execution.getId();afterCommit(()->{try{bridge.submit(id);}catch(RuntimeException error){log.error("Supplement dispatch failed: {}",id,error);self.onExecutionFinished(id,false,"{}",safeMessage(error));}});return id; + } + + @Override @Transactional(rollbackFor=Exception.class) + public void finishSupplement(ScanTaskRequests.FinishSupplement request){ + LabTestTaskDO task=owned(request.getTaskId(),false);var c=config(task.getId());var execution=executions.selectById(request.getExecutionId()); + if(execution==null||!Objects.equals(execution.getTaskId(),task.getId())||!"SUPPLEMENT".equals(execution.getExecutionType())||!"RUNNING".equals(execution.getStatus())||Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested()))throw invalidParamException("当前没有可结束采集的补扫执行"); + supplements.finish(execution.getId());audit(task,"SCAN_SUPPLEMENT_FINISH_REQUESTED",map("executionId",execution.getId())); + } + @Override @Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED) public void onExecutionFinished(Long executionId,boolean success,String outputJson,String error) { LabExecutionDO reference=executions.selectById(executionId);if(reference==null||!isScanTask(reference.getTaskId()))return; @@ -251,6 +324,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { ScanSampleUnitDO unit=units.selectById(execution.getSampleUnitId()); if(unit==null||!Objects.equals(unit.getCurrentExecutionId(),executionId))return; boolean cancelled=Boolean.TRUE.equals(c.getCancelRequested()); + if(success&&!cancelled)try{supplements.archive(execution);}catch(RuntimeException archiveError){success=false;error=safeMessage(archiveError);} execution.setStatus(cancelled?"CANCELLED":success?"SUCCEEDED":"FAILED");execution.setScanStage(cancelled?"CANCELLED":success?"COMPLETED":"FAILED"); execution.setSupplierScanStage(execution.getScanStage());execution.setFailureReason(error);execution.setFinishedAt(LocalDateTime.now()); execution.setResultDeliveryStatus(success?"AVAILABLE":"FAILED");if(success)execution.setProgress(new BigDecimal("100"));executions.updateById(execution); @@ -354,6 +428,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService { if(Boolean.TRUE.equals(c.getStopPending())||Boolean.TRUE.equals(c.getCancelRequested()))throw invalidParamException("请先处理停止待确认状态"); List active=executions.selectActiveByTaskId(taskId);if(active.size()!=1)throw invalidParamException("当前没有可控制的执行"); LabExecutionDO e=active.get(0);if(pause&&!"RUNNING".equals(e.getStatus()))throw invalidParamException("当前单件尚未运行或已暂停"); + if("SUPPLEMENT".equals(e.getExecutionType()))throw invalidParamException("补扫请使用结束采集并生成成果;如需终止任务请取消并确认停止"); if(!pause&&!"PAUSED".equals(e.getStatus()))throw invalidParamException("当前单件未暂停"); afterCommit(()->{try{if(pause)bridge.pause(e.getId());else bridge.resume(e.getId());}catch(RuntimeException error){self.markControlUncertain(taskId,safeMessage(error));}}); audit(task,pause?"SCAN_PAUSE_REQUESTED":"SCAN_RESUME_REQUESTED",map("executionId",e.getId())); diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java index d54f913..0bc6db9 100644 --- a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceService.java @@ -66,8 +66,8 @@ public class ScanResourceService extends ResourceOccupationStore { acquireSet("NATIVE:"+instId,host,instId,catalog.lockedResources(runtimeConfig(robots),true,List.of()),instant(),false); } @Transactional(rollbackFor=Exception.class) - public void finishNative(String instId,boolean success) { - if(success)jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId); + public void finishNative(String instId,boolean safeToRelease) { + if(safeToRelease)jdbc.update("DELETE FROM lab_resource_occupation WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId); else jdbc.update("UPDATE lab_resource_occupation SET status='STOP_PENDING' WHERE owner_key=? AND tenant_id=1","NATIVE:"+instId); } @Transactional(rollbackFor=Exception.class) diff --git a/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflow.java b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflow.java new file mode 100644 index 0000000..93449f9 --- /dev/null +++ b/am-backend/yudao-module-lab/src/main/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflow.java @@ -0,0 +1,78 @@ +package cn.iocoder.yudao.module.lab.service.scanonly; + +import cn.hutool.crypto.digest.DigestUtil; +import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils; +import cn.iocoder.yudao.module.lab.dal.dataobject.execution.*; +import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper; +import cn.iocoder.yudao.module.lab.service.execution.CmvrMethodBindingService; +import com.alibaba.fastjson2.*; +import com.cmvr.scanner.*; +import com.cmvr.test.mapper.*; +import com.cmvr.test.model.domain.*; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Service; +import java.util.*; + +/** An immutable supplemental plan is separate from the user's original published method. */ +@Service +public class ScanSupplementWorkflow { + @Resource private ScannerMonitoringService monitoring; + @Resource private ScannerProperties settings; + @Resource private ScannerSupplementSignals signals; + @Resource private LabCmvrExecutionMapper bindings; + @Resource private TeDetectionItemMapper items; + @Resource private TeDetectionItemVersionMapper versions; + @Resource private cn.iocoder.yudao.module.lab.service.execution.LabScannerAssetArchive archives; + + public JsonNode context(LabExecutionDO parent){ + CmvrMethodBindingService.requirePrimaryTenant(); + var link=bindings.selectById(parent.getId()); + if(link==null||link.getCmvrInstId()==null)throw new ScannerException("project_not_bound","原执行没有可核对的扫描工程,不能补扫",409); + JsonNode context=monitoring.binding(link.getCmvrInstId());JsonNode status=monitoring.status(context); + if(!status.path("initialized").asBoolean()||!status.path("deviceOnline").asBoolean()||status.path("scanning").asBoolean()||status.path("busy").asBoolean()) + throw new ScannerException("scanner_not_ready","扫描仪须在线、就绪且停止采集,才能补扫",409); + if(!Set.of("none","preview","confirmed").contains(status.path("meshState").asText()))throw new ScannerException("mesh_state_unknown","网格状态无法确认,暂不能补扫",409); + return context.deepCopy(); + } + public Map assignment(){return Map.of("roleKey","scanner","members",List.of(Map.of("memberKey","scanner","robotId",settings.getRobotId(),"devices",Map.of("scanner",settings.getDeviceId()))));} + public String robotId(){return settings.getRobotId();} + public void finish(Long execution){var link=bindings.selectById(execution);if(link==null)throw new ScannerException("runtime_pending","补扫尚未启动",409);signals.finish(link.getCmvrInstId());} + public boolean collecting(Long execution){var link=bindings.selectById(execution);return link!=null&&link.getCmvrInstId()!=null&&signals.isCollecting(link.getCmvrInstId());} + public void archive(LabExecutionDO execution){var link=bindings.selectById(execution.getId());if(link==null||link.getCmvrInstId()==null)throw new ScannerException("project_not_bound","缺少成果所属执行",409);archives.archive(execution.getId(),link.getCmvrInstId());} + + public void freeze(LabExecutionDO execution,LabExecutionDO parent,JsonNode context,int seconds){ + var source=bindings.selectById(parent.getId()); + String itemId=UUID.randomUUID().toString().replace("-",""),versionId=UUID.randomUUID().toString().replace("-",""); + String graph=graph(context,seconds),hash=DigestUtil.sha256Hex(graph+"\n[]"); + var item=TeDetectionItem.builder().id(itemId).detectName("补扫 "+execution.getExecutionNo()).detectDesc("来源执行 "+parent.getExecutionNo()+",继续原工程,不新建工程") + .flowData(graph).config("[]").status("0").isDeploy("0").sceneCode("NORMAL").draftRevision(1).draftHash(hash) + .publishedDraftHash(hash).publishedVersionId(versionId).publishedVersionNo(1).build();items.insert(item); + var version=new TeDetectionItemVersion();version.setId(versionId);version.setDetectionItemId(itemId);version.setVersionNo(1); + version.setFlowData(graph);version.setConfig("[]");version.setSchemaVersion(2);version.setContentHash(hash);version.setSourceVersionId(source.getVersionId()); + version.setPublishNote("系统补扫方案;来源 "+parent.getExecutionNo()+";"+seconds+"秒,可提前结束采集");version.setCreateBy(Objects.toString(SecurityFrameworkUtils.getLoginUserId(),""));versions.insert(version); + var binding=new LabCmvrExecutionDO();binding.setExecutionId(execution.getId());binding.setTestCaseId(source.getTestCaseId());binding.setDetectionItemId(itemId); + binding.setVersionId(versionId);binding.setVersionNo(1);binding.setFlowData(graph);binding.setInputConfig("[]");binding.setActorUserId(SecurityFrameworkUtils.getLoginUserId());binding.setCmvrStatus("NOT_STARTED");bindings.insert(binding); + } + + public static String graph(JsonNode context,int seconds){ + if(seconds<1||seconds>1800)throw new IllegalArgumentException("补扫时长必须为1至1800秒"); + JSONArray nodes=new JSONArray(),edges=new JSONArray(); + JSONObject start=JSONObject.of("name","开始补扫","action","START","schemaVersion",2,"inputParams",new JSONArray(), + "resourceRoles",List.of(Map.of("roleKey","scanner","displayName","原扫描工位","required",true,"deviceSlots",List.of(Map.of("slotKey","scanner","displayName","原扫描仪","deviceKind",14,"required",true,"allowReuse",false))))); + nodes.add(JSONObject.of("id","start","type","start","properties",start,"x",100,"y",180)); + String[][] actions={{"prepare","核对原工程并撤销网格","SCANNER_SUPPLEMENT_PREPARE"},{"preview","开启原工程实时预览","SCANNER_PREVIEW_START"},{"scan","继续原样件采集","SCANNER_START"}, + {"wait","补扫采集(可提前结束)","SCANNER_SUPPLEMENT_WAIT"},{"stop","停止并确认采集","SCANNER_STOP"},{"mesh","重新生成网格","SCANNER_MESH"},{"confirm","确认补扫网格","SCANNER_MESH_CONFIRM"},{"export","导出补扫PLY与STL","SCANNER_EXPORT"}}; + for(String[] a:actions){ + JSONArray params=new JSONArray();params.add(JSONObject.of("name","timeoutMs","type","input","input",a[0].equals("wait")?seconds*1000+30000:600000)); + params.add(JSONObject.of("name","expectedContextJson","type","input","input",context.toString())); + if(a[0].equals("wait"))params.add(JSONObject.of("name","durationMs","type","input","input",seconds*1000)); + params.add(JSONObject.of("name","requestJson","type","input","input",a[0].equals("export")?"{\"formats\":[\"PLY\",\"STL\"]}":"{}")); + var p=JSONObject.of("name",a[1],"action",a[2],"nodeType","EDGE","executionTarget",Map.of("roleKey","scanner","deviceSlotKey","scanner"),"nodeParams",params,"inputParams",new JSONArray()); + nodes.add(JSONObject.of("id",a[0],"type","serviceNode","properties",p,"x",100+250*nodes.size(),"y",180)); + } + nodes.add(JSONObject.of("id","end","type","end","properties",JSONObject.of("name","补扫成果已生成","action","END"),"x",100+250*nodes.size(),"y",180)); + for(int i=1;i {}); assertFalse(result.success()); assertTrue(result.error().contains("sensor invalid")); assertEquals("FAILED", result.logs().get(result.logs().size()-1).status()); } + /** 脚本打印内容不得破坏返回协议或替代真实计算结果。 */ + @Test void scriptConsoleOutputCannotCorruptStructuredResult() { + var result = engine.execute(graph(""" + {"id":"a","type":"code","data":{"params":{"code":"function handler(p){print('diagnostic before result');return {answer:42};}"}}} + """, ""), Map.of(), ignored -> {}); + assertTrue(result.success(), result.error()); + assertEquals(42, result.output().path("a").path("result").path("answer").asInt()); + } + /** 缺失引用必须失败,不能把空值带入检测判定。 */ @Test void rejectsUnavailableReference() { var result = engine.execute(graph(""" diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchiveTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchiveTest.java new file mode 100644 index 0000000..a2f5074 --- /dev/null +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerAssetArchiveTest.java @@ -0,0 +1,49 @@ +package cn.iocoder.yudao.module.lab.service.execution; + +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.framework.config.LabBizProperties; +import com.cmvr.scanner.*; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import java.io.*; +import java.nio.file.*; +import java.util.*; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +class LabScannerAssetArchiveTest { + @TempDir Path directory; + ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class); + LabScannerAssetArchive archive; + final String file="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + @BeforeEach void setup(){TenantContextHolder.setTenantId(1L);var properties=new LabBizProperties();properties.getArtifact().setNasRoot(directory.toString());archive=new LabScannerAssetArchive(properties,monitoring);} + @AfterEach void cleanup(){TenantContextHolder.clear();} + @Test void oldFileStaysStableWhenSupplierFileChangesAndRepeatedArchiveDoesNotRedownload() throws Exception { + when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"name\":\"old.stl\",\"bytes\":3}"))); + when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1,2,3}),Map.of())); + archive.archive(7L,"inst");archive.archive(7L,"inst");verify(monitoring,times(1)).asset("inst",file); + try(var saved=archive.open(7L,file)){assertArrayEquals(new byte[]{1,2,3},saved.stream().readAllBytes());} + assertNull(archive.open(8L,file));assertThrows(ScannerException.class,()->archive.open(7L,"../wrong")); + TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->archive.open(7L,file)); + } + @Test void incompleteDownloadNeverBecomesAnArchivedResult() throws Exception { + when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"bytes\":4}"))); + when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1}),Map.of())); + assertThrows(ScannerException.class,()->archive.archive(7L,"inst"));assertNull(archive.open(7L,file)); + try(var paths=Files.walk(directory)){assertFalse(paths.anyMatch(p->p.getFileName().toString().endsWith(".part")));} + } + @Test void durableListSurvivesMissingCommandRecordsAndKeepsExecutionsSeparate() throws Exception { + when(monitoring.assets("inst")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\""+file+"\",\"name\":\"original.ply\",\"bytes\":3,\"projectId\":\"old-project\",\"capturedAt\":456,\"binding\":{\"endpoint\":\"private\"}}"))); + when(monitoring.asset("inst",file)).thenReturn(new ScannerHttpClient.Binary(new ByteArrayInputStream(new byte[]{1,2,3}),Map.of())); + archive.archive(7L,"inst");reset(monitoring); + var listed=archive.list(7L);assertEquals(1,listed.size());assertEquals(file,listed.get(0).path("fileId").asText());assertEquals("old-project",listed.get(0).path("projectId").asText());assertEquals(456,listed.get(0).path("capturedAt").asLong());assertFalse(listed.get(0).has("binding"));assertFalse(listed.get(0).has("sha256")); + assertTrue(archive.list(8L).isEmpty());verifyNoInteractions(monitoring); + TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->archive.list(7L)); + } + @Test void legacyMetadataIsListedButBrokenArchiveDoesNotPretendToBeEmpty() throws Exception { + Path target=directory.resolve("1/7/scanner-files/"+file);Files.createDirectories(target.getParent());Files.write(target,new byte[]{1,2,3}); + Files.writeString(target.resolveSibling(file+".json"),"{\"name\":\"legacy.stl\",\"bytes\":3,\"sha256\":\"old\"}"); + assertEquals("legacy.stl",archive.list(7L).get(0).path("name").asText()); + Files.write(target,new byte[]{1});assertEquals("archive_unavailable",assertThrows(ScannerException.class,()->archive.list(7L)).scannerCode); + } +} diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerStreamControllerTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerStreamControllerTest.java new file mode 100644 index 0000000..b0acf33 --- /dev/null +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerStreamControllerTest.java @@ -0,0 +1,31 @@ +package cn.iocoder.yudao.module.lab.service.execution; + +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.controller.admin.cmvr.LabScannerViewController; +import com.cmvr.scanner.ScannerException; +import org.junit.jupiter.api.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class LabScannerStreamControllerTest { + @AfterEach void cleanup(){TenantContextHolder.clear();} + @Test void asyncStreamRestoresTenantAndChecksAccessBeforeOpeningResponse() throws Exception { + var service=mock(LabScannerViewService.class);var controller=new LabScannerViewController(service); + TenantContextHolder.setTenantId(1L); + var response=controller.stream(42L);verify(service).checkStream(42L); + assertTrue(response.getHeaders().getContentType().toString().startsWith("multipart/x-mixed-replace")); + assertEquals("no",response.getHeaders().getFirst("X-Accel-Buffering")); + TenantContextHolder.setTenantId(7L);TenantContextHolder.setIgnore(true); + doAnswer(call->{assertEquals(1L,TenantContextHolder.getTenantId());assertFalse(TenantContextHolder.isIgnore());return null;}) + .when(service).stream(eq(42L),any()); + response.getBody().writeTo(new java.io.ByteArrayOutputStream()); + assertEquals(7L,TenantContextHolder.getTenantId());assertTrue(TenantContextHolder.isIgnore()); + } + @Test void projectChangeEndsStreamWithoutAppendingJsonAndRestoresTenant() throws Exception { + var service=mock(LabScannerViewService.class);var controller=new LabScannerViewController(service); + TenantContextHolder.setTenantId(1L);var response=controller.stream(42L);TenantContextHolder.clear(); + doThrow(new ScannerException("project_changed","changed",409)).when(service).stream(eq(42L),any()); + var output=new java.io.ByteArrayOutputStream();response.getBody().writeTo(output); + assertEquals(0,output.size());assertNull(TenantContextHolder.getTenantId());assertFalse(TenantContextHolder.isIgnore()); + } +} diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewServiceTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewServiceTest.java index ea66207..6b05aec 100644 --- a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewServiceTest.java +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/execution/LabScannerViewServiceTest.java @@ -17,7 +17,8 @@ class LabScannerViewServiceTest { private final TaskInstHolder runtime=mock(TaskInstHolder.class); private final ScannerMonitoringService monitoring=mock(ScannerMonitoringService.class); private final ScannerProperties settings=new ScannerProperties(); - private final LabScannerViewService views=new LabScannerViewService(executions,bridge,runtime,settings,monitoring); + private final LabScannerAssetArchive archives=mock(LabScannerAssetArchive.class); + private final LabScannerViewService views=new LabScannerViewService(executions,bridge,runtime,settings,monitoring,archives); private LabExecutionDO execution; @BeforeEach void setup(){ @@ -43,6 +44,22 @@ class LabScannerViewServiceTest { execution.setStatus("SUCCEEDED");assertFalse(views.view(1L).path("available").asBoolean()); assertThrows(ScannerException.class,()->views.image(1L));verifyNoInteractions(monitoring); } + @Test void originalAndSupplementAssetsStaySeparatedAndArchivesDoNotNeedRuntime() throws Exception { + execution.setStatus("SUCCEEDED");when(bridge.get(1L)).thenReturn(null); + var file=ScannerRequestValidator.parse("{\"fileId\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"name\":\"original.ply\",\"bytes\":3,\"archived\":true}"); + when(archives.list(1L)).thenReturn(List.of(file)); + assertEquals("original.ply",views.assets(1L).get(0).path("name").asText()); + var binary=new ScannerHttpClient.Binary(new java.io.ByteArrayInputStream(new byte[]{1,2,3}),Map.of()); + when(archives.open(1L,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")).thenReturn(binary); + try(var saved=views.asset(1L,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")){assertArrayEquals(new byte[]{1,2,3},saved.stream().readAllBytes());} + assertThrows(ScannerException.class,()->views.asset(1L,"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")); + verifyNoInteractions(monitoring,runtime); + } + @Test void mergesArchivedAndJournalMetadataWithoutDuplicatesOrPrivateBinding(){ + when(monitoring.assets("inst-1")).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\"a\",\"capturedAt\":123,\"projectId\":\"original\",\"binding\":{\"endpoint\":\"private\"}}"))); + when(archives.list(1L)).thenReturn(List.of(ScannerRequestValidator.parse("{\"fileId\":\"a\",\"name\":\"old.ply\",\"archived\":true}"))); + var files=views.assets(1L);assertEquals(1,files.size());assertEquals(123,files.get(0).path("capturedAt").asLong());assertEquals("original",files.get(0).path("projectId").asText());assertFalse(files.get(0).has("binding")); + } @Test void blocksWrongTenantInactiveRuntimeAndWrongWorkstation(){ TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->views.view(1L)); TenantContextHolder.setTenantId(1L);when(runtime.getContext("inst-1")).thenReturn(null); @@ -62,4 +79,29 @@ class LabScannerViewServiceTest { @Test void emptyConfigurationShowsPendingWithoutContactingHardware(){ settings.setHost("");assertEquals("not_configured",views.view(1L).path("state").asText());verifyNoInteractions(monitoring); } + @Test void streamsOneConnectionAndStopsBeforePublishingAFrameFromCompletedExecution() throws Exception { + byte[] jpeg={(byte)255,(byte)216,(byte)255,(byte)217}; + var raw=new java.io.ByteArrayOutputStream(); + for(int sequence=1;sequence<=2;sequence++) { + raw.write(("--frame\r\nContent-Type: image/jpeg\r\nContent-Length: 4\r\nX-Frame-Sequence: "+sequence+"\r\n\r\n").getBytes()); + raw.write(jpeg);raw.write(new byte[]{13,10}); + } + var source=new ScannerPreviewStream(new ScannerHttpClient.Binary(new java.io.ByteArrayInputStream(raw.toByteArray()),Map.of("content-type",List.of("multipart/x-mixed-replace; boundary=frame")))); + when(monitoring.stream(any())).thenReturn(source);when(monitoring.streamSequence(any(),any())).thenReturn(1L,2L); + var done=LabExecutionDO.builder().id(1L).taskId(2L).status("FAILED").build(); + when(executions.selectById(1L)).thenReturn(execution,execution,done); + var output=new java.io.ByteArrayOutputStream(); + assertThrows(ScannerException.class,()->views.stream(1L,output)); + String sent=output.toString(java.nio.charset.StandardCharsets.ISO_8859_1); + assertTrue(sent.contains("X-Frame-Sequence: 1"));assertFalse(sent.contains("X-Frame-Sequence: 2")); + verify(monitoring,times(1)).stream(any()); + } + @Test void rejectsHistoricalStreamAndReleasesSlotEvenWhenValidationFails() { + execution.setStatus("FAILED"); + for(int attempt=0;attempt<8;attempt++) { + var failure=assertThrows(ScannerException.class,()->views.stream(1L,new java.io.ByteArrayOutputStream())); + assertEquals("execution_finished",failure.scannerCode); + } + verifyNoInteractions(monitoring); + } } diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ReportRevisionTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ReportRevisionTest.java index 56faa6e..c6c3ea1 100644 --- a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ReportRevisionTest.java +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ReportRevisionTest.java @@ -43,4 +43,22 @@ class ReportRevisionTest { assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.publish(1L)); verifyNoInteractions(versions); } + @Test void oversizedReportFieldsAreRejectedBeforeAnyDatabaseWrite(){ + for (String field:List.of("title","reportType","idempotencyKey","externalReportNo")) { + var request=new cn.iocoder.yudao.module.lab.controller.admin.document.vo.LabReportSaveReqVO();request.setTaskId(1L);request.setTitle("valid"); + ReflectionTestUtils.setField(request,field,"x".repeat(field.equals("title")?257:field.equals("reportType")?33:65)); + assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.createReport(request)); + } + verifyNoInteractions(reports,versions); + } + @Test void oversizedRevisionCannotCreateDraftOrChangePublishedReport(){ + assertThrows(cn.iocoder.yudao.framework.common.exception.ServiceException.class,()->service.updateDraft(1L,"new content","x".repeat(257))); + verifyNoInteractions(reports,versions); + } + @Test void maximumLengthTitleIsAcceptedWithoutTruncation(){ + var draft=LabReportVersionDO.builder().id(12L).versionNo(2).status("DRAFT").build(); + when(versions.selectListByReportId(1L)).thenReturn(List.of(draft)); + String title="x".repeat(256);service.updateDraft(1L,"content",title); + assertEquals(title,report.getTitle());verify(reports).updateById(report); + } } diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRulesTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRulesTest.java index 76a1dee..cb460ff 100644 --- a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRulesTest.java +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyRulesTest.java @@ -6,6 +6,24 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.*; public class ScanOnlyRulesTest { + @Test void browserUuidAndMaximumApiKeysFitTheDatabaseAndRemainTaskScoped() { + long task=2113518333730902017L; + String browserKey="50eb650e-9a18-43db-bc91-745f8c783423"; + assertTrue(("SUPPLEMENT-"+task+"-"+browserKey).length()>64); + for(String kind:List.of("SCAN","SUPPLEMENT"))for(String input:List.of(browserKey,"a".repeat(128),"b".repeat(32))){ + String key=ScanOnlyRules.executionKey(kind,task,input); + assertTrue(key.length()<=64);assertEquals(key,ScanOnlyRules.executionKey(kind,task,input)); + assertNotEquals(key,ScanOnlyRules.executionKey(kind,task+1,input)); + String different=(input.charAt(0)=='z'?"y":"z")+input.substring(1); + assertNotEquals(key,ScanOnlyRules.executionKey(kind,task,different)); + } + } + @Test void shortExistingKeysStayCompatibleAndInvalidKeysAreRejected() { + assertEquals("SCAN-1-short-key",ScanOnlyRules.executionKey("SCAN",1L,"short-key")); + assertEquals("SUPPLEMENT-1-short-key",ScanOnlyRules.executionKey("SUPPLEMENT",1L,"short-key")); + for(String invalid:List.of(""," ","x".repeat(129)))assertThrows(IllegalArgumentException.class,()->ScanOnlyRules.executionKey("SUPPLEMENT",1L,invalid)); + assertThrows(IllegalArgumentException.class,()->ScanOnlyRules.executionKey("OTHER",1L,"key")); + } @Test void taskCompletesOnlyWhenAllPhysicalUnitsSucceeded() { assertEquals("PREPARING", ScanOnlyRules.aggregate(List.of("SUCCEEDED", "PENDING", "PENDING"), false)); assertEquals("BLOCKED", ScanOnlyRules.aggregate(List.of("SUCCEEDED", "FAILED", "PENDING"), false)); diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceTest.java index f7bf3e5..d6855a8 100644 --- a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceTest.java +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanOnlyTaskServiceTest.java @@ -38,6 +38,7 @@ class ScanOnlyTaskServiceTest { private ScanSampleUnitMapper units; private ScanRobotOccupationMapper occupations; private ScanResourceService resources; + private ScanSupplementWorkflow supplements; @BeforeEach void setup() { service=new ScanOnlyTaskServiceImpl(); tasks=mock(LabTestTaskMapper.class); configs=mock(ScanTaskConfigMapper.class); executions=mock(LabExecutionMapper.class); @@ -46,6 +47,7 @@ class ScanOnlyTaskServiceTest { units=mock(ScanSampleUnitMapper.class);occupations=mock(ScanRobotOccupationMapper.class); ReflectionTestUtils.setField(service,"units",units);ReflectionTestUtils.setField(service,"occupations",occupations); resources=mock(ScanResourceService.class);ReflectionTestUtils.setField(service,"resources",resources); + supplements=mock(ScanSupplementWorkflow.class);ReflectionTestUtils.setField(service,"supplements",supplements); ReflectionTestUtils.setField(service,"timeline",mock(LabTaskTimelineMapper.class));ReflectionTestUtils.setField(service,"events",mock(LabExecutionEventMapper.class)); TenantContextHolder.setTenantId(1L); identity=mockStatic(SecurityFrameworkUtils.class); identity.when(SecurityFrameworkUtils::getLoginUserId).thenReturn(7L); } @@ -148,22 +150,36 @@ class ScanOnlyTaskServiceTest { List items=(List)result.get("items");assertTrue(items.stream().anyMatch(row->row instanceof Map r&&"RELEASE".equals(r.get("code"))&&Boolean.FALSE.equals(r.get("passed")))); verify(methods,never()).ensureMethod(anyString(),anyString()); } - @Test void thirdUnitSuccessCompletesTaskWithoutResultsOrReport(@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) throws Exception { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(strings={"INITIAL","RETEST","SUPPLEMENT"}) + void thirdUnitSuccessArchivesEveryScanTypeBeforeCompletingTask(String type,@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) throws Exception { LabTestTaskDO task=task();ScanTaskConfigDO c=config();c.setStopPending(false);c.setCancelRequested(false); - LabExecutionDO e=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).status("RUNNING").build();e.setTenantId(1L); + LabExecutionDO e=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).executionType(type).status("RUNNING").build();e.setTenantId(1L); ScanSampleUnitDO one=new ScanSampleUnitDO();one.setStatus("SUCCEEDED");ScanSampleUnitDO two=new ScanSampleUnitDO();two.setStatus("SUCCEEDED"); ScanSampleUnitDO three=new ScanSampleUnitDO();three.setId(3L);three.setCurrentExecutionId(2L);three.setStatus("RUNNING"); when(executions.selectById(2L)).thenReturn(e);when(executions.selectByIdForUpdate(2L)).thenReturn(e);when(units.selectById(3L)).thenReturn(three);when(units.byTask(1L)).thenReturn(List.of(one,two,three)); LabBizProperties properties=new LabBizProperties();properties.getArtifact().setNasRoot(outputRoot.toString()); ReflectionTestUtils.setField(service,"properties",properties);ReflectionTestUtils.setField(service,"artifacts",mock(LabArtifactService.class)); service.onExecutionFinished(2L,true,"{}",null); + verify(supplements).archive(e); assertEquals("SUCCEEDED",three.getStatus());assertEquals("COMPLETED",task.getStatus());assertNotNull(task.getCompletedAt()); verify(occupations).release(1L,1L); service.onExecutionFinished(2L,true,"{}",null);verify(occupations,times(1)).release(1L,1L); + verify(supplements,times(1)).archive(e); } private LabTestTaskDO task(){ LabTestTaskDO task=LabTestTaskDO.builder().id(1L).ownerId(7L).status("EXECUTING").processType("SCAN_ONLY").build(); when(tasks.selectById(1L)).thenReturn(task);when(tasks.selectByIdForUpdate(1L)).thenReturn(task);return task; } + @Test void failedNormalExportArchiveCannotBeReportedAsSuccessful(@org.junit.jupiter.api.io.TempDir java.nio.file.Path outputRoot) { + LabTestTaskDO task=task();ScanTaskConfigDO c=config();c.setStopPending(false);c.setCancelRequested(false); + var execution=LabExecutionDO.builder().id(2L).taskId(1L).sampleUnitId(3L).executionType("INITIAL").status("RUNNING").build();execution.setTenantId(1L); + var unit=new ScanSampleUnitDO();unit.setId(3L);unit.setCurrentExecutionId(2L);unit.setStatus("RUNNING"); + when(executions.selectById(2L)).thenReturn(execution);when(executions.selectByIdForUpdate(2L)).thenReturn(execution);when(units.selectById(3L)).thenReturn(unit);when(units.byTask(1L)).thenReturn(List.of(unit)); + var properties=new LabBizProperties();properties.getArtifact().setNasRoot(outputRoot.toString());ReflectionTestUtils.setField(service,"properties",properties);ReflectionTestUtils.setField(service,"artifacts",mock(LabArtifactService.class)); + doThrow(new IllegalStateException("archive disk full")).when(supplements).archive(execution); + service.onExecutionFinished(2L,true,"{}",null); + assertEquals("FAILED",execution.getStatus());assertEquals("FAILED",unit.getStatus());assertNotEquals("COMPLETED",task.getStatus());assertTrue(execution.getFailureReason().contains("archive disk full")); + } private ScanTaskConfigDO config(){ScanTaskConfigDO c=new ScanTaskConfigDO();c.setTaskId(1L);c.setRuntimeAssignments(List.of());when(configs.byTask(1L)).thenReturn(c);return c;} } diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceServiceTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceServiceTest.java index 655240a..9c39fb5 100644 --- a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceServiceTest.java +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanResourceServiceTest.java @@ -77,6 +77,21 @@ class ScanResourceServiceTest { tx.executeWithoutResult(s->service.release(1L,false));assertEquals(0,count("lab_resource_occupation")); assertEquals("FINISHED",jdbc.queryForObject("SELECT status FROM lab_device_reservation",String.class)); } + @Test void unconfirmedNativeStopKeepsAllLeasesUntilAcknowledgement() { + tx.executeWithoutResult(s->service.acquireSet("NATIVE:trial",null,"trial",resources("r1",101),window(),false)); + tx.executeWithoutResult(s->service.finishNative("trial",false)); + assertEquals(3,count("lab_resource_occupation")); + assertEquals(3,jdbc.queryForObject("SELECT COUNT(*) FROM lab_resource_occupation WHERE status='STOP_PENDING'",Integer.class)); + tx.executeWithoutResult(s->service.finishNative("trial",true)); + assertEquals(0,count("lab_resource_occupation")); + } + @Test void acknowledgedNativeStopReleasesOnlyItsOwnLease() { + tx.executeWithoutResult(s->service.acquireSet("NATIVE:trial",null,"trial",resources("r1",101),window(),false)); + jdbc.update("INSERT INTO lab_resource_occupation(id,resource_key,resource_type,resource_id,owner_key,status) VALUES(999,'R:other','ROBOT','other','NATIVE:other','HELD')"); + tx.executeWithoutResult(s->service.finishNative("trial",true)); + assertEquals(1,count("lab_resource_occupation")); + assertEquals("NATIVE:other",jdbc.queryForObject("SELECT owner_key FROM lab_resource_occupation",String.class)); + } @Test void differentRobotsCannotShareAnExclusiveLabAndFailureRollsBackAllClaims() { acquire(1,"r1",101); assertThrows(RuntimeException.class,()->acquire(2,"r2",102)); diff --git a/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflowTest.java b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflowTest.java new file mode 100644 index 0000000..3861ef7 --- /dev/null +++ b/am-backend/yudao-module-lab/src/test/java/cn/iocoder/yudao/module/lab/service/scanonly/ScanSupplementWorkflowTest.java @@ -0,0 +1,45 @@ +package cn.iocoder.yudao.module.lab.service.scanonly; + +import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder; +import cn.iocoder.yudao.module.lab.dal.dataobject.execution.*; +import cn.iocoder.yudao.module.lab.dal.mysql.execution.LabCmvrExecutionMapper; +import com.alibaba.fastjson2.*; +import com.cmvr.scanner.*; +import com.cmvr.test.enums.ActionEnum; +import com.cmvr.test.flow.runtime.operator.edge.WorkcellNodeContract; +import org.junit.jupiter.api.*; +import org.springframework.test.util.ReflectionTestUtils; +import java.util.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class ScanSupplementWorkflowTest { + private final ScanSupplementWorkflow service=new ScanSupplementWorkflow(); + private final ScannerMonitoringService monitor=mock(ScannerMonitoringService.class); + private final LabCmvrExecutionMapper bindings=mock(LabCmvrExecutionMapper.class); + @BeforeEach void setup(){TenantContextHolder.setTenantId(1L);ReflectionTestUtils.setField(service,"monitoring",monitor);ReflectionTestUtils.setField(service,"bindings",bindings);} + @AfterEach void cleanup(){TenantContextHolder.clear();} + @Test void generatedFrozenPlanNeverCreatesOrSwitchesProjectsAndAllNodesPassContracts(){ + var context=ScannerRequestValidator.parse("{\"endpoint\":\"e\",\"sessionId\":\"s\",\"projectId\":\"p\",\"robotId\":\"r\",\"deviceId\":\"d\"}"); + var graph=JSON.parseObject(ScanSupplementWorkflow.graph(context,60));var nodes=graph.getJSONArray("nodes"); + List actions=new ArrayList<>(); + for(int i=0;iservice.context(parent)); + when(monitor.status(context)).thenThrow(new ScannerException("project_changed","工程已切换",409));assertThrows(ScannerException.class,()->service.context(parent)); + TenantContextHolder.setTenantId(2L);assertThrows(RuntimeException.class,()->service.context(parent)); + } +} diff --git a/am-backend/yudao-server/src/main/resources/application.yaml b/am-backend/yudao-server/src/main/resources/application.yaml index 882788b..feceaee 100644 --- a/am-backend/yudao-server/src/main/resources/application.yaml +++ b/am-backend/yudao-server/src/main/resources/application.yaml @@ -1,8 +1,8 @@ cmvr: scanner: - # 待现场确认。端口为空时不连接设备;18888/18890不能混用。 - host: ${AM_FREESCAN_SCANNER_HOST:} - port: ${AM_FREESCAN_SCANNER_PORT:} + # 现场API地址;访问密钥待配置。18888为API端口,不能使用18890网页代理端口。 + host: ${AM_FREESCAN_SCANNER_HOST:192.168.0.121} + port: ${AM_FREESCAN_SCANNER_PORT:18888} api-key: ${AM_FREESCAN_SCANNER_API_KEY:} robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:} device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:} @@ -12,6 +12,8 @@ cmvr: poll-interval-ms: 500 spring: + config: + import: optional:file:./.local/scanner-private.yaml application: name: am-freescan profiles: diff --git a/am-web/.env b/am-web/.env index c7d1c47..8a77172 100644 --- a/am-web/.env +++ b/am-web/.env @@ -2,7 +2,9 @@ VITE_APP_TITLE=AM FreeScan VITE_PORT=5180 VITE_OPEN=false -VITE_BASE_URL=http://localhost:48090 +# 页面与接口使用同一入口,兼容 localhost 和局域网 IP。 +VITE_BASE_URL= +VITE_DEV_PROXY_TARGET=http://127.0.0.1:48090 VITE_API_URL=/admin-api VITE_BASE_PATH=/ VITE_APP_TENANT_ENABLE=true diff --git a/am-web/.env.local b/am-web/.env.local index 7e3eec5..5ce3f62 100644 --- a/am-web/.env.local +++ b/am-web/.env.local @@ -4,7 +4,8 @@ NODE_ENV=development VITE_DEV=true # 请求路径 -VITE_BASE_URL=http://localhost:48090 +VITE_BASE_URL= +VITE_DEV_PROXY_TARGET=http://127.0.0.1:48090 # 文件上传类型:server - 后端上传, client - 前端直连上传,仅支持 S3 服务 VITE_UPLOAD_TYPE=server diff --git a/am-web/src/api/lab/execution/index.ts b/am-web/src/api/lab/execution/index.ts index f70539a..a74e3a8 100644 --- a/am-web/src/api/lab/execution/index.ts +++ b/am-web/src/api/lab/execution/index.ts @@ -9,6 +9,7 @@ export interface LabExecutionVO { taskNo?: string parentExecutionId?: number | string executionType: string + supplementCollecting?: boolean methodRefId?: number | string methodExternalId?: string methodVersion?: string diff --git a/am-web/src/api/lab/scan-task/index.ts b/am-web/src/api/lab/scan-task/index.ts index f9417f1..2c291e0 100644 --- a/am-web/src/api/lab/scan-task/index.ts +++ b/am-web/src/api/lab/scan-task/index.ts @@ -108,6 +108,10 @@ export interface ScanPrecheck { items: { code: string; passed: boolean; message: string }[] } const base = '/lab/scan-task' +export interface SupplementOption { available: boolean; parentExecutionId?: Id; parentExecutionNo?: string; projectId?: string; physicalSerial?: string; message?: string } +export const getSupplementOption = (taskId: Id, unitId: Id) => request.get({ url: base + '/supplement-option', params: { taskId, unitId } }) +export const startSupplement = (data: { taskId: Id; unitId: Id; parentExecutionId: Id; expectedRevision: number; durationSeconds: number; reason: string; idempotencyKey: string; sampleConfirmed: boolean; fixtureConfirmed: boolean; loadedConfirmed: boolean }) => request.post({ url: base + '/supplement', data }) +export const finishSupplement = (taskId: Id, executionId: Id) => request.post({ url: base + '/finish-supplement', data: { taskId, executionId } }) export const acquireResources = (taskId: Id, expectedRevision: number) => request.post({ url: base + '/acquire-resources', data: { taskId, expectedRevision } }) export const releaseResources = (taskId: Id, reason: string) => diff --git a/am-web/src/api/lab/scan-task/scannerView.ts b/am-web/src/api/lab/scan-task/scannerView.ts index ebaa306..142440f 100644 --- a/am-web/src/api/lab/scan-task/scannerView.ts +++ b/am-web/src/api/lab/scan-task/scannerView.ts @@ -1,6 +1,7 @@ import request from '@/config/axios' import { getAccessToken, getTenantId, getVisitTenantId } from '@/utils/auth' import { readScannerBinary } from '@/views/lab/scan-task/scannerBinary.mjs' +import { consumeScannerMjpeg } from '@/cmvr/common/utils/scannerMjpeg.mjs' export interface ScannerExecutionView { executionId: string @@ -61,3 +62,15 @@ export async function getScannerExecutionImage(executionId: string | number, sig } return response.blob() } + +export async function streamScannerExecution(executionId: string | number, onFrame: (bytes: Uint8Array) => void, signal: AbortSignal) { + const response = await fetch(`${import.meta.env.VITE_BASE_URL}/admin-api${path}/stream?executionId=${encodeURIComponent(executionId)}`, { + headers: scannerHeaders(), signal, cache: 'no-store' + }) + if (!response.ok || !response.headers.get('content-type')?.startsWith('multipart/x-mixed-replace') || !response.body) { + const error = await response.json().catch(() => ({})) + throw new Error(error.msg || '扫描流暂不可用,正在重新核对状态') + } + await consumeScannerMjpeg(response.body, onFrame, signal) + if (!signal.aborted) throw new Error('扫描流已断开,正在重新连接') +} diff --git a/am-web/src/cmvr/common/api/flow/flow.js b/am-web/src/cmvr/common/api/flow/flow.js index 11276d6..186903a 100644 --- a/am-web/src/cmvr/common/api/flow/flow.js +++ b/am-web/src/cmvr/common/api/flow/flow.js @@ -73,6 +73,7 @@ export function flowView(data) { export function flowPause(instId) { return request({ url: `/flow/pause/${instId}`, + timeout: 300000, method: 'post' }) } @@ -80,6 +81,7 @@ export function flowPause(instId) { export function flowResume(instId) { return request({ url: `/flow/resume/${instId}`, + timeout: 300000, method: 'post' }) } @@ -87,6 +89,7 @@ export function flowResume(instId) { export function flowStop(instId) { return request({ url: `/flow/stop/${instId}`, + timeout: 300000, method: 'post' }) } diff --git a/am-web/src/cmvr/common/utils/flowControlGate.mjs b/am-web/src/cmvr/common/utils/flowControlGate.mjs new file mode 100644 index 0000000..73b76a0 --- /dev/null +++ b/am-web/src/cmvr/common/utils/flowControlGate.mjs @@ -0,0 +1,18 @@ +// Hold one control request through its response handling, including errors. +export function createFlowControlGate(onPending) { + let pending = false + return { + async run(action, request) { + if (pending) return false + pending = true + onPending(action) + try { + await request() + return true + } finally { + pending = false + onPending('') + } + } + } +} diff --git a/am-web/src/cmvr/common/utils/flowControlGate.test.mjs b/am-web/src/cmvr/common/utils/flowControlGate.test.mjs new file mode 100644 index 0000000..e329bb9 --- /dev/null +++ b/am-web/src/cmvr/common/utils/flowControlGate.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createFlowControlGate } from './flowControlGate.mjs' + +test('终止请求及响应处理完成前,重复终止与暂停恢复都不下发', async () => { + const states = [], calls = [] + const gate = createFlowControlGate(action => states.push(action)) + let finish, handleResponse + const first = gate.run('stop', async () => { + calls.push('stop') + await new Promise(resolve => { finish = resolve }) + await new Promise(resolve => { handleResponse = resolve }) + }) + assert.deepEqual(states, ['stop']) + for (const action of ['stop', 'pause', 'resume']) + assert.equal(await gate.run(action, () => calls.push(action)), false) + finish(); await Promise.resolve() + assert.equal(await gate.run('stop', () => calls.push('duplicate')), false) + handleResponse(); assert.equal(await first, true) + assert.deepEqual(calls, ['stop']); assert.deepEqual(states, ['stop', '']) +}) +test('请求失败后恢复按钮状态,并继续向调用方传递失败', async () => { + const states = [], gate = createFlowControlGate(action => states.push(action)) + await assert.rejects(gate.run('stop', async () => { throw new Error('停止尚未确认') }), /停止尚未确认/) + assert.deepEqual(states, ['stop', '']) + assert.equal(await gate.run('pause', async () => {}), true) +}) +test('同步异常同样清理操作锁,不能让按钮永久停在终止中', async () => { + const states = [], gate = createFlowControlGate(action => states.push(action)) + await assert.rejects(gate.run('stop', () => { throw new Error('network unavailable') }), /network/) + assert.deepEqual(states, ['stop', '']) +}) diff --git a/am-web/src/cmvr/common/utils/nodeIdentity.mjs b/am-web/src/cmvr/common/utils/nodeIdentity.mjs new file mode 100644 index 0000000..a468881 --- /dev/null +++ b/am-web/src/cmvr/common/utils/nodeIdentity.mjs @@ -0,0 +1,39 @@ +const normalizeAction = value => String(value || '').trim().toUpperCase() +const terminalActions = { START: '流程开始', END: '流程结束', SUB_START: '单次循环开始', SUB_END: '单次循环结束' } + +// The editable node name is never evidence of its component type. +export function createNodeIdentityResolver(groups) { + const byAction = new Map(), byType = new Map() + for (const group of groups || []) { + for (const node of group.nodeList || []) { + const identity = Object.freeze({ + label: node.name, category: group.collapseTitle || '', known: true, + }) + const action = normalizeAction(node.action) + if (action && action !== 'NONE') byAction.set(action, identity) + if (node.type) { + const candidates = byType.get(node.type) || [] + candidates.push(identity) + byType.set(node.type, candidates) + } + } + } + return node => { + const properties = node?.properties || node || {} + const action = normalizeAction(properties.action) + const type = node?.type || properties.type + let identity = byAction.get(action) + if (!identity && Object.hasOwn(terminalActions, action)) { + identity = { label: terminalActions[action], category: '流程', known: true } + } + // Old data may omit action. Only an unambiguous renderer type is safe. + if (!identity && (!action || action === 'NONE')) { + const candidates = byType.get(type) || [] + if (candidates.length === 1) identity = candidates[0] + else if (type === 'start') identity = { label: '流程开始', category: '流程', known: true } + else if (type === 'end') identity = { label: '流程结束', category: '流程', known: true } + else if (type === 'selectArea') identity = { label: '分组', category: '流程', known: true } + } + return { ...(identity || { label: '未识别组件', category: '', known: false }), action } + } +} diff --git a/am-web/src/cmvr/common/utils/nodeIdentity.test.mjs b/am-web/src/cmvr/common/utils/nodeIdentity.test.mjs new file mode 100644 index 0000000..a374648 --- /dev/null +++ b/am-web/src/cmvr/common/utils/nodeIdentity.test.mjs @@ -0,0 +1,46 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createNodeIdentityResolver } from './nodeIdentity.mjs' +import { createWorkcellNodeGroups } from './scanMotorNodes.mjs' + +const groups = [...createWorkcellNodeGroups(), { + collapseTitle: '功能', nodeList: [ + { name: '睡眠', action: 'sleep', type: 'sleep' }, + { name: 'HTTP请求', action: 'HTTP', type: 'http' }, + { name: '分支', action: 'BRANCH', type: 'branch' }, + ], +}] +const identify = createNodeIdentityResolver(groups) + +test('扫描和电机所有组件改名、保存重载后仍能识别原组件,不改写流程数据', () => { + for (const group of createWorkcellNodeGroups()) for (const definition of group.nodeList) { + const node = JSON.parse(JSON.stringify({ type: definition.type, properties: { ...definition, name: '我的步骤' } })) + const before = JSON.stringify(node) + assert.equal(identify(node).label, definition.name) + assert.equal(identify(node).category, group.collapseTitle) + assert.equal(identify(node).known, true) + assert.equal(JSON.stringify(node), before) + } +}) +test('普通功能节点及大小写不同的旧动作标识可以识别,当前名称不参与匹配', () => { + assert.equal(identify({ action: ' sleep ', name: '等待采集' }).label, '睡眠') + assert.equal(identify({ properties: { action: 'http', name: '发送通知' } }).label, 'HTTP请求') + assert.equal(identify({ properties: { action: 'BRANCH', name: '判断采集结果' } }).label, '分支') +}) +test('缺少动作标识的旧流程仅按唯一类型回退,共用serviceNode不能误认成某个扫描组件', () => { + assert.equal(identify({ type: 'sleep', properties: { name: '等待' } }).label, '睡眠') + assert.equal(identify({ type: 'serviceNode', properties: { name: '创建扫描工程' } }).known, false) + assert.equal(identify({ type: 'start', properties: { name: '入口' } }).label, '流程开始') + assert.equal(identify({ type: 'end', properties: {} }).label, '流程结束') + assert.equal(identify({ type: 'selectArea', properties: { action: 'NONE' } }).label, '分组') +}) +test('不认识的动作保留标识,不能因名称或渲染类型相同误认已有组件', () => { + const unknown = identify({ type: 'sleep', properties: { action: 'CUSTOM_DELAY', name: '睡眠' } }) + assert.deepEqual(unknown, { label: '未识别组件', category: '', known: false, action: 'CUSTOM_DELAY' }) + assert.equal(identify(null).known, false) +}) +test('画布内置入口、出口和循环入口出口无需在可拖拽组件库中重复登记', () => { + for (const [action, label] of Object.entries({ START: '流程开始', END: '流程结束', SUB_START: '单次循环开始', SUB_END: '单次循环结束' })) { + assert.equal(identify({ properties: { action: action.toLowerCase(), name: '自定义入口' } }).label, label) + } +}) diff --git a/am-web/src/cmvr/common/views/flow/components/NodeTitle.vue b/am-web/src/cmvr/common/views/flow/components/NodeTitle.vue index 7140686..2ded025 100644 --- a/am-web/src/cmvr/common/views/flow/components/NodeTitle.vue +++ b/am-web/src/cmvr/common/views/flow/components/NodeTitle.vue @@ -6,7 +6,7 @@
-
+
@@ -14,7 +14,7 @@
{{ localName }} - {{ typeLabel }} + {{ typeLabel }}