feat: add standalone Windows deployment and resource-aware large file transfers

This commit is contained in:
lixiaolong 2026-11-11 17:17:50 +08:00
parent 71bd55919d
commit 0a5a083e48
56 changed files with 1249 additions and 105 deletions

View File

@ -1,6 +1,6 @@
# AM FreeScan
独立的任务管理与检测配置项目。前后端分离,业务数据使用 `192.168.28.10:3306/am-freescan`,不读取旧系统业务数据。
独立的任务管理与检测配置项目。前后端分离,现有开发环境使用 `192.168.28.10:3306/am-freescan`。Windows 11 新电脑独立部署使用本机中间件,并迁移当前业务数据,详见 [完整部署与迁移手册](deploy/windows11/README.md)。
- 前端:Vue 3、TypeScript、Element Plus、Vite、Vue Flow。
- 后端:Java 17、Spring Boot 3.5.15、Yudao、MyBatis Plus、MySQL 8、Redis。

View File

@ -0,0 +1,16 @@
package cn.iocoder.yudao.framework.common.util.io;
/** Protect legacy byte-array storage clients by actual JVM headroom; streaming scanner archives do not use this gate. */
public final class UploadMemoryGuard implements AutoCloseable {
private static long reserved;
private final long bytes;
private boolean closed;
private UploadMemoryGuard(long bytes){this.bytes=bytes;}
public static synchronized UploadMemoryGuard reserve(long length){
var runtime=Runtime.getRuntime();long available=runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory());
if(length<0||length>Integer.MAX_VALUE-8L||length>Math.max(0,available-reserved)/4)
throw new IllegalArgumentException("当前文件存储客户端可用内存不足,请使用流式扫描归档或增加后端可用内存");
long estimate=Math.multiplyExact(length,3);reserved+=estimate;return new UploadMemoryGuard(estimate);
}
@Override public void close(){synchronized(UploadMemoryGuard.class){if(!closed){reserved-=bytes;closed=true;}}}
}

View File

@ -14,7 +14,8 @@ import java.util.function.LongSupplier;
/** Durable platform copies for every scanner export, including ordinary workflow trial runs. */
@Component
public class ScannerFileArchive {
private static final long MAX_BYTES=100L*1024*1024;
private static final long DISK_RESERVE=512L*1024*1024;
private final java.util.concurrent.Semaphore downloads=new java.util.concurrent.Semaphore(2);
private static final String URL="/admin-api/cmvr/scanner/files/";
@Value("${lab.artifact.nas-root:./.local/artifacts}") private String root;
private final Object[] locks=new Object[64];
@ -58,6 +59,7 @@ public class ScannerFileArchive {
private ObjectNode save(String id,String remote,String endpoint,String task,JsonNode expected,Function<String,ScannerHttpClient.Binary> download,LongSupplier remaining){
Path target=path(id),temporary=null,metaTemporary=null;
if(!downloads.tryAcquire())throw failure("归档通道正忙,请稍后重试文件下载");
try{
Files.createDirectories(target.getParent());temporary=Files.createTempFile(target.getParent(),id,".part");
String name;long bytes=0;var digest=java.security.MessageDigest.getInstance("SHA-256");
@ -67,10 +69,11 @@ public class ScannerFileArchive {
if(name.isBlank()&&header!=null)name=ContentDisposition.parse(header).getFilename();
validateName(name);
String declared=header(source.headers(),"content-length");long length=declared==null?-1:Long.parseLong(declared);
if(length>MAX_BYTES)throw failure("单个文件超过100MiB归档限制");
if(length>=0&&length>Files.getFileStore(target.getParent()).getUsableSpace()-DISK_RESERVE)throw failure("归档磁盘空间不足,需保留512MiB运行空间");
byte[] buffer=new byte[65536];int n;
while((n=source.stream().read(buffer))!=-1){
remaining.getAsLong();bytes+=n;if(bytes>MAX_BYTES)throw failure("单个文件超过100MiB归档限制");
remaining.getAsLong();bytes=Math.addExact(bytes,n);
if((bytes%(8L*1024*1024))<n&&Files.getFileStore(target.getParent()).getUsableSpace()<DISK_RESERVE)throw failure("归档磁盘可用空间不足512MiB");
digest.update(buffer,0,n);out.write(buffer,0,n);
}
if(bytes==0||length>=0&&bytes!=length)throw failure("文件为空或下载不完整");
@ -87,7 +90,7 @@ public class ScannerFileArchive {
return receipt;
}catch(ScannerException error){throw error;}
catch(Exception error){throw failure("文件下载或持久保存失败:"+Objects.toString(error.getMessage(),error.getClass().getSimpleName()));}
finally{for(Path part:new Path[]{temporary,metaTemporary})if(part!=null)try{Files.deleteIfExists(part);}catch(IOException ignored){}}
finally{for(Path part:new Path[]{temporary,metaTemporary})if(part!=null)try{Files.deleteIfExists(part);}catch(IOException ignored){}downloads.release();}
}
private static void verifyLength(JsonNode expected,long bytes){
JsonNode size=expected.hasNonNull("bytes")?expected.get("bytes"):expected.get("size");
@ -99,7 +102,7 @@ public class ScannerFileArchive {
try{
if(Files.size(meta)>16384||Files.isSymbolicLink(target)||Files.isSymbolicLink(meta))throw new IOException("metadata");
var receipt=ScannerRequestValidator.JSON.readTree(Files.readString(meta));validateName(receipt.path("name").asText());
if(!receipt.isObject()||!id.equals(receipt.path("fileId").asText())||Files.size(target)<=0||Files.size(target)>MAX_BYTES
if(!receipt.isObject()||!id.equals(receipt.path("fileId").asText())||Files.size(target)<=0
||Files.size(target)!=receipt.path("bytes").asLong()||!cn.hutool.crypto.digest.DigestUtil.sha256Hex(target.toFile()).equals(receipt.path("sha256").asText()))throw new IOException("checksum");
return (ObjectNode)receipt;
}catch(Exception error){throw failure("平台归档文件缺失或损坏,请检查成果存储;不会回退到临时URL");}

View File

@ -16,12 +16,24 @@ public class ScannerFixtureFrameworkStore {
return Path.of(root).toAbsolutePath().normalize().resolve("fixture-framework").resolve(id);
}
public JSONObject save(String name,byte[] bytes) {
if(!ScannerFrameworkReferences.frameworkName(name)||bytes==null||bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES)throw new ScannerException("invalid_file","框架文件必须为非空P3/TXT/ASC且不超过100MiB",400);
if(bytes==null)throw new ScannerException("invalid_file","框架文件不能为空",400);
return save(name,new ByteArrayInputStream(bytes),bytes.length);
}
public JSONObject save(String name,InputStream source,long expected) {
if(!ScannerFrameworkReferences.frameworkName(name))throw new ScannerException("invalid_file","框架文件必须为非空P3/TXT/ASC",400);
name=ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(name));
String id=UUID.randomUUID().toString().replace("-","");Path p=path(id);
var m=JSONObject.of("fileId",id,"name",name,"bytes",bytes.length,"sha256",cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes),"downloadUrl","/admin-api/cmvr/scanner/files/"+id);
try{Files.createDirectories(p.getParent());Files.write(p,bytes,StandardOpenOption.CREATE_NEW);Files.writeString(p.resolveSibling(id+".json"),m.toJSONString(),StandardOpenOption.CREATE_NEW);return m;}
catch(IOException e){
try{
Files.createDirectories(p.getParent());long size=0;var digest=java.security.MessageDigest.getInstance("SHA-256");
if(Files.getFileStore(p.getParent()).getUsableSpace()<512L*1024*1024)throw new IOException("disk reserve");
try(var out=Files.newOutputStream(p,StandardOpenOption.CREATE_NEW)){
byte[] buffer=new byte[65536];int n;while((n=source.read(buffer))!=-1){size=Math.addExact(size,n);if((size%(8L*1024*1024))<n&&Files.getFileStore(p).getUsableSpace()<512L*1024*1024)throw new IOException("disk reserve");digest.update(buffer,0,n);out.write(buffer,0,n);}
}
if(size==0||expected>=0&&size!=expected)throw new IOException("length");
var m=JSONObject.of("fileId",id,"name",name,"bytes",size,"sha256",HexFormat.of().formatHex(digest.digest()),"downloadUrl","/admin-api/cmvr/scanner/files/"+id);
Files.writeString(p.resolveSibling(id+".json"),m.toJSONString(),StandardOpenOption.CREATE_NEW);return m;
}
catch(Exception e){
try{Files.deleteIfExists(p);Files.deleteIfExists(p.resolveSibling(id+".json"));}catch(IOException ignored){}
throw new ScannerException("framework_archive_failed","框架点保存失败,原版本保留",503);
}
@ -30,12 +42,12 @@ public class ScannerFixtureFrameworkStore {
Path p=path(id),meta=p.resolveSibling(p.getFileName()+".json");
if(!Files.exists(p)&&!Files.exists(meta))return null;
try{
if(Files.size(p)==0||Files.size(p)>ScannerFrameworkService.MAX_BYTES||Files.size(meta)>8192)throw new IOException("size");
var m=JSONObject.parseObject(Files.readString(meta));byte[] bytes=Files.readAllBytes(p);
if(Files.size(p)==0||Files.size(meta)>8192)throw new IOException("size");
var m=JSONObject.parseObject(Files.readString(meta));
if(!p.getFileName().toString().equals(m.getString("fileId")))throw new IOException("id");
ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(m.getString("name")));
if(bytes.length!=m.getIntValue("bytes")||!cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes).equals(m.getString("sha256")))throw new IOException("checksum");
return new ScannerHttpClient.Binary(new ByteArrayInputStream(bytes),Map.of("content-length",List.of(""+bytes.length),"content-disposition",List.of("attachment; filename*=UTF-8''"+ScannerFrameworkReferences.encode(m.getString("name")))));
if(Files.size(p)!=m.getLongValue("bytes")||!cn.hutool.crypto.digest.DigestUtil.sha256Hex(p.toFile()).equals(m.getString("sha256")))throw new IOException("checksum");
return new ScannerHttpClient.Binary(Files.newInputStream(p),Map.of("content-length",List.of(""+Files.size(p)),"content-disposition",List.of("attachment; filename*=UTF-8''"+ScannerFrameworkReferences.encode(m.getString("name")))));
}catch(IOException|RuntimeException e){throw new ScannerException("framework_archive_unavailable","框架点文件缺失或损坏,请重新录入或导入",503);}
}
public JSONObject metadata(String id){
@ -43,7 +55,7 @@ public class ScannerFixtureFrameworkStore {
if(data==null)throw new IOException();
Path p=path(id);var m=JSONObject.parseObject(Files.readString(p.resolveSibling(p.getFileName()+".json")));
// Return only canonical local references, never caller-supplied URLs or names.
return JSONObject.of("fileId",p.getFileName().toString(),"name",m.getString("name"),"bytes",m.getIntValue("bytes"),"sha256",m.getString("sha256"),"downloadUrl","/admin-api/cmvr/scanner/files/"+p.getFileName());
return JSONObject.of("fileId",p.getFileName().toString(),"name",m.getString("name"),"bytes",m.getLongValue("bytes"),"sha256",m.getString("sha256"),"downloadUrl","/admin-api/cmvr/scanner/files/"+p.getFileName());
}catch(IOException e){throw new ScannerException("framework_archive_unavailable","框架点文件不可用,请重新录入或导入",503);}
}
public void verify(Object urls){for(var s:ScannerFrameworkReferences.sources(urls))metadata(s.fileId());}

View File

@ -35,20 +35,20 @@ public class ScannerFrameworkReferenceService {
try {
var files=ScannerRequestValidator.JSON.createArrayNode();var ids=ScannerRequestValidator.JSON.createArrayNode();
for(var source:sources) {
byte[] bytes;String name;
java.nio.file.Path staged=null;
try {
long bytes;String name;
try(var file=client.frameworkFile(source.fileId(),budget(deadline))) {
long declared=headerLength(file.headers());
if(declared>ScannerFrameworkService.MAX_BYTES)throw bad("框架下载文件超过100MiB");
name=headerName(file.headers(),source.name());
bytes=file.stream().readNBytes(ScannerFrameworkService.MAX_BYTES+1);
if(bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES||declared>=0&&declared!=bytes.length
||source.bytes()!=null&&source.bytes()!=bytes.length)throw bad("框架下载文件为空、超限或与导出回执长度不符");
staged=ScannerTransferFiles.copy(file.stream(),declared,()->budget(deadline));bytes=java.nio.file.Files.size(staged);
if(source.bytes()!=null&&source.bytes()!=bytes)throw bad("框架下载文件与导出回执长度不符");
}catch(ScannerException error) {
if(error.remoteStatus==404)throw new ScannerException("framework_source_unavailable",
"框架源文件不存在或URL已失效,请重新导出P3并引用最新结果(HTTP404)",404);
throw error;
}
String contentHash=cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes);
String contentHash=cn.hutool.crypto.digest.DigestUtil.sha256Hex(staged.toFile());
String fileHash=ScannerService.hash(endpoint+":"+status.path("sessionId").asText()+":"+source.fileId()+":"+name+":"+contentHash);
String fileKey=ScannerService.hash("framework-file:"+fileHash);
var cached=journal.get(fileKey);JsonNode receipt;
@ -63,13 +63,14 @@ public class ScannerFrameworkReferenceService {
else {
begin(fileKey,"FILE",endpoint,fileHash,"workflow:"+instId);
try {
receipt=uploads.upload(ScannerFrameworkReferences.encode(name),"application/octet-stream",bytes.length,new ByteArrayInputStream(bytes),budget(deadline));
try(var frameInput=java.nio.file.Files.newInputStream(staged)){receipt=uploads.upload(ScannerFrameworkReferences.encode(name),"application/octet-stream",bytes,frameInput,budget(deadline));}
journal.ready(fileKey,receipt.toString());
}catch(RuntimeException error){journal.uncertain(fileKey,error.getMessage());throw error;}
}
ids.add(receipt.path("fileId").asText());
files.addObject().put("sourceUrl",source.url()).put("sourceFileId",source.fileId()).put("fileId",receipt.path("fileId").asText())
.put("name",name).put("bytes",bytes.length).put("sha256",contentHash).put("reused",reused);
.put("name",name).put("bytes",bytes).put("sha256",contentHash).put("reused",reused);
}finally{if(staged!=null)java.nio.file.Files.deleteIfExists(staged);}
}
ObjectNode body=ScannerRequestValidator.JSON.createObjectNode();body.set("fileIds",ids);
ScannerRequestValidator.validate(ScannerOperation.FRAMEWORK_IMPORT,body);
@ -93,10 +94,12 @@ public class ScannerFrameworkReferenceService {
}
private boolean registered(JsonNode receipt,String expectedHash,long deadline) throws IOException {
try(var file=client.remoteFile(receipt.path("fileId").asText(),budget(deadline))){
byte[] bytes=file.stream().readNBytes(ScannerFrameworkService.MAX_BYTES+1);
if(bytes.length==0||bytes.length>ScannerFrameworkService.MAX_BYTES||!expectedHash.equals(cn.hutool.crypto.digest.DigestUtil.sha256Hex(bytes)))throw bad("扫描服务已登记文件与平台框架点校验值不一致");
var digest=java.security.MessageDigest.getInstance("SHA-256");long size=0;byte[] buffer=new byte[65536];int n;
while((n=file.stream().read(buffer))!=-1){budget(deadline);size=Math.addExact(size,n);digest.update(buffer,0,n);}
if(size==0||!expectedHash.equals(java.util.HexFormat.of().formatHex(digest.digest())))throw bad("扫描服务已登记文件与平台框架点校验值不一致");
return true;
}catch(ScannerException error){if(error.remoteStatus==404)return false;throw error;}
catch(java.security.NoSuchAlgorithmException impossible){throw new IllegalStateException(impossible);}
}
private void begin(String key,String kind,String endpoint,String hash,String owner) {
try {journal.intent(key,kind,endpoint,hash,owner);}

View File

@ -42,7 +42,7 @@ public final class ScannerFrameworkReferences {
Long bytes=null;
JsonNode length=item.has("bytes")?item.get("bytes"):item.get("size");
if(length!=null&&!length.isNull()) {
if(!length.isIntegralNumber()||!length.canConvertToLong()||length.asLong()<=0||length.asLong()>ScannerFrameworkService.MAX_BYTES)throw bad("框架文件必须非空且单个不超过100MiB");
if(!length.isIntegralNumber()||!length.canConvertToLong()||length.asLong()<=0)throw bad("框架文件必须非空且长度有效");
bytes=length.asLong();
}
Source source=new Source(url,id.toLowerCase(Locale.ROOT),name,bytes);

View File

@ -14,7 +14,6 @@ import java.util.concurrent.Semaphore;
@Service
@RequiredArgsConstructor
public class ScannerFrameworkService {
public static final int MAX_BYTES=100*1024*1024;
private final ScannerHttpClient client;
private final ScannerProperties settings;
private final Semaphore uploads=new Semaphore(2);
@ -32,26 +31,24 @@ public class ScannerFrameworkService {
if(contentType==null||!contentType.split(";",2)[0].trim().equalsIgnoreCase("application/octet-stream"))
throw new ScannerException("invalid_media_type","框架上传仅接收application/octet-stream原始文件",415);
String name=decodeName(encodedName);
if(contentLength>MAX_BYTES)throw tooLarge();
if(!uploads.tryAcquire())throw new ScannerException("upload_busy","最多同时上传两个框架文件,请稍后重试",429);
java.nio.file.Path staged=null;
try {
byte[] bytes=source.readNBytes(MAX_BYTES+1);
if(bytes.length>MAX_BYTES)throw tooLarge();
if(bytes.length==0||contentLength>=0&&contentLength!=bytes.length)
throw new ScannerException("invalid_file","上传文件不能为空,实际长度须与声明一致",400);
staged=ScannerTransferFiles.copy(source,contentLength,()->{if(Thread.currentThread().isInterrupted())throw new ScannerException("interrupted","文件上传已中断",504);});
long size=java.nio.file.Files.size(staged);
// No automatic retry: a lost 201 response may still have consumed vendor quota.
JsonNode result;
try {result=client.uploadFramework(URLEncoder.encode(name,StandardCharsets.UTF_8).replace("+","%20"),bytes,Math.min(budgetMs,settings.getRequestTimeoutMs()));}
try {result=client.uploadFramework(URLEncoder.encode(name,StandardCharsets.UTF_8).replace("+","%20"),staged,Math.min(budgetMs,settings.getRequestTimeoutMs()));}
catch(ScannerException error){
if(error.remoteStatus==413)throw new ScannerException(error.scannerCode,"扫描服务拒绝此文件大小。平台支持100MiB,请检查扫描服务自身的上传上限;原始错误:"+error.getMessage(),413);
if(error.remoteStatus==413)throw new ScannerException(error.scannerCode,"扫描服务自身拒绝此文件大小;平台不设单文件大小上限,请核对厂家服务配置。原始错误:"+error.getMessage(),413);
throw error;
}
if(!result.path("fileId").asText().matches("[a-fA-F0-9]{32}")||!name.equals(result.path("name").asText())
||!result.path("size").isIntegralNumber()||result.path("size").asLong()!=bytes.length)
||!result.path("size").isIntegralNumber()||result.path("size").asLong()!=size)
throw new ScannerException("upload_result_uncertain","文件可能已上传,但回执缺少有效编号或长度;请核对服务,勿自动重传",502);
return result;
}catch(IOException error){throw new ScannerException("invalid_file","读取上传文件失败,未提交设备导入",400);}
finally {uploads.release();}
finally {if(staged!=null)try{java.nio.file.Files.deleteIfExists(staged);}catch(IOException ignored){}uploads.release();}
}
public static String decodeName(String encoded) {
if(encoded==null||encoded.isEmpty()||encoded.length()>720)throw invalidName();
@ -75,5 +72,4 @@ public class ScannerFrameworkService {
catch(Exception error){throw invalidName();}
}
private static ScannerException invalidName(){return new ScannerException("invalid_file_name","请选择.p3、.txt或.asc文件,文件名不能包含目录,且不超过240个UTF-8字节及128个UTF-16单元",400);}
private static ScannerException tooLarge(){return new ScannerException("file_too_large","单个框架文件不能超过100MiB",413);}
}

View File

@ -68,13 +68,20 @@ public class ScannerHttpClient {
return body.toString();
}
public JsonNode uploadFramework(String encodedName,byte[] bytes,long timeoutMs) {
return uploadFramework(encodedName,HttpRequest.BodyPublishers.ofByteArray(bytes),timeoutMs);
}
public JsonNode uploadFramework(String encodedName,java.nio.file.Path file,long timeoutMs) {
try{return uploadFramework(encodedName,HttpRequest.BodyPublishers.ofFile(file),timeoutMs);}
catch(java.io.FileNotFoundException error){throw new ScannerException("invalid_file","框架暂存文件不可读",400);}
}
private JsonNode uploadFramework(String encodedName,HttpRequest.BodyPublisher publisher,long timeoutMs) {
requireConfigured();
try {
var address=settings.connection();URI uri=new URI("http",null,address.host(),address.port(),ScannerOperation.FRAMEWORK_UPLOAD.path,null,null);
var request=HttpRequest.newBuilder(uri).timeout(Duration.ofMillis(Math.max(1,timeoutMs)))
.header("Accept","application/json").header("Authorization","Bearer "+settings.getApiKey())
.header("Content-Type","application/octet-stream").header("X-File-Name",encodedName)
.POST(HttpRequest.BodyPublishers.ofByteArray(bytes)).build();
.POST(publisher).build();
return json(request,201,timeoutMs);
}catch(ScannerException error){throw error;}
catch(Exception error){throw new ScannerException("invalid_request","框架上传请求无效",400);}

View File

@ -97,7 +97,6 @@ public class ScannerMonitoringService {
.orElseThrow(()->new ScannerException("file_not_owned","文件不属于本次执行",404));
var archived=client.archivedFile(fileId);if(archived!=null)return archived;
if(!file.path("binding").path("endpoint").asText().equals(client.endpointKey()))throw new ScannerException("endpoint_changed","扫描服务已变更,原文件不能从当前地址读取",409);
if(file.path("bytes").asLong()>100L*1024*1024)throw new ScannerException("model_too_large","文件超过在线三维查看的100MiB限制,请使用原始成果下载",413);
return scanner.binary(ScannerOperation.FILE,fileId);
}

View File

@ -0,0 +1,16 @@
package com.cmvr.scanner;
import java.io.*;
import java.nio.file.*;
/** Bounded-memory staging; disk availability, not an arbitrary per-file byte limit, controls writes. */
final class ScannerTransferFiles {
private ScannerTransferFiles(){}
static Path copy(InputStream input,long expected,Runnable checkpoint) throws IOException {
Path file=Files.createTempFile("freescan-transfer-",".part");boolean complete=false;
try {
if(expected>Files.getFileStore(file).getUsableSpace()-512L*1024*1024)throw new IOException("磁盘可用空间不足,需保留512MiB运行空间");
long size=0;try(var out=Files.newOutputStream(file)){byte[] buffer=new byte[65536];int n;while((n=input.read(buffer))!=-1){checkpoint.run();size=Math.addExact(size,n);if((size%(8L*1024*1024))<n&&Files.getFileStore(file).getUsableSpace()<512L*1024*1024)throw new IOException("磁盘余量不足512MiB");out.write(buffer,0,n);}}
if(size==0||expected>=0&&size!=expected)throw new IOException("文件为空或实际长度与声明不一致");complete=true;return file;
}finally{if(!complete)Files.deleteIfExists(file);}
}
}

View File

@ -24,14 +24,11 @@ public class ScannerLocalFrameworkController {
public AjaxResult upload(@RequestPart("file") MultipartFile file) {
if (!Long.valueOf(1L).equals(TenantContextHolder.getTenantId()))
throw new ScannerException("invalid_tenant", "框架文件仅属于本项目主租户", 403);
if (file == null || file.isEmpty() || file.getSize() > ScannerFrameworkService.MAX_BYTES)
throw new ScannerException("invalid_file", "框架文件不能为空,且单个不能超过100MiB", 400);
if (file == null || file.isEmpty())throw new ScannerException("invalid_file", "框架文件不能为空", 400);
String name = ScannerFrameworkService.decodeName(ScannerFrameworkReferences.encode(file.getOriginalFilename() == null ? "" : file.getOriginalFilename()));
if (!uploads.tryAcquire()) throw new ScannerException("upload_busy", "当前上传较多,请稍后重新选择文件", 429);
try (var input = file.getInputStream()) {
byte[] bytes = input.readNBytes(ScannerFrameworkService.MAX_BYTES + 1);
if (bytes.length != file.getSize()) throw new ScannerException("invalid_file", "文件内容与声明长度不一致,请重新选择", 400);
return AjaxResult.success(store.save(name, bytes));
return AjaxResult.success(store.save(name, input, file.getSize()));
} catch (IOException error) {
throw new ScannerException("framework_upload_failed", "本地文件读取失败,请重新选择", 400);
} finally { uploads.release(); }

View File

@ -57,23 +57,20 @@ public class ScannerFrameworkIntegrationTest {
}
@Test public void emptyOversizedTruncatedAndWrongMediaFilesNeverReachTransport() {
assertEquals(400,assertThrows(ScannerException.class,()->upload("Frame.p3",new byte[0])).remoteStatus);
assertEquals(413,assertThrows(ScannerException.class,()->framework.upload("Frame.p3","application/octet-stream",ScannerFrameworkService.MAX_BYTES+1L,InputStream.nullInputStream())).remoteStatus);
var oversized=assertThrows(ScannerException.class,()->framework.upload("Frame.p3","application/octet-stream",-1,new ByteArrayInputStream(new byte[ScannerFrameworkService.MAX_BYTES+1])));
assertEquals(413,oversized.remoteStatus);assertFalse(oversized.getMessage().contains("扫描服务拒绝"));
assertEquals(400,assertThrows(ScannerException.class,()->framework.upload("Frame.p3","application/octet-stream",(100L*1024*1024)+1,InputStream.nullInputStream())).remoteStatus);
assertEquals(400,assertThrows(ScannerException.class,()->framework.upload("Frame.p3","application/octet-stream",2,new ByteArrayInputStream(new byte[]{1}))).remoteStatus);
for(String type:List.of("application/json","multipart/form-data","text/plain"))assertEquals(415,assertThrows(ScannerException.class,()->framework.upload("Frame.p3",type,1,new ByteArrayInputStream(new byte[]{1}))).remoteStatus);
assertEquals(0,calls.get());
}
@Test public void exact100MiBIsAcceptedIncludingAnUnknownLengthRequest() {
assertEquals(100*1024*1024,ScannerFrameworkService.MAX_BYTES);
byte[] bytes=new byte[ScannerFrameworkService.MAX_BYTES];bytes[0]=42;
byte[] bytes=new byte[100*1024*1024+1];bytes[0]=42;
assertEquals(bytes.length,framework.upload("Frame.ASC","application/octet-stream",-1,new ByteArrayInputStream(bytes)).path("size").asLong());
assertEquals(1,calls.get());assertArrayEquals(bytes,received.get());
}
@Test public void supplierSizeLimitRemainsVisibleAndIsNotRetried(){
status.set(413);var error=assertThrows(ScannerException.class,()->upload("Frame.p3",new byte[]{1}));
assertEquals(413,error.remoteStatus);assertEquals("fixture_error",error.scannerCode);
assertTrue(error.getMessage().contains("扫描服务自身的上传上限"));assertEquals(1,calls.get());
assertTrue(error.getMessage().contains("扫描服务自身"));assertEquals(1,calls.get());
}
@Test public void wrongSuccessStatusMalformedReceiptAndRemoteFailureAreNotRetried() {
status.set(202);assertEquals("invalid_response",assertThrows(ScannerException.class,()->upload("Frame.p3",new byte[]{1})).scannerCode);

View File

@ -28,9 +28,9 @@ public class ScannerLocalFrameworkControllerTest {
TenantContextHolder.setTenantId(2L);assertEquals("invalid_tenant",assertThrows(ScannerException.class,()->controller.upload(file("frame.p3",new byte[]{1}))).scannerCode);
}
@Test public void exactLimitAllowedButOversizeAndFalseLengthAreRejected(){
byte[] maximum=new byte[ScannerFrameworkService.MAX_BYTES];maximum[0]=1;
byte[] maximum=new byte[100*1024*1024];maximum[0]=1;
assertEquals(200,controller.upload(file("frame.asc",maximum)).get("code"));
assertThrows(ScannerException.class,()->controller.upload(file("frame.asc",new byte[maximum.length+1])));
assertEquals(200,controller.upload(file("frame.asc",new byte[maximum.length+1])).get("code"));
var truncated=new MockMultipartFile("file","frame.txt","text/plain",new byte[]{1}){@Override public long getSize(){return 2;}};
assertThrows(ScannerException.class,()->controller.upload(truncated));
}

View File

@ -49,9 +49,11 @@ public class FileController {
schema = @Schema(type = "string", format = "binary"))
public CommonResult<String> uploadFile(@Valid FileUploadReqVO uploadReqVO) throws Exception {
MultipartFile file = uploadReqVO.getFile();
try(var memory=cn.iocoder.yudao.framework.common.util.io.UploadMemoryGuard.reserve(file.getSize())){
byte[] content = IoUtil.readBytes(file.getInputStream());
return success(fileService.createFile(content, file.getOriginalFilename(),
uploadReqVO.getDirectory(), file.getContentType()));
}
}
@GetMapping("/presigned-url")

View File

@ -36,7 +36,7 @@ public class LabScannerViewController {
var source=views.asset(executionId,fileId);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).cacheControl(CacheControl.noStore()).body(output->{
try(source){byte[] buffer=new byte[16384];long total=0;int count;
while((count=source.stream().read(buffer))!=-1){total+=count;if(total>100L*1024*1024)throw new java.io.IOException("Model exceeds online viewing size limit");output.write(buffer,0,count);}
while((count=source.stream().read(buffer))!=-1){total=Math.addExact(total,count);output.write(buffer,0,count);}
}
});
}

View File

@ -29,10 +29,10 @@ public class LabBizProperties {
@Data
public static class Artifact {
/** Unified browser upload limit; independent of existing large scanner archives. */
private long uploadMaxSizeBytes = 100L * 1024 * 1024;
private long uploadMaxSizeBytes = 0;
/** 受控 NAS 根路径,空则仅允许对象存储登记 */
private String nasRoot = "";
private long maxSizeBytes = 10L * 1024 * 1024 * 1024;
private long maxSizeBytes = 0;
}
@Data

View File

@ -100,7 +100,7 @@ public class LabArtifactServiceImpl implements LabArtifactService {
throw exception(FILE_ALREADY_REGISTERED);
}
}
if (reqVO.getSizeBytes() != null && reqVO.getSizeBytes() > bizProperties.getArtifact().getMaxSizeBytes()) {
if (bizProperties.getArtifact().getMaxSizeBytes()>0 && reqVO.getSizeBytes() != null && reqVO.getSizeBytes() > bizProperties.getArtifact().getMaxSizeBytes()) {
throw exception(ARTIFACT_FILE_TOO_LARGE);
}
LabArtifactFileDO row = LabArtifactFileDO.builder()
@ -178,11 +178,12 @@ public class LabArtifactServiceImpl implements LabArtifactService {
if (file == null || file.isEmpty()) {
throw exception(ARTIFACT_FILE_NOT_FOUND);
}
if (file.getSize() > bizProperties.getArtifact().getMaxSizeBytes()) {
if (bizProperties.getArtifact().getMaxSizeBytes()>0 && file.getSize() > bizProperties.getArtifact().getMaxSizeBytes()) {
throw exception(ARTIFACT_FILE_TOO_LARGE);
}
validateType(artifactType);
LabExecutionDO execution = executionService.validateExists(executionId);
try(var memory=cn.iocoder.yudao.framework.common.util.io.UploadMemoryGuard.reserve(file.getSize())){
byte[] bytes;
try {
bytes = file.getBytes();
@ -223,6 +224,7 @@ public class LabArtifactServiceImpl implements LabArtifactService {
executionService.reevaluateDelivery(row.getExecutionId());
}
return row.getId();
}
}
@Override

View File

@ -14,7 +14,7 @@ import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionU
/** Controlled archive; no arbitrary URLs, paths, or device requests. */
@Service @RequiredArgsConstructor
public class DimensionFiles {
public static final long DEFAULT_LIMIT=100L*1024*1024;
public static final long DEFAULT_LIMIT=0;
private final LabBizProperties settings;
public record Stored(String path,long size,String sha256) {}
public static void validateName(String role,String name) {
@ -41,8 +41,9 @@ public class DimensionFiles {
Path target=directory.resolve(UUID.randomUUID()+"."+name.substring(name.lastIndexOf('.')+1).toLowerCase(Locale.ROOT));
boolean success=false;long size=0;
try {
if(Files.getFileStore(directory).getUsableSpace()<512L*1024*1024)throw invalidParamException("磁盘可用空间不足,需保留512MiB运行空间");
try(InputStream in=source;OutputStream out=Files.newOutputStream(target,StandardOpenOption.CREATE_NEW)) {
byte[] buffer=new byte[64*1024];int n;while((n=in.read(buffer))!=-1){size+=n;if(size>maximum)throw invalidParamException("文件超过允许大小("+(maximum/1024/1024)+"MB)");out.write(buffer,0,n);}
byte[] buffer=new byte[64*1024];int n;while((n=in.read(buffer))!=-1){size=Math.addExact(size,n);if(maximum>0&&size>maximum)throw invalidParamException("文件超过允许大小("+(maximum/1024/1024)+"MB)");if((size%(8L*1024*1024))<n&&Files.getFileStore(directory).getUsableSpace()<512L*1024*1024)throw invalidParamException("磁盘可用空间不足,需保留512MiB运行空间");out.write(buffer,0,n);}
}
if(size==0)throw invalidParamException("不能上传空文件");
try(InputStream in=Files.newInputStream(target)){

View File

@ -215,7 +215,7 @@ public class DimensionService {
public Long upload(long taskId,long unitId,String role,MultipartFile upload) throws IOException {
task(taskId,true);unit(taskId,unitId);if(!Set.of("MODEL","DRAWING","SCAN_CLOUD").contains(role))throw invalidParamException("此入口仅接收数模、图纸、PLY,最终成果请成套登记");
if(unitId==0&&role.equals("SCAN_CLOUD"))throw invalidParamException("PLY必须关联具体样件");
if(upload.getSize()>files.uploadLimit())throw invalidParamException("上传文件超过允许大小");
if(files.uploadLimit()>0&&upload.getSize()>files.uploadLimit())throw invalidParamException("上传文件超过允许大小");
long id=save(taskId,unitId,role,upload.getOriginalFilename(),upload.getInputStream(),files.uploadLimit(),"LOCAL_UPLOAD",null,null);event(taskId,unitId,"FILE_VERSION_UPLOADED",map("fileId",id,"role",role));return id;
}
@Transactional(rollbackFor=Exception.class)

View File

@ -25,10 +25,11 @@ public class LabScannerAssetArchive {
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;
if(Files.getFileStore(target.getParent()).getUsableSpace()<512L*1024*1024)throw new IOException("磁盘可用空间不足,需保留512MiB运行空间");
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);}
while((n=source.stream().read(buffer))!=-1){bytes=Math.addExact(bytes,n);if((bytes%(8L*1024*1024))<n&&Files.getFileStore(target.getParent()).getUsableSpace()<512L*1024*1024)throw new IOException("磁盘余量不足512MiB");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()));

View File

@ -88,12 +88,11 @@ public class LabFixtureFrameworkService {
for(var s:sources){
ScannerFrameworkReferences.validateOrigin(s,settings);
try(var f=scanner.frameworkFile(s.fileId(),10000)){
byte[] bytes=f.stream().readNBytes(ScannerFrameworkService.MAX_BYTES+1);
String name=s.name();if(name.isBlank()){
var headers=f.headers().entrySet().stream().filter(e->e.getKey().equalsIgnoreCase("content-disposition")).findFirst().orElseThrow(()->invalidParamException("框架导出文件缺少文件名"));
name=org.springframework.http.ContentDisposition.parse(headers.getValue().get(0)).getFilename();
}
saved.add(store.save(name,bytes));
saved.add(store.save(name,f.stream(),s.bytes()==null?-1:s.bytes()));
}
}
finish(id,"READY",saved.toJSONString(),null);

View File

@ -43,8 +43,8 @@ class LabFixtureFrameworkServiceTest {
var end=new com.cmvr.test.model.domain.TeNodeInst();end.setAction("END");end.setStatus("SUCCESS");end.setParamsOut("{\"frameworkUrls\":[\"/api/v1/files/00000000000000000000000000000000\"]}");when(instances.detail("inst")).thenReturn(List.of(end));
var scanner=(ScannerHttpClient)org.springframework.test.util.ReflectionTestUtils.getField(service,"scanner");
when(scanner.frameworkFile(anyString(),anyLong())).thenReturn(new ScannerHttpClient.Binary(new java.io.ByteArrayInputStream(new byte[]{1,2}),Map.of("content-disposition",List.of("attachment; filename=fixture.p3"))));
when(store.save(eq("fixture.p3"),any())).thenReturn(com.alibaba.fastjson2.JSONObject.of("downloadUrl","/admin-api/cmvr/scanner/files/11111111111111111111111111111111","name","fixture.p3"));
service.synchronize(1L);assertEquals("new",service.current(1L).get("id"));verify(store).save(eq("fixture.p3"),any());assertEquals(1,jdbc.queryForObject("SELECT COUNT(*) FROM lab_fixture_framework WHERE id='old' AND status='READY'",Integer.class));
when(store.save(eq("fixture.p3"),any(java.io.InputStream.class),eq(-1L))).thenReturn(com.alibaba.fastjson2.JSONObject.of("downloadUrl","/admin-api/cmvr/scanner/files/11111111111111111111111111111111","name","fixture.p3"));
service.synchronize(1L);assertEquals("new",service.current(1L).get("id"));verify(store).save(eq("fixture.p3"),any(java.io.InputStream.class),eq(-1L));assertEquals(1,jdbc.queryForObject("SELECT COUNT(*) FROM lab_fixture_framework WHERE id='old' AND status='READY'",Integer.class));
}
@Test void missingFixtureAndMissingDataFailBeforeAnyHardware(){assertThrows(RuntimeException.class,()->service.parameters(GRAPH,null,Map.of()));assertThrows(RuntimeException.class,()->service.parameters(GRAPH,1L,Map.of()));verifyNoInteractions(runtime,controls,store);}
@Test void currentVersionIsInjectedAndUrlsCannotBeSpoofed(){ready("v1");var result=service.parameters(GRAPH,1L,Map.of("fixtureFrameworkUrls","evil"));assertEquals("v1",result.get("fixtureFrameworkVersion"));assertEquals("[]",result.get("fixtureFrameworkUrls"));verify(store).verify("[]");}

View File

@ -47,7 +47,7 @@ lab:
require-material: false
artifact:
nas-root: E:/workspace/hybrid/am-freescan/.local/artifacts
max-size-bytes: 10737418240
max-size-bytes: 0 # Unlimited file policy; runtime resource guards remain enabled.
yudao:
captcha:
enable: false

View File

@ -47,7 +47,7 @@ lab:
require-material: false
artifact:
nas-root: E:/workspace/hybrid/am-freescan/.local/artifacts
max-size-bytes: 10737418240
max-size-bytes: 0 # Unlimited file policy; runtime resource guards remain enabled.
yudao:
captcha:
enable: false

View File

@ -59,7 +59,7 @@ lab:
require-material: false
artifact:
nas-root: ${LAB_ARTIFACT_NAS_ROOT:./artifacts}
max-size-bytes: 10737418240
max-size-bytes: 0 # Unlimited file policy; runtime resource guards remain enabled.
yudao:
captcha:

View File

@ -0,0 +1,103 @@
# Windows 11 independent instance. Retain this profile in Git; never import dev/local credentials.
# Start with --spring.profiles.active=standalone. Middleware is restricted to this host.
server:
port: 48090
address: 0.0.0.0
spring:
servlet:
multipart:
location: ${AM_FREESCAN_HOME}/tmp
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration
- com.binarywang.spring.starter.wxjava.mp.config.WxMpAutoConfiguration
- com.binarywang.spring.starter.wxjava.miniapp.config.WxMaAutoConfiguration
datasource:
dynamic:
primary: master
strict: true
datasource:
master:
url: jdbc:mysql://127.0.0.1:3306/am-freescan?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
username: ${AM_FREESCAN_DB_USER:freescan}
password: ${AM_FREESCAN_DB_PASSWORD}
data:
redis:
host: 127.0.0.1
port: 6379
database: 15
password: ${AM_FREESCAN_REDIS_PASSWORD}
boot:
admin:
client:
enabled: false
cache:
redis:
key-prefix: 'am-freescan:standalone:'
cmvr:
scanner:
# Device services are NOT middleware. Supply actual LAN addresses only after commissioning.
host: ${AM_FREESCAN_SCANNER_HOST:}
port: ${AM_FREESCAN_SCANNER_PORT:18888}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
connect-timeout-ms: 5000
request-timeout-ms: 120000
operation-timeout-ms: 120000
rotary-base:
host: ${AM_FREESCAN_ROTARY_BASE_HOST:}
port: ${AM_FREESCAN_ROTARY_BASE_PORT:50052}
rpc-timeout-ms: 120000
resource:
robot-state:
external-robot-ids: []
quic:
enabled: ${CMVR_QUIC_ENABLED:false}
bind-host: 0.0.0.0
port: 4433
alpn: ${CMVR_QUIC_ALPN:cmvr-quic-edge/1}
allowed-node-ids: ${CMVR_QUIC_ALLOWED_NODE_IDS:}
tls:
certificate: ${CMVR_QUIC_TLS_CERTIFICATE:}
private-key: ${CMVR_QUIC_TLS_PRIVATE_KEY:}
client-ca: ${CMVR_QUIC_TLS_CLIENT_CA:}
require-client-certificate: ${CMVR_QUIC_TLS_REQUIRE_CLIENT_CERTIFICATE:false}
lab:
integration:
mock-enabled: false
mock-auto-callback: false
callback-base-url: http://127.0.0.1:48090/open-api
public-base-url: ${AM_FREESCAN_PUBLIC_BASE_URL:http://127.0.0.1:5180}
resource:
require-fixture: false
require-material: false
artifact:
nas-root: ${AM_FREESCAN_HOME}/artifacts
max-size-bytes: 0 # Unlimited file policy; runtime resource guards remain enabled.
yudao:
captcha:
enable: false
security:
mock-enable: false
demo: false
api-encrypt:
enable: false
web:
admin-ui:
url: ${AM_FREESCAN_PUBLIC_BASE_URL:http://127.0.0.1:5180}
justauth:
enabled: false
management:
endpoints:
web:
exposure:
include: health,info
logging:
file:
name: ${AM_FREESCAN_HOME}/logs/backend.log
level:
cn.iocoder.yudao: INFO

View File

@ -33,8 +33,8 @@ spring:
allow-circular-references: true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 210MB # Paired delivery: one STL and one PDF, each up to 100MB.
max-file-size: -1
max-request-size: -1
jackson:
time-zone: Asia/Shanghai
serialization:

14
am-web/.env.standalone Normal file
View File

@ -0,0 +1,14 @@
NODE_ENV=production
VITE_DEV=false
VITE_BASE_URL=
VITE_API_URL=/admin-api
VITE_UPLOAD_TYPE=server
VITE_BASE_PATH=/
VITE_OUT_DIR=dist-standalone
VITE_SOURCEMAP=false
VITE_DROP_DEBUGGER=true
VITE_DROP_CONSOLE=true
VITE_COMPRESS=none
VITE_APP_CAPTCHA_ENABLE=false
VITE_APP_API_ENCRYPT_ENABLE=false
VITE_APP_DEFAULT_LOGIN_PASSWORD=

View File

@ -1,7 +1,7 @@
server {
listen 80;
server_name _;
client_max_body_size 32m;
client_max_body_size 0;
location /admin-api/ {
proxy_pass ${BACKEND_UPSTREAM}/admin-api/;

View File

@ -14,6 +14,7 @@
"build:test": "node --max_old_space_size=8192 ./node_modules/vite/bin/vite.js build --mode test",
"build:stage": "node --max_old_space_size=8192 ./node_modules/vite/bin/vite.js build --mode stage",
"build:prod": "node --max_old_space_size=8192 ./node_modules/vite/bin/vite.js build --mode prod",
"build:standalone": "node --max_old_space_size=8192 ./node_modules/vite/bin/vite.js build --mode standalone",
"serve:dev": "vite preview --mode dev",
"serve:prod": "vite preview --mode prod",
"preview": "pnpm build:local && vite preview",

View File

@ -59,7 +59,7 @@ const props = defineProps({
/* 上传文件大小限制(MB) */
fileSize: {
type: Number,
default: 5,
default: 0,
},
/* 类型(base64格式、url格式) */
type: {

View File

@ -63,7 +63,7 @@ const props = defineProps({
// 大小限制(MB)
fileSize: {
type: Number,
default: 5
default: 0
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {

View File

@ -2,7 +2,7 @@
<div class="local-framework-upload">
<input ref="picker" type="file" multiple accept=".p3,.txt,.asc" hidden :disabled="disabled || uploading" @change="selectFiles" />
<el-button :loading="uploading" :disabled="disabled || uploading || modelValue.length >= 8" @click="picker?.click()">{{ uploading ? '正在上传文件' : '选择本地文件' }}</el-button>
<div class="upload-note">P3 / TXT / ASC,最多8个,单个不超过100MiB。文件保存到平台,运行时自动导入;上传不会启动扫描仪。</div>
<div class="upload-note">P3 / TXT / ASC,最多8个,不设单文件大小上限。文件保存到平台,运行时自动导入;上传不会启动扫描仪。</div>
<ul v-if="modelValue.length" class="uploaded-files">
<li v-for="file in modelValue" :key="file.fileId">
<span class="file-name" :title="file.name">{{ file.name }}</span><span class="file-size">{{ sizeText(file.bytes) }}</span>

View File

@ -71,7 +71,7 @@ const props = defineProps({
// 大小限制(MB)
fileSize: {
type: Number,
default: 5
default: 0
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {

View File

@ -8,7 +8,7 @@ test('local receipts restore from workflow JSON and resolve through existing ref
assert.deepEqual(files, [receipt()]); assert.deepEqual(frameworkReferences(files), [receipt().downloadUrl])
})
test('invalid or remote receipts, empty and oversized files cannot be saved', () => {
for (const patch of [{bytes: 0}, {bytes: 100 * 1024 * 1024 + 1}, {downloadUrl: '/api/v1/files/' + 'a'.repeat(32)}, {fileId: '../abc'}, {sha256: ''}, {name: 'bad.stl'}, {name: '../bad.p3'}]) assert.throws(() => localFrameworkFiles([{...receipt(), ...patch}]))
for (const patch of [{bytes: 0}, {bytes: Number.MAX_SAFE_INTEGER+1}, {downloadUrl: '/api/v1/files/' + 'a'.repeat(32)}, {fileId: '../abc'}, {sha256: ''}, {name: 'bad.stl'}, {name: '../bad.p3'}]) assert.throws(() => localFrameworkFiles([{...receipt(), ...patch}]))
assert.throws(() => localFrameworkFiles([])); assert.throws(() => localFrameworkFiles('not JSON'))
})
test('100MiB及超过旧16MiB限制的框架回执可以保存', () => {

View File

@ -1,4 +1,4 @@
export const FRAMEWORK_MAX_BYTES = 100 * 1024 * 1024
export const FRAMEWORK_MAX_BYTES = Number.POSITIVE_INFINITY
export function validateFrameworkFiles(files, existingCount = 0) {
if (!files.length || files.length + existingCount > 8) throw new Error('一次导入最多8个框架文件')
@ -6,8 +6,8 @@ export function validateFrameworkFiles(files, existingCount = 0) {
if (!/\.(p3|txt|asc)$/i.test(file.name) || /[<>:"/\\|?*\x00-\x1f\x7f]/.test(file.name)
|| file.name.length > 128 || new TextEncoder().encode(file.name).length > 240)
throw new Error('框架文件仅支持.p3、.txt、.asc,文件名不可含目录或超过240字节 / 128个UTF-16单元')
if (!Number.isInteger(file.size) || file.size <= 0 || file.size > FRAMEWORK_MAX_BYTES)
throw new Error('框架文件不能为空,且单个文件不能超过100MiB')
if (!Number.isSafeInteger(file.size) || file.size <= 0)
throw new Error('框架文件不能为空,且实际长度必须有效')
}
}

View File

@ -6,8 +6,8 @@ import { createWorkcellNodeGroups } from './scanMotorNodes.mjs'
const file = (name = '框架+ A.p3', size = 10) => ({ name, size })
test('框架文件按UTF-8字节、UTF-16单元、扩展名和100MiB验证', () => {
assert.equal(FRAMEWORK_MAX_BYTES, 100 * 1024 * 1024)
validateFrameworkFiles([file(), file('one.ASC'), file('two.TXT', FRAMEWORK_MAX_BYTES)])
assert.equal(FRAMEWORK_MAX_BYTES, Number.POSITIVE_INFINITY)
validateFrameworkFiles([file(), file('one.ASC'), file('two.TXT', 1024 * 1024 * 1024)])
validateFrameworkFiles([file('a'.repeat(125)+'.p3')])
for (const item of [file('../frame.p3'), file('bad.stl'), file('bad.p3\0'), file('a'.repeat(126)+'.p3'), file('框'.repeat(80)+'.p3'), file('empty.p3',0), file('large.p3',FRAMEWORK_MAX_BYTES+1)])
assert.throws(() => validateFrameworkFiles([item]))

View File

@ -23,7 +23,7 @@
</el-form-item>
<el-form-item v-else-if="sourceMode === 'input'" label="框架下载URL" required>
<el-input v-model="source.input" type="textarea" :rows="4" :maxlength="131072" placeholder="每行一个扫描服务的文件下载URL,如 /api/v1/files/…" />
<div class="note">支持 P3 / TXT / ASC,1–8个文件,单个最大100MiB;URL必须来自当前扫描服务。</div>
<div class="note">支持 P3 / TXT / ASC,1–8个文件,不设单文件大小上限;URL必须来自当前扫描服务。</div>
</el-form-item>
<el-alert title="流程顺序:导出P3 → 创建用于扫描的新工程 → 选择 trak / mesh / scanner → 导入框架 → 开始采集。不会自动切换工程。" type="info" :closable="false" />
<el-form-item label="等待超时(毫秒)" required><el-input-number v-model="timeout.input" :min="1" :max="3600000" :precision="0" /></el-form-item>

View File

@ -25,7 +25,7 @@
选取文件
</el-button>
<template v-if="isShowTip" #tip>
<div style="font-size: 8px">
<div v-if="fileSize > 0" style="font-size: 8px">
大小不超过 <b style="color: var(--app-danger-text)">{{ fileSize }}MB</b>
</div>
<div v-if="fileType.length" style="font-size: 8px">
@ -81,7 +81,7 @@ const emit = defineEmits(['update:modelValue', 'update:fileSize'])
const props = defineProps({
modelValue: propTypes.oneOfType<string | string[]>([String, Array<String>]).isRequired,
fileType: propTypes.array.def(['doc', 'xls', 'ppt', 'txt', 'pdf']), // 文件类型,空数组表示不限制格式
fileSize: propTypes.number.def(100), // Unified default, explicit caller limits remain supported.
fileSize: propTypes.number.def(0), // Zero means no fixed file size limit.
limit: propTypes.number.def(5), // 数量限制
autoUpload: propTypes.bool.def(true), // 自动上传
drag: propTypes.bool.def(false), // 拖拽上传
@ -122,7 +122,7 @@ const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
if (file.type.indexOf(type) > -1) return true
return !!(fileExtension && fileExtension.indexOf(type) > -1)
})
const isLimit = file.size <= props.fileSize * 1024 * 1024
const isLimit = props.fileSize <= 0 || file.size <= props.fileSize * 1024 * 1024
if (!isAllowedType) {
message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
removeRejectedFile(file)

View File

@ -73,7 +73,7 @@ const props = defineProps({
modelValue: propTypes.string.def(''),
drag: propTypes.bool.def(true), // 是否支持拖拽上传 ==> 非必传(默认为 true)
disabled: propTypes.bool.def(false), // 是否禁用上传组件 ==> 非必传(默认为 false)
fileSize: propTypes.number.def(5), // 图片大小限制 ==> 非必传(默认为 5M)
fileSize: propTypes.number.def(0), // 默认不设固定文件大小上限
fileType: propTypes.array.def(['image/jpeg', 'image/png', 'image/gif']), // 图片类型限制 ==> 非必传(默认为 ["image/jpeg", "image/png", "image/gif"])
height: propTypes.string.def('150px'), // 组件高度 ==> 非必传(默认为 150px)
width: propTypes.string.def('150px'), // 组件宽度 ==> 非必传(默认为 150px)
@ -115,7 +115,7 @@ const editImg = () => {
}
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
const imgSize = rawFile.size / 1024 / 1024 < props.fileSize
const imgSize = props.fileSize <= 0 || rawFile.size / 1024 / 1024 < props.fileSize
const imgType = props.fileType
if (!imgType.includes(rawFile.type as FileTypes))
message.notifyWarning('上传图片不符合所需的格式!')

View File

@ -77,7 +77,7 @@ const props = defineProps({
drag: propTypes.bool.def(true), // 是否支持拖拽上传 ==> 非必传(默认为 true)
disabled: propTypes.bool.def(false), // 是否禁用上传组件 ==> 非必传(默认为 false)
limit: propTypes.number.def(5), // 最大图片上传数 ==> 非必传(默认为 5张)
fileSize: propTypes.number.def(5), // 图片大小限制 ==> 非必传(默认为 5M)
fileSize: propTypes.number.def(0), // 默认不设固定文件大小上限
fileType: propTypes.array.def(['image/jpeg', 'image/png', 'image/gif']), // 图片类型限制 ==> 非必传(默认为 ["image/jpeg", "image/png", "image/gif"])
height: propTypes.string.def('150px'), // 组件高度 ==> 非必传(默认为 150px)
width: propTypes.string.def('150px'), // 组件宽度 ==> 非必传(默认为 150px)
@ -101,7 +101,7 @@ const uploadList = ref<UploadUserFile[]>([])
* @param rawFile 上传的文件
* */
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
const imgSize = rawFile.size / 1024 / 1024 < props.fileSize
const imgSize = props.fileSize <= 0 || rawFile.size / 1024 / 1024 < props.fileSize
const imgType = props.fileType
const isValidType = imgType.includes(rawFile.type as FileTypes)
const isValidSize = imgSize

View File

@ -45,12 +45,12 @@ export const acceptedFormats = {
RESULT_MESH: '.stl',
RESULT_REPORT: '.pdf'
}
export function validateUpload(file, role, limit = 100 * 1024 * 1024) {
export function validateUpload(file, role, limit = 0) {
const ext = '.' + (file?.name || '').split('.').pop().toLowerCase()
if (!acceptedFormats[role]?.split(',').includes(ext))
return `请选择${acceptedFormats[role] || '支持的'}文件`
if (!file.size) return '不能上传空文件'
if (file.size > limit) return `单文件不能超过${Math.floor(limit / 1024 / 1024)}MB`
if (limit > 0 && file.size > limit) return `单文件不能超过${Math.floor(limit / 1024 / 1024)}MB`
return ''
}
export const eventLabels = {

View File

@ -25,10 +25,10 @@ test('资料用途区分数模图纸点云以及两类STL', () => {
})
test('上传边界接受100MB,拒绝空文件、超限和错误类型', () => {
const max = 100 * 1024 * 1024
assert.equal(validateUpload({ name: 'drawing.pdf', size: max }, 'DRAWING'), '')
assert.equal(validateUpload({ name: 'drawing.pdf', size: max + 1 }, 'DRAWING'), '')
assert.ok(validateUpload({ name: 'drawing.pdf', size: max + 1 }, 'DRAWING',max))
for (const f of [
{ name: 'drawing.pdf', size: 0 },
{ name: 'drawing.pdf', size: max + 1 },
{ name: 'drawing.exe', size: 1 }
])
assert.ok(validateUpload(f, 'DRAWING'))

View File

@ -110,10 +110,7 @@
@click="saveSelection"
>保存比对资料版本</el-button
><span class="secondary"
>单文件上限
{{
Math.floor(data.uploadMaxBytes / 1024 / 1024)
}}MB;新上传生成新版本,历史文件保留。</span
>不设单文件大小上限;新上传生成新版本,历史文件保留。</span
></div
>
<h3>本样件的扫描导出文件</h3

View File

@ -215,7 +215,7 @@
:before-upload="beforeAttachment"
><el-button :loading="uploading">上传模型、图纸或其他资料</el-button
><template #tip
><div class="hint">单文件不超过 100MB;资料关联本次任务。分类及版本选用请在检测任务工作台管理。</div></template
><div class="hint">不设单文件大小上限;资料关联本次任务。分类及版本选用请在检测任务工作台管理。</div></template
></el-upload
>
<el-table :data="detail.attachments || []" size="small"
@ -1246,8 +1246,8 @@ const submitStart = () =>
message.success('本件已提交执行')
})
const beforeAttachment = (file: File) => {
if (file.size > 100 * 1024 * 1024) {
message.warning('单文件不能超过 100MB')
if (!file.size) {
message.warning('文件不能为空')
return false
}
return true

View File

@ -1,4 +1,4 @@
export const MAX_SCANNER_MODEL_BYTES = 100 * 1024 * 1024
export const MAX_SCANNER_MODEL_BYTES = Number.POSITIVE_INFINITY
export async function readScannerBinary(response, maximum = MAX_SCANNER_MODEL_BYTES) {
const error = () => new Error('文件超过在线查看限制,请使用原始成果下载')
@ -13,6 +13,10 @@ export async function readScannerBinary(response, maximum = MAX_SCANNER_MODEL_BY
const { value, done } = await reader.read()
if (done) break
size += value.byteLength
const memory = globalThis.performance?.memory
if (memory?.jsHeapSizeLimit && memory.usedJSHeapSize + size * 3 > memory.jsHeapSizeLimit * 0.8) {
await reader.cancel(); throw new Error('当前浏览器可用内存不足,请下载原始成果或使用内存更大的电脑查看')
}
if (size > maximum) { await reader.cancel(); throw error() }
chunks.push(value)
}

View File

@ -1,7 +1,7 @@
import * as THREE from 'three'
import { parseScannerModel, disposeScannerModel } from './scannerModel.mjs'
export const MAX_MODEL_BYTES = 100 * 1024 * 1024
export const MAX_MODEL_BYTES = Number.POSITIVE_INFINITY
export const MAX_DISPLAY_POINTS = 500000
export const MAX_MESH_BYTES = 256 * 1024 * 1024
export const MAX_MESH_TRIANGLES = 2500000
@ -9,7 +9,6 @@ const MAX_OBJECTS = 256
/** Runs only in a worker. Transfer typed arrays instead of cloning millions of numbers. */
export function prepareScannerModel(buffer, name, pointLimit = MAX_DISPLAY_POINTS) {
if (buffer.byteLength > MAX_MODEL_BYTES) throw new Error('文件超过在线查看的100MiB限制,请下载原始成果查看')
if (/\.ply$/i.test(name)) {
const header = new TextDecoder().decode(new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 65536))).split('end_header')[0]
const count = Number(/element\s+vertex\s+(\d+)/i.exec(header)?.[1] || 0)

277
deploy/windows11/README.md Normal file
View File

@ -0,0 +1,277 @@
# Windows 11 专业版独立部署与历史数据迁移手册
适用:招商车研三维尺寸快检平台,Windows 11 专业版 x64。目标是迁移现有测试用例、发布版本、夹具、框架点、任务、执行日志及平台已有文件,数据库和Redis改为新电脑本机服务。
## 1. 给目标电脑 AI 的完整任务指令
把下面这段和本手册一起交给目标电脑 AI:
> 在本机部署本仓库的 Windows 11 独立实例,按 deploy/windows11/README.md 执行。先读取仓库 AGENTS.md。本任务使用 application-standalone.yaml、am-web/.env.standalone 和 deploy/windows11/compose.yaml,必须保留并提交这些模板,不能覆盖 dev/local/prod。先检查系统和端口,再安装依赖、初始化私有配置、启动本机中间件、导入经校验的源环境迁移包、构建并启动前后端、完成验收和备份。MySQL只连接127.0.0.1:3306/am-freescan,Redis只连接127.0.0.1:6379/15,不得使用源服务器数据库作为目标运行库。默认迁移历史数据,禁止先运行Bootstrap填充目标库。缺少迁移包就完成可独立进行的准备后等待源电脑交付,不能用空库冒充迁移完成。禁止删除非空数据库、删除Docker数据卷、覆盖已有数据目录、关闭防火墙或结束不属于本实例的进程。实际密码、SQL备份、框架点文件和私钥不得提交Git或输出到聊天。现场运动/采集停止并经用户确认后才能切换设备连接;基础验收不执行使能、回零、移动、采集或真实工作流。把完成项、验证证据和仍缺少的现场信息分别列出,不能把缺少硬件配置称为全部完成。
## 2. 部署结构与地址
| 服务 | 方式 | 本机地址 | 持久数据 |
|---|---|---|---|
| 后端,Java17,包含QUIC | Windows后台进程 | HTTP48090;QUIC UDP4433 | 固定数据目录及私有配置 |
| MySQL8.4 | Docker Linux容器 | 127.0.0.1:3306 | 项目专属mysql-data卷 |
| Redis7.4 | Docker Linux容器 | 127.0.0.1:6379,库15 | 项目专属redis-data卷,AOF |
| Nginx与打包后的前端 | Docker Linux容器 | http://127.0.0.1:5180 | Windows数据目录/web |
| 扫描归档、框架点、上传文件 | Windows磁盘 | 不依赖扫描服务进程 | 数据目录/artifacts及uploads |
后端通过127.0.0.1访问所有本机中间件。Nginx位于Linux容器内,它访问Windows后端必须使用`host.docker.internal:48090`;容器里的127.0.0.1是容器自己,不能把这一项机械改成127.0.0.1。
扫描服务18888、机械臂/AGV/旋转底座gRPC是现场设备服务,不是本机中间件。使用现场真实地址,不伪造127.0.0.1,不从旧模板猜测密钥。QUIC已经集成在同一个Java后端进程,不再启动第二套4433服务。
当前归档使用本地文件目录;不要求安装MinIO。迁移脚本会验证源文件存储为当前的单个LOCAL配置,检测到S3/MinIO会停止并要求另外迁移对象,不能只改地址就宣称文件已迁移。第三方尺寸比对尚未接通,不把演示结果当作真实STL/PDF交付。
## 3. 需要准备的东西
软件:Git、PowerShell7.2+、JDK17、Maven3.9.x、Node.js24 LTS、pnpm11.25.0、Python3.12、WSL2和Docker Desktop(Linux容器)。pnpm版本与本次验证环境一致,安装兼容性见[pnpm官方说明](https://pnpm.io/installation)。构建在Windows完成,保证QUIC的本地库匹配Windows;不要拿Linux构建的JAR直接当Windows包。
建议16GB以上内存,32GB更宽裕;SSD。迁移前统计源数据库和文件大小,目标可用空间应覆盖迁移包、恢复后数据、构建及备份,通常至少实际业务数据的3倍。Docker镜像和WSL虚拟磁盘也占空间,事先在Docker设置中选定数据盘。
AI先记录这些检查结果:
```powershell
Get-ComputerInfo | Select-Object WindowsProductName,OsArchitecture
$PSVersionTable.PSVersion
wsl --version
docker version
docker compose version
java -version
mvn -version
node --version
pnpm --version
python --version
Get-NetTCPConnection -State Listen -LocalPort 3306,6379,48090,5180 -ErrorAction SilentlyContinue
Get-NetUDPEndpoint -LocalPort 4433 -ErrorAction SilentlyContinue
Get-PSDrive -PSProvider FileSystem
```
端口被占用先查进程身份,不随便结束MySQL、Redis、IDEA或别的项目。数据盘没有D盘时,后面的`-DataRoot`可以改成C盘绝对路径,必须是新目录。
### 安装顺序
1. BIOS/UEFI开启虚拟化。管理员PowerShell执行`wsl --install --no-distribution`,系统要求重启时先告知用户;不要强制重启现场电脑。
2. 按Docker官方说明安装Docker Desktop,开启WSL2后端和Linux容器;启动后确认`docker info`成功,`docker info --format '{{.OSType}}'`为`linux`。
3. 安装其余开发工具,设置`JAVA_HOME`指向JDK17,PATH中Maven3.9排在旧版之前。可以先用`winget search`确认包,再安装Git.Git、Microsoft.PowerShell、Microsoft.OpenJDK.17、OpenJS.NodeJS.LTS、Python.Python.3.12。Maven从Apache官网下载3.9.x二进制包并核验SHA512,不假设机器原来的Maven版本正确。
4. `npm install --global pnpm@11.25.0`,重新打开PowerShell7检查全部版本。
Git网络可达不代表Docker Hub、Maven仓库、npm或PyPI可达。联网失败时不要反复重试;按第12节准备离线资源。
## 4. 拉取代码,创建永久配置
```powershell
git clone http://192.168.28.10:18088/SmartBench/am-freescan.git D:\apps\am-freescan
cd D:\apps\am-freescan
git pull --ff-only origin main
git rev-parse HEAD
python -m pip install -r deploy/windows11/requirements.txt
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Init -DataRoot D:/am-freescan-data -PublicBaseUrl http://127.0.0.1:5180
```
需要局域网其他电脑访问时,`PublicBaseUrl`从第一次初始化就填写目标电脑实际局域网IP,例如`http://目标电脑IP:5180`。这不是中间件地址。以后变更域名还需同步文件存储配置中的domain和已有平台文件URL,不能只改前端。
Init生成并保留:
```text
代码仓库/.local/standalone/
runtime.json 本实例标识、中间件新密码、数据目录和对外入口
compose.env Docker所需私有变量
application-private.yaml 本实例现场设备与QUIC覆盖配置
initial-admin.txt 仅空库初始化时适用的初始账号说明
backend/yudao-server.jar 构建后的运行包
backend-process.json 本实例Java进程身份,防止误杀别的进程
deployed-commit.txt 构建来源提交
backend-sha256.txt 运行包校验值
D:/am-freescan-data/
artifacts/ 扫描文件、夹具框架点、成果、执行输出、AGV轨迹
uploads/ 平台通用上传文件
web/ 打包后的前端
backups/ 迁移SQL副本及后续备份
logs/
certs/
tmp/ 上传与流式传输的临时文件,避免挤满系统盘
```
模板留在Git,实际配置保存在Git忽略目录,Init重复运行不会重置密码或实例标识。不要复制源机器的`.local/runtime.json`覆盖目标配置,否则可能重新连回源数据库。不要丢失目标私有配置:密码不是容器每次启动时可以随意重新生成的。
## 5. 源电脑制作历史数据迁移包
本节在**当前源电脑**执行,目标电脑不能凭Git重建数据库和未入库的扫描文件。
1. 源电脑拉取包含本手册的最新提交,确认目标用例`8b0c888b013347c08df1a7167f721a83`的当前发布记录存在。
2. 安排切换窗口:现场停止采集和所有运动,结束/终止运行任务并确认资源释放。通过原启动方式停止源后端,确认48090不再监听;Redis和源MySQL不必停。
3. 安装官方MySQL8.4 Windows客户端工具,找到`mysqldump.exe`。可以解压官方ZIP,不需要在源电脑再安装一套MySQL服务。
4. 私有迁移目录限制为本用户和管理员可读,不开放Everyone匿名共享。执行:
```powershell
cd D:\project\project\cmvr\cmvr-robot\am-freescan
python -m pip install -r deploy/windows11/requirements.txt
python scripts/migrate_standalone.py export `
--mysqldump 'D:\tools\mysql\bin\mysqldump.exe' `
--source-runtime .local/runtime.json `
--artifacts .local/artifacts `
--output .local/migration-export/transfer-20261111 `
--confirm-source-stopped
python scripts/migrate_standalone.py verify --package .local/migration-export/transfer-20261111
```
`--output`必须是不存在的新目录。脚本只允许源库`192.168.28.10/am-freescan`,检查没有活动流程、资源占用或未确认扫描命令,使用单事务导出。不会写源库,也不会调用SDK。失败时保留诊断目录,不把未完成包作为成功交付。
包里包含:全库SQL、平台artifacts、通用uploads、逐文件SHA256和源表行数;另有原登录信息及设备私有配置的受限副本、被明确引用的QUIC证书/服务端私钥/CA证书。**整个包属于敏感业务数据,绝对不要提交Git、贴到聊天或上传公共网盘。** 用组织批准的受限文件共享/移动介质交付目标电脑。Git只传代码和模板。
导出不会把源扫描仪服务磁盘上“从未归档到平台”的文件变出来。历史`/api/v1/files/...`若已失效且平台无副本,仍需上位机原文件;把此类源数据缺失单独列出,不用其他夹具文件替代。边端保存的机械臂轨迹仍在原机械臂控制服务上,数据库保存的是关联与版本,不能凭名称伪造轨迹实体。
本次源库只读检查还发现:60条含磁盘路径的历史成果中,53条指向更早电脑的旧目录,当前电脑没有对应文件,另外7条可找到。迁移会保留这些历史记录,并将缺失项写入迁移包`manifest.json`的`missingReferences`,不会伪造文件或隐藏缺失。该数字会随源数据变化,以最终导出清单为准;要补齐缺失文件,需要找到原电脑或备份。已归档且真实存在的文件会逐个复制和校验。
## 6. 目标电脑启动中间件并恢复数据
```powershell
cd D:\apps\am-freescan
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Middleware
python scripts/migrate_standalone.py verify --package D:/transfer/transfer-20261111
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Restore `
-MigrationPath D:/transfer/transfer-20261111 -ConfirmStopped
```
**迁移当前业务时,不运行Bootstrap。** Restore只接受空的目标库和空的目标artifacts/uploads;不会DROP、TRUNCATE或覆盖已存在实例。SQL通过目标Docker MySQL导入,不往源库写数据。所有文件校验通过、表行数核对后,重写受控存储路径和平台文件域名,保留用例ID、冻结版本、夹具、框架点、历史任务、日志和现有菜单。缺失文件清单一并保留,不把“数据库记录已迁移”混同于“历史原文件全部找回”。
迁移后的账号与密码沿用源系统,Init随机生成的新管理员密码不适用。源运行配置有已确认的管理员登录密码时,私有交接文件会提供给目标验收使用;如果登录失败,向用户确认原系统有效账号,不猜密码,也不擅自重置所有用户密码。
Redis运行会话和锁不迁移;目标使用全新Redis,并清除迁移库中的旧OAuth访问/刷新令牌。设备连接状态重置为离线,等待现场真实上报,不用源数据库里的“在线”状态冒充目标已接入。
如果中途恢复失败,不自动清空数据库或删除数据卷。保留私有错误日志和失败现场,先修复问题;需要从头再来时,由用户确认另建一套空实例或处理这套失败实例。
仅在用户明确改为“全新空业务环境”时,才用:
```powershell
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Bootstrap
```
此入口独立校验127.0.0.1与本实例所有权,按源SQL创建基础107张表、原生48张表和005—015增量结构,再建立字典、菜单、角色。它不是“恢复历史数据”,不会自动创建真实在线设备或替用户复制用例。
## 7. 构建、启动与局域网访问
```powershell
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Build
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Start
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Status
```
Build使用Windows的JDK17/Maven3.9构建后端,再用`pnpm build:standalone`构建前端,输出`am-web/dist-standalone`。不会把浏览器API地址打包为localhost:48090;浏览器统一走当前网页的`/admin-api`。
Start只启动本实例的MySQL、Redis、Java和Nginx,等待数据库、Redis及后端就绪,不结束其他进程。后端使用`--spring.profiles.active=standalone`,额外只读取`.local/standalone/application-private.yaml`,不加载现有dev/local的私有设备信息。当前程序没有打包Actuator;启动探测使用已有的只读`/admin-api/system/tenant/simple-list`,要求业务码0且存在主租户1,不把仅HTTP200当成成功。
本机先打开`http://127.0.0.1:5180`。需要局域网访问时,把网络设为可信的“专用网络”,管理员PowerShell7执行:
```powershell
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Firewall
```
只新增本应用的5180/TCP、48090/TCP、4433/UDP专用网络/本地子网规则。MySQL和Redis端口仍只发布到127.0.0.1;不关闭Windows防火墙。然后在另一台局域网电脑访问`http://目标IP:5180`,核对登录、刷新页面、文件下载及WebSocket。
## 8. 接入扫描仪、旋转底座、机械臂与AGV
基础系统验收完成后,再填写目标私有配置。可以参考迁移包`private/source-scanner-private.yaml`,但不要整体覆盖新实例,更不要复制旧MySQL/Redis地址。界面“设备与资源→机器人→连接配置”中核对迁移的设备服务地址,必要时人工调整。
- 扫描仪:实际HTTP地址/端口、Bearer API密钥、工位及设备永久ID,必须与资源绑定一致。只读核对status,不自动开始扫描。
- 旋转底座:实际gRPC地址和设备身份,只读核对状态;不自动使能、回零或旋转。
- 机械臂/AGV:边端的QUIC目标改为新电脑LAN IP、UDP4433。保持协议ALPN和可信CA一致,随后由真实QUIC快照重新发现设备与gRPC地址。
- QUIC初始为关闭状态。把合规的证书/私钥放到目标dataRoot/certs,在私有YAML中填写绝对路径再启用。新服务器IP必须被服务端证书SAN覆盖;旧证书只覆盖旧IP时,由原CA签发新证书并核对指纹。不能关闭TLS验证或随便换自签CA来“解决连接”。
- 源、目标不能同时作为现场活动控制平台。最终切换前用户确认源端已停止,源自动启动任务不再把旧平台拉起来;目标验收完成前不让同一边端在两边来回切换。
- 私有配置变更后按第10节安全重启。界面“在线”仅代表对应真实通道状态,不能作为夹具安装正确、机械臂已使能或扫描精度验收的替代。
## 9. AI验收清单与交付记录
基础验收全部可以不运动:
1. `docker compose --env-file .local/standalone/compose.env -f deploy/windows11/compose.yaml ps`:MySQL、Redis健康,web运行。
2. `Invoke-RestMethod http://127.0.0.1:48090/admin-api/system/tenant/simple-list`返回业务码0,data中存在租户1;前端与Nginx配置检查通过。数据库结构由bootstrap_standalone的verify核对,Redis由容器健康检查核对。
3. 原账号登录;任务中心、配置中心、设备与资源、成果中心可打开,无持续500错误。
4. 迁移包所有SHA256通过;导入前后表行数相符。OAuth令牌清理、连接状态重置属于明确列出的运行态变化。
5. 核对指定用例ID、当前发布版本、子流程引用、所有设备角色、夹具框架点版本及轨迹关联;打开配置和历史执行,不点试运行。
6. 抽查历史PLY/STL、框架点、数模和PDF的下载与SHA256,确保读的是新目录。只生成预览,不启动扫描。报告/STL原本不存在时保留“暂无”,不能伪造交付。
7. 从另一台电脑检查资源访问不指向它自己的127.0.0.1,WebSocket能升级,扫描流配置为不缓冲;实际设备预览在用户现场允许后观察。
8. 验证后端48090和UDP4433(QUIC启用时)归属于同一个Java进程;无第二套旧4433进程。
9. 留下Git提交号、JAR SHA256、镜像RepoDigest、数据目录、端口、备份路径、启动方式和仍未完成的现场项。记录不包含密码/Token/私钥。
真实使能、回零、机械臂运动、扫描和工作流执行由现场用户确认后单独验收。用例此前在源环境运行成功,不代表目标设备地址、坐标系和现场条件已重新确认。
## 10. 停止、更新、启动与登录后自启
现场停止后:
```powershell
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Stop -ConfirmStopped
```
脚本还会检查活动任务和占用;未确认停止则拒绝。只停止它保存并核对过身份的Java进程,不终止全部java.exe,也不删除数据卷。
更新前先备份;源/目标均无活动现场操作后:
```powershell
git status --short
git pull --ff-only origin main
# 有本地源码修改时先整理,禁止 reset --hard 覆盖。
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Build
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Start
```
模板升级不会覆盖`.local/standalone`。数据库结构升级需要阅读对应迁移说明,不能把空库Bootstrap当作业务库升级工具。
管理员可注册登录启动:
```powershell
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action InstallAutostart
```
同时开启Docker Desktop“用户登录时启动”。此方案是**该用户登录后自动启动**,不是“无人登录也保证运行”的Windows服务承诺;Docker Desktop依赖用户会话。需要无人登录运行时,应另行设计自动启动的Linux虚拟机/Docker Engine或受支持的服务部署,不设置明文自动登录来绕过此限制。
## 11. 备份、恢复与回退
必须一起备份:MySQL、artifacts、uploads、目标私有配置、QUIC材料、部署提交和运行包指纹。仅备份Git无法恢复业务。
先停止新任务和现场设备,按Stop确认退出后端,再在PowerShell7执行数据库备份(示例文件名自行带时间):
```powershell
docker compose --env-file .local/standalone/compose.env -f deploy/windows11/compose.yaml exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysqldump -uroot --single-transaction --no-tablespaces --set-gtid-purged=OFF --hex-blob am-freescan > /backup/after-migration.sql'
```
确认退出码0、SQL非空并记录SHA256,再复制artifacts、uploads、私有配置和证书到受限备份位置。Redis主要保存可重建会话/缓存;Docker持久卷保留,迁移不恢复旧登录锁。需要卷级完整备份时先正常停止相应容器,再按Docker卷备份文档操作,不能在线直接复制数据库数据目录。
回退必须将数据库、文件和兼容的代码版本一起恢复到另一套空环境。禁止只回滚JAR后就让不兼容数据库继续运行。新机验收前保留旧电脑和迁移包;切回源设备前先停目标控制入口,防止双控制。
## 12. 离线部署
仅Git可达时,由有网络的可信构建电脑准备:Windows JDK17/Node24/Python/PowerShell7/Maven3.9安装包、锁文件对应依赖缓存或Windows构建的JAR和`dist-standalone`、Python所需Windows wheels、对应Docker Linux镜像。
```powershell
docker pull mysql:8.4
docker pull redis:7.4-alpine
docker pull nginx:stable-alpine
docker save -o freescan-images.tar mysql:8.4 redis:7.4-alpine nginx:stable-alpine
# 目标电脑:
docker load -i freescan-images.tar
```
交付SHA256和镜像RepoDigest,首次验收后固定到已验证镜像digest再升级。Python包用匹配Windows/Python3.12的wheels,`pip install --no-index --find-links <wheel目录> -r deploy/windows11/requirements.txt`。不能把Linux native JAR、Linux node_modules或Linux wheels直接交给Windows运行。
使用预构建产物时,把Windows版JAR放到`.local/standalone/backend/yudao-server.jar`,前端产物内容放到dataRoot/web,核对版本和SHA256后直接Start;这样目标机不必重新下载Maven/npm依赖。迁移包始终单独受限交付,不放入Git或公共镜像。
## 13. 常见故障
本次在源电脑完成了后端回归、前端类型检查与standalone打包、配置隔离检查,以及模拟空库的迁移流程验证。源电脑没有Docker环境,未在这里启动新MySQL/Redis容器或实际导出/恢复业务数据库。目标AI必须执行本手册的Docker配置检查、真实导入和验收;不能跳过后宣称迁移完成。启动容器前先运行`docker compose --env-file .local/standalone/compose.env -f deploy/windows11/compose.yaml config --quiet`,不要打印包含密码的展开配置。
- WSL/Docker没启动:检查虚拟化、WSL版本、当前用户Docker Desktop,不切成Windows容器。
- MySQL/Redis不健康:先看`compose ps`及容器日志;不输出`compose config`展开后的密码,不删卷重建。
- RSA认证失败:确认安装本目录requirements中的cryptography;不通过更换旧认证插件规避。
- 后端启动失败:看dataRoot/logs,确认standalone激活、127.0.0.1地址和私有密码匹配,不回退到dev/local。
- 页面能开但API502:从web容器检查`host.docker.internal:48090`,确认后端监听0.0.0.0及防火墙;不能改成容器自身127.0.0.1。
- 上传/归档失败:固定文件大小上限已取消的版本仍会按实际磁盘/内存/GPU容量保护。确认磁盘余量和临时目录;归档传输采用流式,不把OOM视为“无限大小支持”。厂商HTTP上传自身的上限需要厂商调整。
- 大文件或扫描流超时:核对节点等待、网络和Nginx读取超时;不因为超时就自动重发设备动作。
- 文件404:区分平台持久URL和供应商临时URL。缺失的原文件要补传,不能拿JSON元数据当文件内容。
- 夹具轨迹看得到但不能执行:目标仍需连接原边端文件、匹配轨迹版本、坐标系和机械臂身份;不自动补录或应用。
官方安装与配置来源:[Docker Windows安装](https://docs.docker.com/desktop/setup/install/windows-install/)、[WSL安装](https://learn.microsoft.com/windows/wsl/install)、[MySQL下载](https://dev.mysql.com/downloads/mysql/)、[Maven下载](https://maven.apache.org/download.cgi)、[Node.js下载](https://nodejs.org/en/download)、[Redis持久化](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)、[Nginx代理配置](https://nginx.org/en/docs/http/ngx_http_proxy_module.html)。Docker Desktop的组织许可按官方条款由部署方确认。

View File

@ -0,0 +1,21 @@
# Copy to .local/standalone/application-private.yaml only after the base instance passes acceptance.
# Keep actual keys and private key files outside Git. Blank device hosts do not claim hardware online.
cmvr:
scanner:
host: ""
port: 18888
api-key: ""
robot-id: am-freescan-station-001
device-id: am-freescan-scanner-001
rotary-base:
host: ""
port: 50052
quic:
enabled: false
alpn: cmvr-quic-edge/1
allowed-node-ids: []
tls:
certificate: ""
private-key: ""
client-ca: ""
require-client-certificate: false

View File

@ -0,0 +1,57 @@
name: am-freescan-standalone
services:
mysql:
image: mysql:8.4
restart: unless-stopped
ports:
- "127.0.0.1:3306:3306"
environment:
TZ: Asia/Shanghai
MYSQL_DATABASE: am-freescan
MYSQL_USER: freescan
MYSQL_PASSWORD: ${MYSQL_APP_PASSWORD:?run manage.ps1 Init first}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?run manage.ps1 Init first}
command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci"]
volumes:
- mysql-data:/var/lib/mysql
- ${BACKUP_ROOT:?required}:/backup
healthcheck:
test: ["CMD-SHELL", "MYSQL_PWD=$$MYSQL_PASSWORD mysql -h 127.0.0.1 -ufreescan -D am-freescan -e 'SELECT 1' >/dev/null 2>&1"]
interval: 5s
timeout: 5s
retries: 36
start_period: 30s
logging:
options: {max-size: "20m", max-file: "3"}
redis:
image: redis:7.4-alpine
restart: unless-stopped
ports:
- "127.0.0.1:6379:6379"
environment:
REDIS_PASSWORD: ${REDIS_PASSWORD:?run manage.ps1 Init first}
command: ["sh", "-c", 'exec redis-server --appendonly yes --appendfsync everysec --databases 16 --requirepass "$$REDIS_PASSWORD"']
volumes:
- redis-data:/data
healthcheck:
test: ["CMD-SHELL", 'REDISCLI_AUTH="$$REDIS_PASSWORD" redis-cli -h 127.0.0.1 ping | grep -q PONG']
interval: 5s
timeout: 3s
retries: 12
logging:
options: {max-size: "20m", max-file: "3"}
web:
image: nginx:stable-alpine
restart: unless-stopped
ports:
- "5180:80"
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
- ${WEB_ROOT:?build frontend first}:/usr/share/nginx/html:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
logging:
options: {max-size: "20m", max-file: "3"}
volumes:
mysql-data:
redis-data:

184
deploy/windows11/manage.ps1 Normal file
View File

@ -0,0 +1,184 @@
#requires -Version 7.2
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('Init','Middleware','Bootstrap','Restore','Build','Start','Stop','Status','Firewall','InstallAutostart')][string]$Action,
[string]$DataRoot = 'D:/am-freescan-data',
[string]$PublicBaseUrl = 'http://127.0.0.1:5180',
[switch]$ConfirmStopped,
[string]$MigrationPath
)
$ErrorActionPreference = 'Stop'
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$private = Join-Path $repo '.local/standalone'
$runtimeFile = Join-Path $private 'runtime.json'
$compose = Join-Path $PSScriptRoot 'compose.yaml'
$envFile = Join-Path $private 'compose.env'
$pidFile = Join-Path $private 'backend-process.json'
$jar = Join-Path $private 'backend/yudao-server.jar'
$bootstrap = Join-Path $repo 'scripts/bootstrap_standalone.py'
function Invoke-Checked([string]$Program, [string[]]$Arguments) {
& $Program @Arguments
if ($LASTEXITCODE -ne 0) { throw "$Program failed ($LASTEXITCODE); do not continue to the next deployment step" }
}
function Compose([string[]]$Arguments) {
Invoke-Checked 'docker' (@('compose','--env-file',$envFile,'-f',$compose) + $Arguments)
}
function Read-Runtime {
if (-not (Test-Path -LiteralPath $runtimeFile)) { throw 'Run Init first' }
$value = Get-Content -LiteralPath $runtimeFile -Raw | ConvertFrom-Json
if ($value.mysql.host -ne '127.0.0.1' -or $value.mysql.database -ne 'am-freescan' -or $value.mysql.port -ne 3306 -or $value.redis.host -ne '127.0.0.1' -or $value.redis.port -ne 6379) { throw 'Standalone middleware must remain local' }
return $value
}
function Secret([int]$Length) {
$bytes = [byte[]]::new($Length)
[Security.Cryptography.RandomNumberGenerator]::Fill($bytes)
return -join ($bytes | ForEach-Object { 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'[$_ % 55] })
}
function Write-ComposeEnv($cfg) {
$web = (Join-Path $cfg.dataRoot 'web').Replace('\','/')
$backup = (Join-Path $cfg.dataRoot 'backups').Replace('\','/')
@("MYSQL_ROOT_PASSWORD=$($cfg.mysqlRootPassword)","MYSQL_APP_PASSWORD=$($cfg.mysql.password)","REDIS_PASSWORD=$($cfg.redis.password)","WEB_ROOT='$web'","BACKUP_ROOT='$backup'") |
Set-Content -LiteralPath $envFile -Encoding utf8NoBOM
}
function Ensure-Idle($cfg) {
if (-not $ConfirmStopped) { throw 'Onsite confirmation required: use -ConfirmStopped only after acquisition and all physical motion have stopped' }
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--check-idle')
}
function Owned-Backend {
if (-not (Test-Path -LiteralPath $pidFile)) { return $null }
$saved = Get-Content -LiteralPath $pidFile -Raw | ConvertFrom-Json
$process = Get-Process -Id $saved.pid -ErrorAction SilentlyContinue
if (-not $process) { return $null }
$details = Get-CimInstance Win32_Process -Filter "ProcessId=$($saved.pid)"
if ($process.StartTime.ToUniversalTime().ToString('o') -ne $saved.startedUtc -or -not $details.CommandLine -or $details.CommandLine.IndexOf($jar,[StringComparison]::OrdinalIgnoreCase) -lt 0) { throw 'PID was reused or points to another service; refusing to stop it' }
return $process
}
function Healthy {
# This application does not bundle Actuator. Use its existing, public, read-only
# tenant lookup, and require an initialized primary tenant rather than HTTP 200 alone.
try {
$reply = Invoke-RestMethod 'http://127.0.0.1:48090/admin-api/system/tenant/simple-list' -TimeoutSec 3
return $reply.code -eq 0 -and @($reply.data | Where-Object { $_.id -eq 1 }).Count -eq 1
}
catch { return $false }
}
if ($Action -eq 'Init') {
if (Test-Path -LiteralPath $runtimeFile) { Write-Output 'Private instance config already exists; preserved without changes'; exit 0 }
foreach ($port in @(3306,6379,48090,5180)) {
if (Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction SilentlyContinue) { throw "Port $port is occupied; identify its owner before creating an independent instance" }
}
if (-not [IO.Path]::IsPathFullyQualified($DataRoot)) { throw 'DataRoot must be an absolute Windows path' }
$origin = [uri]$PublicBaseUrl
if ($origin.Scheme -notin @('http','https') -or -not $origin.Host -or $origin.UserInfo -or $origin.Query -or $origin.Fragment -or $origin.AbsolutePath -ne '/') { throw 'PublicBaseUrl must be a plain browser-accessible HTTP(S) origin' }
$DataRoot = [IO.Path]::GetFullPath($DataRoot).TrimEnd('\','/').Replace('\','/')
if (Test-Path -LiteralPath $DataRoot) {
if (Get-ChildItem -LiteralPath $DataRoot -Force) { throw 'Choose a new empty DataRoot; do not adopt another deployment storage directory' }
}
New-Item -ItemType Directory -Path $private -Force | Out-Null
$principal = [Security.Principal.WindowsIdentity]::GetCurrent().Name
Invoke-Checked 'icacls.exe' @($private,'/inheritance:r','/grant:r',"${principal}:(OI)(CI)F",'*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F')
foreach ($dir in @('artifacts','uploads','web','backups','logs','certs','tmp')) { New-Item -ItemType Directory -Path (Join-Path $DataRoot $dir) -Force | Out-Null }
New-Item -ItemType Directory -Path (Join-Path $private 'backend') -Force | Out-Null
$cfg = [ordered]@{
instanceId = [guid]::NewGuid().ToString('N'); dataRoot = $DataRoot; uploadRoot = "$DataRoot/uploads"
publicBaseUrl = $PublicBaseUrl.TrimEnd('/'); adminPassword = (Secret 14); mysqlRootPassword = (Secret 32)
mysql = @{host='127.0.0.1';port=3306;database='am-freescan';user='freescan';password=(Secret 32)}
redis = @{host='127.0.0.1';port=6379;database=15;password=(Secret 32)}
}
$cfg | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $runtimeFile -Encoding utf8NoBOM
Write-ComposeEnv $cfg
@('username=admin',"password=$($cfg.adminPassword)") | Set-Content -LiteralPath (Join-Path $private 'initial-admin.txt') -Encoding utf8NoBOM
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'application-private.example.yaml') -Destination (Join-Path $private 'application-private.yaml')
Write-Output 'Independent config created in .local/standalone; passwords are stored privately and are not printed'
exit 0
}
$cfg = Read-Runtime
Write-ComposeEnv $cfg
switch ($Action) {
'Middleware' { Compose @('up','-d','--wait','mysql','redis') }
'Bootstrap' {
Invoke-Checked 'python' @($bootstrap)
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--apply')
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify')
}
'Build' {
if (Owned-Backend) { throw 'Stop this backend safely before replacing its runtime package' }
$java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java).Source }
$version = (& $java -version 2>&1 | Out-String)
if ($version -notmatch 'version "17\.') { throw 'Build and runtime require JDK 17' }
$maven = (& mvn -version 2>&1 | Out-String)
if ($maven -notmatch 'Apache Maven 3\.9\.') { throw 'Use Maven 3.9.x and place it first on PATH' }
Push-Location (Join-Path $repo 'am-backend')
try { Invoke-Checked 'mvn' @('-pl','yudao-server','-am','package','-DskipTests','-DskipITs') } finally { Pop-Location }
Copy-Item -LiteralPath (Join-Path $repo 'am-backend/yudao-server/target/yudao-server.jar') -Destination $jar -Force
Push-Location (Join-Path $repo 'am-web')
try {
Invoke-Checked 'pnpm' @('install','--frozen-lockfile')
Invoke-Checked 'pnpm' @('build:standalone')
Copy-Item -Path 'dist-standalone/*' -Destination (Join-Path $cfg.dataRoot 'web') -Recurse -Force
} finally { Pop-Location }
git -C $repo rev-parse HEAD | Set-Content -LiteralPath (Join-Path $private 'deployed-commit.txt') -Encoding utf8NoBOM
(Get-FileHash -LiteralPath $jar).Hash | Set-Content -LiteralPath (Join-Path $private 'backend-sha256.txt') -Encoding utf8NoBOM
}
'Restore' {
if (-not $ConfirmStopped -or -not $MigrationPath) { throw 'Restore requires -MigrationPath and -ConfirmStopped; source must remain stopped' }
Invoke-Checked 'python' @((Join-Path $repo 'scripts/migrate_standalone.py'),'import','--config',$runtimeFile,'--package',$MigrationPath,'--confirm-source-stopped')
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify')
}
'Start' {
$until = [datetime]::UtcNow.AddSeconds(120)
do { & docker info *> $null; if ($LASTEXITCODE -eq 0) { break }; Start-Sleep 3 } while ([datetime]::UtcNow -lt $until)
if ($LASTEXITCODE -ne 0) { throw 'Docker Desktop is not ready; start it in this Windows user session' }
Compose @('up','-d','--wait','mysql','redis')
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify')
if (-not (Test-Path -LiteralPath $jar) -or -not (Test-Path -LiteralPath (Join-Path $cfg.dataRoot 'web/index.html'))) { throw 'Run Build first' }
$owned = Owned-Backend
if (-not $owned) {
if (Get-NetTCPConnection -State Listen -LocalPort 48090 -ErrorAction SilentlyContinue) { throw '48090 belongs to another process; do not kill it' }
if (Get-NetUDPEndpoint -LocalPort 4433 -ErrorAction SilentlyContinue) { throw 'UDP 4433 belongs to another process; identify it before starting' }
$java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java).Source }
if ((& $java -version 2>&1 | Out-String) -notmatch 'version "17\.') { throw 'Runtime requires JDK 17' }
$env:AM_FREESCAN_HOME = $cfg.dataRoot
$env:AM_FREESCAN_DB_USER = 'freescan'; $env:AM_FREESCAN_DB_PASSWORD = $cfg.mysql.password
$env:AM_FREESCAN_REDIS_PASSWORD = $cfg.redis.password; $env:AM_FREESCAN_PUBLIC_BASE_URL = $cfg.publicBaseUrl
$privateYaml = (Join-Path $private 'application-private.yaml').Replace('\','/')
$arguments = @('-Xms512m','-Xmx2g','-Dfile.encoding=UTF-8',('"-Djava.io.tmpdir='+$cfg.dataRoot+'/tmp"'),'-jar',('"'+$jar+'"'),'--spring.profiles.active=standalone',('"--spring.config.additional-location=optional:file:'+$privateYaml+'"'))
$process = Start-Process -FilePath $java -ArgumentList $arguments -WorkingDirectory $repo -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $cfg.dataRoot 'logs/launch.stdout.log') -RedirectStandardError (Join-Path $cfg.dataRoot 'logs/launch.stderr.log')
@{pid=$process.Id;startedUtc=$process.StartTime.ToUniversalTime().ToString('o')} | ConvertTo-Json | Set-Content -LiteralPath $pidFile -Encoding utf8NoBOM
}
$until = [datetime]::UtcNow.AddSeconds(120)
while (-not (Healthy) -and [datetime]::UtcNow -lt $until) { Start-Sleep 2 }
if (-not (Healthy)) { throw 'Backend is not healthy; inspect dataRoot/logs without printing passwords' }
Compose @('up','-d','web')
Compose @('exec','-T','web','nginx','-t')
Write-Output "Backend healthy; browser entry: $($cfg.publicBaseUrl)"
}
'Stop' {
Ensure-Idle $cfg
$process = Owned-Backend
if ($process) { Stop-Process -Id $process.Id -ErrorAction Stop; $process.WaitForExit(30000) | Out-Null }
Write-Output 'Owned backend stopped; middleware, frontend and persistent data retained'
}
'Status' {
Compose @('ps')
Write-Output "Backend healthy: $(Healthy)"
Get-NetTCPConnection -State Listen -LocalPort 48090,5180 -ErrorAction SilentlyContinue | Select-Object LocalPort,OwningProcess
Get-NetUDPEndpoint -LocalPort 4433 -ErrorAction SilentlyContinue | Select-Object LocalPort,OwningProcess
}
'Firewall' {
foreach ($rule in @(@{name='AM-FreeScan-Web';port=5180;protocol='TCP'},@{name='AM-FreeScan-QUIC';port=4433;protocol='UDP'},@{name='AM-FreeScan-API';port=48090;protocol='TCP'})) {
if (-not (Get-NetFirewallRule -Name $rule.name -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name $rule.name -DisplayName $rule.name -Direction Inbound -Action Allow -Protocol $rule.protocol -LocalPort $rule.port -Profile Private -RemoteAddress LocalSubnet | Out-Null }
}
Write-Output 'Added only application rules for Private/LocalSubnet; database and Redis ports remain loopback-only'
}
'InstallAutostart' {
$executable = (Get-Command pwsh).Source
$taskAction = New-ScheduledTaskAction -Execute $executable -Argument ('-NoProfile -ExecutionPolicy Bypass -File "'+$PSCommandPath+'" -Action Start') -WorkingDirectory $repo
$trigger = New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name)
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -MultipleInstances IgnoreNew
Register-ScheduledTask -TaskName 'AM-FreeScan-Standalone' -Action $taskAction -Trigger $trigger -Settings $settings -Description 'Start the independent instance after this user logs in and Docker Desktop is ready' -Force | Out-Null
Write-Output 'Login startup registered; also enable Docker Desktop startup at login. No unattended pre-login startup is claimed.'
}
}

View File

@ -0,0 +1,48 @@
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
client_max_body_size 0;
location /admin-api/ {
# The backend runs on Windows, not inside this Linux container.
proxy_pass http://host.docker.internal:48090;
proxy_http_version 1.1;
proxy_connect_timeout 10s;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_buffering off;
proxy_cache off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /open-api/ {
proxy_pass http://host.docker.internal:48090;
proxy_connect_timeout 10s;
proxy_read_timeout 3600s;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /infra/ws {
proxy_pass http://host.docker.internal:48090;
proxy_http_version 1.1;
proxy_read_timeout 3600s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $http_host;
}
location = /index.html {
add_header Cache-Control "no-store";
}
location / {
try_files $uri $uri/ /index.html;
}
}

View File

@ -0,0 +1,2 @@
-r ../../scripts/requirements.txt
cryptography>=42,<50

View File

@ -199,10 +199,10 @@ def provision_identity(cursor, config):
insert_new(cursor, "system_oauth2_client", dict(id=1, client_id="default", secret=secrets.token_urlsafe(32), name="AM FreeScan", logo="", description="Independent local admin client", status=0, access_token_validity_seconds=1800, refresh_token_validity_seconds=2592000, redirect_uris='["http://127.0.0.1:5180"]', authorized_grant_types='["password","refresh_token"]', scopes="[]", auto_approve_scopes="[]", **audit), ["client_id"])
insert_new(cursor, "infra_config", dict(id=1, category="system", type=1, name="Account registration", config_key="system.user.register-enabled", value="false", visible=0, remark="Independent baseline: registration disabled", **audit), ["config_key"])
# A local filesystem client is configured without inheriting old cloud keys.
storage_root = (ROOT / ".local" / "files").as_posix()
storage_root = Path(config.get("uploadRoot") or ROOT / ".local" / "files").resolve().as_posix()
file_config = {"@class": "cn.iocoder.yudao.module.infra.framework.file.core.client.local.LocalFileClientConfig", "basePath": storage_root, "domain": config.get("backendUrl", "http://localhost:48090")}
insert_new(cursor, "infra_file_config", dict(id=1, name="AM FreeScan local files", storage=10, remark="Independent local directory", master=1, config=json.dumps(file_config), **audit), ["id"])
(ROOT / ".local" / "files").mkdir(parents=True, exist_ok=True)
Path(storage_root).mkdir(parents=True, exist_ok=True)
if generated and admin_created:
local = ROOT / ".local"
local.mkdir(exist_ok=True)

View File

@ -0,0 +1,167 @@
"""Independent localhost-only deployment bootstrap. Never uses .local/runtime.json or a LAN DB.
Default: parse/validate the complete schema offline. --apply requires a private runtime generated
by deploy/windows11/manage.ps1. An unrelated nonempty database is always rejected.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import sys
from urllib.parse import urlparse
import bootstrap_db as base
import bootstrap_cmvr as native
from apply_scan_only import apply_schema, load_migration
OWNER = "am-freescan/standalone-v1"
MIGRATIONS = (
"005_scan_only.sql", "006_resource_scheduling.sql", "007_scanner_integration.sql",
"008_scanner_execution_view.sql", "009_rotary_base_integration.sql",
"010_scanner_framework_reference.sql", "011_fixture_framework.sql",
"012_robot_service_endpoint.sql", "013_execution_plan.sql", "014_dimension_delivery.sql",
"015_fixture_trajectory.sql",
)
def plan():
schema, seeds = base.load_assets()
cmvr = base.load_schema(native.SCHEMA, native.PREFIXES)
reference = native.load_reference()
migrations = [(name, load_migration(base.SQL_ROOT / name)) for name in MIGRATIONS]
discovered = {p.name for p in base.SQL_ROOT.glob("*.sql") if p.name[:3].isdigit() and int(p.name[:3]) >= 5}
if discovered != set(MIGRATIONS) | {"016_coordinate_management.sql"}:
raise ValueError("Migration inventory changed; review the standalone initialization plan first")
return schema, seeds, cmvr, reference, migrations
def configuration(path):
cfg = json.loads(path.read_text(encoding="utf-8-sig"))
db = cfg["mysql"]
if db.get("host") != "127.0.0.1" or int(db.get("port", 0)) != 3306 or db.get("database") != "am-freescan" or db.get("user") != "freescan":
raise ValueError("Standalone bootstrap only permits freescan@127.0.0.1:3306/am-freescan")
if not cfg.get("instanceId") or not db.get("password"):
raise ValueError("Missing instance identity or local database credential")
admin = cfg.get("adminPassword", "")
if not 8 <= len(admin) <= 16:
raise ValueError("Initial admin password must contain 8 to 16 characters")
if os.environ.get("AM_FREESCAN_ADMIN_PASSWORD", admin) != admin:
raise ValueError("Conflicting administrator environment variable; do not override this instance")
home = Path(cfg["dataRoot"]).resolve()
if not Path(cfg["dataRoot"]).is_absolute() or Path(cfg["uploadRoot"]).resolve() != home / "uploads":
raise ValueError("Upload storage must be the uploads directory of this independent data root")
public = urlparse(cfg["publicBaseUrl"])
if public.scheme not in {"http", "https"} or not public.hostname or public.username or public.password or public.query or public.fragment or public.path not in {"", "/"}:
raise ValueError("Public base URL must be a plain browser-accessible HTTP(S) origin")
return cfg
def connect(cfg):
import pymysql
m = cfg["mysql"]
return pymysql.connect(host="127.0.0.1", port=3306, user="freescan", password=m["password"],
database="am-freescan", charset="utf8mb4", autocommit=True, connect_timeout=5,
read_timeout=60, write_timeout=60)
def ownership(cursor, cfg, allow_empty=False):
cursor.execute("SELECT DATABASE()")
if cursor.fetchone() != ("am-freescan",):
raise ValueError("Unexpected database")
cursor.execute("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan'")
tables = {r[0] for r in cursor.fetchall()}
if not tables and allow_empty:
return
if base.META not in tables:
raise ValueError("Nonempty database has no standalone ownership marker; refusing to change it")
cursor.execute(f"SELECT name,value FROM `{base.META}` WHERE name IN ('owner','instance')")
values = dict(cursor.fetchall())
if values.get("owner") != OWNER or values.get("instance") != cfg["instanceId"]:
raise ValueError("Database belongs to another deployment; refusing to change it")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path)
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--apply", action="store_true")
mode.add_argument("--verify", action="store_true")
mode.add_argument("--check-idle", action="store_true")
args = parser.parse_args(argv)
schema, seeds, cmvr, reference, migrations = plan()
if not any((args.apply, args.verify, args.check_idle)):
print(json.dumps(dict(mode="offline", target="127.0.0.1:3306/am-freescan",
baseTables=len(schema), nativeTables=len(cmvr), migrations=[n for n, _ in migrations],
referenceSeeds=list(seeds), noDatabaseConnection=True)))
return 0
if args.config is None:
raise ValueError("An explicit standalone --config is required")
cfg = configuration(args.config)
if args.apply:
import bcrypt # Verify availability before any writes.
with connect(cfg) as connection:
with connection.cursor() as cursor:
ownership(cursor, cfg, allow_empty=args.apply)
if args.check_idle:
for sql in (
"SELECT COUNT(*) FROM te_task_inst WHERE status IN ('1','3')",
"SELECT COUNT(*) FROM lab_execution WHERE status IN ('RUNNING','PAUSED','STOPPING') AND deleted=0",
"SELECT COUNT(*) FROM lab_resource_occupation WHERE tenant_id=1 AND deleted=0",
):
cursor.execute(sql)
if cursor.fetchone()[0]:
raise ValueError("Active execution or occupation remains; stop safely through the platform first")
print("No active platform execution or occupation; physical state still requires onsite confirmation")
return 0
if args.verify:
# A migrated business instance may have deliberately reorganized menus.
# Validate usable identity/navigation without rewriting it to seed values.
for sql in (
"SELECT COUNT(*) FROM system_users WHERE id=1 AND username='admin' AND tenant_id=1 AND deleted=0",
"SELECT COUNT(*) FROM system_tenant WHERE id=1 AND deleted=0",
"SELECT COUNT(*) FROM system_menu WHERE deleted=0 AND status=0 AND type IN (1,2)",
):
cursor.execute(sql)
if cursor.fetchone()[0] < 1:
raise ValueError("Required identity or navigation data is missing")
for table in set(schema) | set(cmvr) | {"lab_dimension_delivery", "lab_fixture_trajectory", "lab_resource_occupation", "lab_scanner_command"}:
cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan' AND TABLE_NAME=%s", (table,))
if cursor.fetchone()[0] != 1:
raise ValueError("Missing required table: " + table)
print("Standalone schema, ownership, reference data and menus verified")
return 0
cursor.execute("SELECT GET_LOCK(%s,10)", (OWNER,))
if cursor.fetchone() != (1,):
raise ValueError("Another standalone bootstrap is running")
try:
# Recheck ownership after taking the lock, before creating even the marker table.
ownership(cursor, cfg, allow_empty=True)
cursor.execute(f"CREATE TABLE IF NOT EXISTS `{base.META}` (name varchar(80) PRIMARY KEY,value text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4")
for key, value in (("owner", OWNER), ("instance", cfg["instanceId"])):
cursor.execute(f"INSERT IGNORE INTO `{base.META}` (name,value) VALUES(%s,%s)", (key, value))
changed = base.ensure_schema(cursor, schema) + base.ensure_schema(cursor, cmvr)
for name, operations in migrations:
changed += apply_schema(cursor, operations)
checksum = hashlib.sha256((base.SQL_ROOT / name).read_bytes()).hexdigest()
cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (name, checksum))
base.provision_identity(cursor, dict(adminPassword=cfg["adminPassword"], uploadRoot=cfg["uploadRoot"], backendUrl=cfg["publicBaseUrl"]))
for filename, (checksum, statements) in seeds.items():
cursor.execute(f"SELECT value FROM `{base.META}` WHERE name=%s", (filename,))
if cursor.fetchone() == (checksum,):
continue
for statement in statements:
cursor.execute(statement)
cursor.execute(f"INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)", (filename, checksum))
native.references(cursor, reference)
base.finalize_permissions(cursor)
native.verify_references(cursor, reference)
print(json.dumps(dict(initialized=True, target="127.0.0.1/am-freescan", additiveChanges=changed,
user="admin", passwordPrinted=False, originalBusinessDataImported=False)))
finally:
cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,))
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error:
detail = str(error) if isinstance(error, ValueError) else "check the private config, local middleware and deployment logs"
print(f"Standalone bootstrap stopped ({type(error).__name__}): {detail}", file=sys.stderr)
raise SystemExit(1)

View File

@ -0,0 +1,219 @@
"""Private migration bundle: stopped source -> empty localhost deployment. Nothing is uploaded to Git.
Requires official mysqldump on the source; the target imports with its local MySQL container.
"""
from __future__ import annotations
import argparse, hashlib, json, os, re, shutil, socket, subprocess, sys, tempfile, uuid
from pathlib import Path
from urllib.parse import urlsplit
import bootstrap_db as source_bootstrap
import bootstrap_standalone as standalone
ROOT = Path(__file__).resolve().parents[1]
def reparse(path):
"""Do not follow Windows junctions or symbolic links into unrelated directories."""
return path.is_symlink() or bool(getattr(path.lstat(), 'st_file_attributes', 0) & 0x400)
def digest(path):
h=hashlib.sha256()
with path.open('rb') as f:
while chunk:=f.read(1024*1024):h.update(chunk)
return h.hexdigest()
def copy_tree(source,target):
source=Path(source)
if source.exists() and reparse(source):raise ValueError('Source directory must not be a link or junction')
source=source.resolve()
if not source.is_dir():raise ValueError('Missing source data directory: '+str(source))
target.mkdir(parents=True,exist_ok=True)
for p in source.rglob('*'):
if reparse(p):raise ValueError('Migration does not follow symlinks or junctions: '+str(p))
destination=target/p.relative_to(source)
if p.is_dir():destination.mkdir(parents=True,exist_ok=True)
else:shutil.copy2(p,destination)
def idle(cursor):
for sql in ("SELECT COUNT(*) FROM te_task_inst WHERE status IN ('1','3')",
"SELECT COUNT(*) FROM lab_execution WHERE status IN ('RUNNING','PAUSED','STOPPING') AND deleted=0",
"SELECT COUNT(*) FROM lab_resource_occupation WHERE deleted=0",
"SELECT COUNT(*) FROM lab_scanner_command WHERE active_endpoint IS NOT NULL"):
cursor.execute(sql)
if cursor.fetchone()[0]:raise ValueError('Source execution, occupation or unconfirmed scanner command remains; resolve it before exporting')
def export_bundle(args):
if not args.confirm_source_stopped:raise ValueError('Explicit --confirm-source-stopped is required after stopping all physical operations and the source backend')
with socket.socket() as probe:
if probe.connect_ex(('127.0.0.1',48090))==0:raise ValueError('Source backend still listens on 48090; do not export while it can modify files')
runtime=json.loads(args.source_runtime.read_text(encoding='utf-8-sig'));mysql=runtime['mysql'];source_bootstrap.validate_target(mysql)
import pymysql
connection=pymysql.connect(host=mysql['host'],port=int(mysql.get('port',3306)),user=mysql['user'],password=mysql['password'],database='am-freescan',charset='utf8mb4',autocommit=True)
output=args.output.resolve()
if output.is_relative_to(args.artifacts.resolve()):raise ValueError('Bundle output must be outside source artifacts')
if output.exists():raise ValueError('Output must be a new directory; partial/previous bundles are never overwritten')
output.mkdir(parents=True)
try:
if os.name=='nt':
principal=subprocess.run(['whoami'],capture_output=True,text=True,check=True).stdout.strip()
secured=subprocess.run(['icacls',str(output),'/inheritance:r','/grant:r',principal+':(OI)(CI)F','*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F'],capture_output=True)
if secured.returncode:raise ValueError('Cannot restrict private migration directory permissions')
with connection.cursor() as cursor:
cursor.execute('SET SESSION TRANSACTION READ ONLY');idle(cursor)
cursor.execute("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan' AND TABLE_TYPE='BASE TABLE' ORDER BY TABLE_NAME")
tables=[r[0] for r in cursor.fetchall()]
if not tables or any(not re.fullmatch(r'[A-Za-z0-9_]+',t) for t in tables):raise ValueError('Unexpected source table inventory')
counts={}
for t in tables:cursor.execute(f'SELECT COUNT(*) FROM `{t}`');counts[t]=cursor.fetchone()[0]
cursor.execute('SELECT id,storage,config FROM infra_file_config WHERE deleted=0')
clients=cursor.fetchall()
if len(clients)!=1 or clients[0][1]!=10:raise ValueError('This migration requires the current single LOCAL file client; export other object storage separately before proceeding')
file_client=json.loads(clients[0][2]);uploads=Path(file_client['basePath']).resolve()
if output.is_relative_to(uploads):raise ValueError('Bundle output must be outside source uploads')
roots={str(args.artifacts.resolve()).replace('\\','/'):'artifacts',str(uploads).replace('\\','/'):'uploads'}
missing=[]
for table in ('lab_artifact_file','lab_dimension_file'):
cursor.execute(f"SELECT id,storage_path FROM `{table}` WHERE storage_path IS NOT NULL AND storage_path<>''")
for identifier,path in cursor.fetchall():
normalized=path.replace('\\','/')
matched=next(((root,kind) for root,kind in roots.items() if normalized.lower().startswith(root.lower()+'/')),None)
if matched is None:
marker='/.local/artifacts/'
offset=normalized.lower().find(marker)
if offset<0:raise ValueError('Unmapped historical file path; review it before exporting: '+normalized)
root=normalized[:offset]+marker[:-1];roots[root]='artifacts';matched=(root,'artifacts')
root,kind=matched;relative=normalized[len(root)+1:]
if '..' in Path(relative).parts or Path(relative).is_absolute():raise ValueError('Unsafe source storage path')
source=(args.artifacts if kind=='artifacts' else uploads)/relative
if not source.is_file():missing.append(dict(table=table,id=str(identifier),sourcePath=path,targetRelative=kind+'/'+relative))
dump=Path(args.mysqldump).resolve()
if not dump.is_file():raise ValueError('Provide the official Windows mysqldump executable')
def quoted(v):return '"'+str(v).replace('\\','\\\\').replace('"','\\"')+'"'
defaults=output/'client-private.cnf'
defaults.write_text('[client]\nhost='+quoted(mysql['host'])+'\nport='+str(mysql.get('port',3306))+'\nuser='+quoted(mysql['user'])+'\npassword='+quoted(mysql['password'])+'\n',encoding='utf-8')
try:
command=[str(dump),'--defaults-extra-file='+str(defaults),'--single-transaction','--skip-lock-tables','--skip-add-drop-table','--no-tablespaces','--set-gtid-purged=OFF','--hex-blob','--routines','--events','--triggers','--column-statistics=0','--default-character-set=utf8mb4','--result-file='+str(output/'database.sql'),'am-freescan']
result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if result.returncode:raise ValueError('mysqldump failed; check source client compatibility and credentials privately')
finally:defaults.unlink(missing_ok=True)
copy_tree(args.artifacts,output/'artifacts');copy_tree(uploads,output/'uploads')
private=output/'private';private.mkdir()
if runtime.get('adminPassword'):(private/'login.json').write_text(json.dumps(dict(adminPassword=runtime['adminPassword'])),encoding='utf-8')
scanner=ROOT/'.local/scanner-private.yaml'
if scanner.exists():
shutil.copy2(scanner,private/'source-scanner-private.yaml')
import yaml
cfg=yaml.safe_load(scanner.read_text(encoding='utf-8-sig')) or {}
tls=cfg.get('cmvr',{}).get('quic',{}).get('tls',{})
for key in ('certificate','private-key','client-ca'):
if tls.get(key):
p=Path(tls[key]);p=p if p.is_absolute() else ROOT/p
if p.is_file():shutil.copy2(p,private/(key+'.pem'))
manifest=dict(format='am-freescan-migration-v1',sourceDatabase='am-freescan',sourceConfirmedStopped=True,
sourceArtifactRoot=str(args.artifacts.resolve()),sourceUploadRoot=str(uploads),sourceFileDomain=file_client['domain'],tableCounts=counts,
storageRoots=roots,missingReferences=missing)
manifest['files']=[dict(path=p.relative_to(output).as_posix(),size=p.stat().st_size,sha256=digest(p)) for p in sorted(output.rglob('*')) if p.is_file()]
(output/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(dict(exported=True,tables=len(tables),files=len(manifest['files']),missingHistoricalFiles=len(missing),bundle=str(output),containsPrivateData=True)))
finally:connection.close()
def check_bundle(directory):
if reparse(directory):raise ValueError('Bundle root must not be a link or junction')
directory=directory.resolve()
inventory=set()
for entry in directory.rglob('*'):
if reparse(entry):raise ValueError('Bundle contains a link or junction')
if entry.is_file():inventory.add(entry.relative_to(directory).as_posix())
manifest=json.loads((directory/'manifest.json').read_text(encoding='utf-8-sig'))
if manifest.get('format')!='am-freescan-migration-v1' or manifest.get('sourceDatabase')!='am-freescan' or not manifest.get('sourceConfirmedStopped'):raise ValueError('Unrecognized migration bundle')
paths=set()
for item in manifest['files']:
name=item['path'];path=(directory/name).resolve()
if path.is_relative_to(directory) is False or name!=path.relative_to(directory).as_posix() or name in paths:raise ValueError('Unsafe bundle path')
paths.add(name)
if not path.is_file() or path.stat().st_size!=item['size'] or digest(path)!=item['sha256']:raise ValueError('Bundle checksum failed: '+name)
if 'database.sql' not in paths:raise ValueError('Bundle has no database dump')
if inventory != paths | {'manifest.json'}:raise ValueError('Bundle contains unverified extra or missing files')
roots=manifest.get('storageRoots',{})
if not roots or any(kind not in ('artifacts','uploads') or not Path(root).is_absolute() or '..' in Path(root).parts for root,kind in roots.items()):raise ValueError('Bundle storage mapping is missing or invalid')
return manifest
def import_bundle(args):
if not args.confirm_source_stopped:raise ValueError('Confirm the source remains stopped before enabling the new instance')
cfg=standalone.configuration(args.config);manifest=check_bundle(args.package)
with socket.socket() as probe:
if probe.connect_ex(('127.0.0.1',48090))==0:raise ValueError('Stop the target backend before importing')
with standalone.connect(cfg) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='am-freescan'")
if cursor.fetchone()[0]:raise ValueError('Target must be empty: never run Bootstrap before historical migration, and never overwrite an existing database')
home=Path(cfg['dataRoot']).resolve()
for name in ('artifacts','uploads'):
destination=home/name
if destination.exists() and any(destination.iterdir()):raise ValueError('Target data directory is not empty: '+name)
# Reject database/user administration outside the designated schema, including executable comments.
with (args.package/'database.sql').open(encoding='utf-8-sig') as sql:
for line in sql:
command=re.sub(r'^/\*!\d+\s*','',line.strip())
if re.match(r'(?i)^(?:CREATE|DROP)\s+DATABASE\b|^(?:GRANT|REVOKE)\b|^(?:CREATE|ALTER|DROP)\s+USER\b|^USE\b',command):raise ValueError('Dump contains database/user switching; export without --databases')
staging=home/'backups'/('migration-'+uuid.uuid4().hex+'.sql');shutil.copy2(args.package/'database.sql',staging)
compose=ROOT/'deploy/windows11/compose.yaml';env=ROOT/'.local/standalone/compose.env'
shell='MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql -uroot --binary-mode=1 am-freescan < /backup/'+staging.name
result=subprocess.run(['docker','compose','--env-file',str(env),'-f',str(compose),'exec','-T','mysql','sh','-c',shell],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if result.returncode:
(args.config.parent/'migration-error.log').write_bytes(result.stderr)
raise ValueError('Import stopped; preserve the partial instance and inspect private migration-error.log. Do not delete or reimport over it automatically')
for name in ('artifacts','uploads'):copy_tree(args.package/name,home/name)
mappings=[(old,str(home/kind)) for old,kind in manifest['storageRoots'].items()]
def remap(value):
if not value:return value
normalized=value.replace('\\','/')
for old,new in mappings:
old=old.replace('\\','/').rstrip('/')
if normalized.lower().startswith(old.lower()+'/'):
relative=normalized[len(old)+1:]
if '..' in Path(relative).parts or Path(relative).is_absolute():raise ValueError('Unsafe storage path in database')
return new.replace('\\','/')+'/'+relative
raise ValueError('Unmapped storage path requires manual review: '+value)
with standalone.connect(cfg) as connection:
with connection.cursor() as cursor:
for table,expected in manifest['tableCounts'].items():
if not re.fullmatch(r'[A-Za-z0-9_]+',table):raise ValueError('Invalid table name')
cursor.execute(f'SELECT COUNT(*) FROM `{table}`')
if cursor.fetchone()[0]!=expected:raise ValueError('Row-count mismatch: '+table)
connection.begin()
for table in ('lab_artifact_file','lab_dimension_file'):
cursor.execute(f'SELECT id,storage_path FROM `{table}` WHERE storage_path IS NOT NULL AND storage_path<>\'\'')
for identifier,path in cursor.fetchall():cursor.execute(f'UPDATE `{table}` SET storage_path=%s WHERE id=%s',(remap(path),identifier))
cursor.execute('SELECT id,config FROM infra_file_config WHERE storage=10')
for identifier,text in cursor.fetchall():
value=json.loads(text);value['basePath']=cfg['uploadRoot'];value['domain']=cfg['publicBaseUrl']
cursor.execute('UPDATE infra_file_config SET config=%s WHERE id=%s',(json.dumps(value),identifier))
for table,column in (('infra_file','url'),('lab_artifact_file','file_url')):
cursor.execute(f'SELECT id,`{column}` FROM `{table}` WHERE `{column}` IS NOT NULL')
for identifier,url in cursor.fetchall():
if url and url.startswith(manifest['sourceFileDomain'].rstrip('/')+'/'):
cursor.execute(f'UPDATE `{table}` SET `{column}`=%s WHERE id=%s',(cfg['publicBaseUrl'].rstrip('/')+url[len(manifest['sourceFileDomain'].rstrip('/')):],identifier))
for table in ('system_oauth2_access_token','system_oauth2_refresh_token'):cursor.execute(f'DELETE FROM `{table}`')
cursor.execute("UPDATE iot_robot SET connect_status='0'");cursor.execute("UPDATE iot_device SET online_status='0'")
for key,value in (('owner',standalone.OWNER),('instance',cfg['instanceId'])):
cursor.execute(f'INSERT INTO `{source_bootstrap.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',(key,value))
connection.commit()
login=args.package/'private/login.json'
if login.exists():
cfg['adminPassword']=json.loads(login.read_text(encoding='utf-8'))['adminPassword']
args.config.write_text(json.dumps(cfg,ensure_ascii=False,indent=2),encoding='utf-8')
(args.config.parent/'initial-admin.txt').write_text('迁移保留原账号及密码;初始化生成的新密码不适用。请使用源系统有效账号。\n',encoding='utf-8')
print(json.dumps(dict(imported=True,tablesVerified=len(manifest['tableCounts']),filesVerified=len(manifest['files']),missingHistoricalFiles=len(manifest.get('missingReferences',[])),runtimeConnectionsReset=True,redisSessionsNotMigrated=True)))
def main():
parser=argparse.ArgumentParser(description=__doc__);sub=parser.add_subparsers(dest='mode',required=True)
export=sub.add_parser('export');export.add_argument('--source-runtime',type=Path,default=ROOT/'.local/runtime.json');export.add_argument('--artifacts',type=Path,default=ROOT/'.local/artifacts');export.add_argument('--output',type=Path,required=True);export.add_argument('--mysqldump',required=True);export.add_argument('--confirm-source-stopped',action='store_true')
restore=sub.add_parser('import');restore.add_argument('--config',type=Path,required=True);restore.add_argument('--package',type=Path,required=True);restore.add_argument('--confirm-source-stopped',action='store_true')
verify=sub.add_parser('verify');verify.add_argument('--package',type=Path,required=True)
args=parser.parse_args()
if args.mode=='export':export_bundle(args)
elif args.mode=='import':import_bundle(args)
else:manifest=check_bundle(args.package);print(json.dumps(dict(verified=True,files=len(manifest['files']))))
if __name__=='__main__':
try:main()
except Exception as error:
print('Migration stopped: '+(str(error) if isinstance(error,ValueError) else type(error).__name__+'; inspect private configuration without printing credentials'),file=sys.stderr);raise SystemExit(1)