feat: automate production updates and final full-data handoff

This commit is contained in:
lixiaolong 2026-11-12 17:54:32 +08:00
parent c903364fa2
commit 44653a2a43
36 changed files with 1008 additions and 102 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Unified diff context contains intentional single-space lines; preserve patch bytes.
deploy/quic/*.patch -text -whitespace

View File

@ -1,5 +1,9 @@
# AM FreeScan 开发约定
- 2026-11-12 用户确认正式环境已按早先包独立安装、尚未录入业务;安排最后一次源端全量同步后,正式环境作为唯一业务数据源。此次不备份目标业务数据,使用新空数据卷/目录导入并保留旧卷;最终包等用户确认暂停操作后再生成。后续正式环境仅通过公网Git main和deploy/windows11/update.ps1更新代码及批准的增量结构,不重复导入开发数据,不覆盖现场私有配置或删除数据卷。公网仓库为https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git。
- 2026-11-12 用户要求实时预览正常收帧时不逐帧查询扫描服务状态,也不由前端持续轮询SDK状态;首次连接与断流恢复时重新查询并核对设备会话/工程。收帧期间保留平台本地执行、录入记录和设备绑定校验;预览连接不下发停止、断开或重连设备命令。
- 2026-11-11 用户要求所有设备组件的默认业务等待统一为120秒,前端可修改并由后端尊重显式值;旋转底座、扫描仪、机械臂、AGV与动作队列每步均适用,取消旧45秒上限和自由标定固定5秒规则。当前用例草稿中的显式业务超时按用户授权统一120秒,之后新填的自定义值不自动覆盖;冻结版本及历史执行不改写。队列总等待仍累加每步时间,边端0值语义和30分钟上限按协议保留。HTTP回执预留10秒,回零节点时限不得短于服务端等待并预留回执时间;连接建立、心跳、采样周期、画面流和清理线程收敛期限不属于业务操作超时。禁止自动重发超时运动,仍按实际停止确认释放。
- 2026-11-10 用户明确授权 QUIC 短暂断开恢复规则:新动作最多等待5秒重连,只在重新在线且设备校验通过后下发;不重发已经执行的动作。QUIC单独断开不取消独立的在途gRPC调用;地址、端口或边端bootId变化仍使旧通道失效。仅状态查询和停止清理可使用同一已登记设备的最后地址,不能用于新运动;停止回执与实际停止状态均确认后才释放占用,未知或失败保留。自动验证仅用本机模拟服务,不执行现场运动。

View File

@ -12,7 +12,7 @@ public class RotaryBaseProperties {
public com.cmvr.resource.service.ServiceEndpoint connection() {var current=connectionOverride;return current==null?new com.cmvr.resource.service.ServiceEndpoint(host,port):current;}
public String getHost() {return connection().host();}
public Integer getPort() {return connection().port();}
private String host="192.168.0.203";
private String host="";
private Integer port=50052;
private String robotId="am-freescan-rotary-base-station-001";
private String deviceId="aima_motor";

View File

@ -101,17 +101,20 @@ public class ScannerMonitoringService {
}
public JsonNode status(JsonNode binding) {
if(binding==null)throw new ScannerException("project_not_bound","等待本次执行建立扫描工程关联",409);
client.requireConfigured();
if(!binding.path("endpoint").asText().equals(client.endpointKey())
||!binding.path("robotId").asText().equals(settings.getRobotId())
||!binding.path("deviceId").asText().equals(settings.getDeviceId()))throw new ScannerException("device_changed","扫描服务或设备身份已变更,暂停展示画面",409);
requireBinding(binding);
JsonNode status=scanner.get(ScannerOperation.STATUS,null);
requireProject(status);
if(!binding.path("sessionId").asText().equals(status.path("sessionId").asText())
||!binding.path("projectId").asText().equals(status.path("projectId").asText()))throw new ScannerException("project_changed","扫描会话或工程已切换,当前画面不属于这次执行",409);
return status;
}
private void requireBinding(JsonNode binding) {
if(binding==null)throw new ScannerException("project_not_bound","等待本次执行建立扫描工程关联",409);
client.requireConfigured();
if(!binding.path("endpoint").asText().equals(client.endpointKey())
||!binding.path("robotId").asText().equals(settings.getRobotId())
||!binding.path("deviceId").asText().equals(settings.getDeviceId()))throw new ScannerException("device_changed","扫描服务或设备身份已变更,暂停展示画面",409);
}
public record Frame(byte[] bytes,Map<String,List<String>> headers) {}
public ScannerPreviewStream stream(JsonNode binding) {
status(binding);
@ -120,7 +123,9 @@ public class ScannerMonitoringService {
catch(RuntimeException invalid){try{source.close();}catch(IOException ignored){}throw invalid;}
}
public long streamSequence(JsonNode binding,Frame frame) {
status(binding); // Validate the project after reading each complete frame, before publishing it.
// The remote session/project is checked when opening (and reopening) the stream.
// Frames only validate the local device binding; never query the SDK per frame.
requireBinding(binding);
try{return Long.parseLong(header(frame.headers(),"x-frame-sequence"));}
catch(Exception invalid){throw new ScannerException("invalid_frame","扫描流缺少有效帧编号",502);}
}

View File

@ -42,7 +42,7 @@ public class TtsSynthesizeTaskServiceImpl implements ITtsSynthesizeTaskService {
@Autowired
private MinioService minioService;
@org.springframework.beans.factory.annotation.Value("${tts.external-api.url:http://192.168.1.101:8080/tts/synthesize}")
@org.springframework.beans.factory.annotation.Value("${tts.external-api.url:}")
private String externalTtsUrl;
@org.springframework.beans.factory.annotation.Value("${minio.bucketName:cmvr-iot}")
@ -266,6 +266,9 @@ public class TtsSynthesizeTaskServiceImpl implements ITtsSynthesizeTaskService {
*/
private void callExternalTtsApi(TtsSynthesizeTask task) {
try {
if (externalTtsUrl == null || externalTtsUrl.isBlank()) {
throw new IllegalStateException("语音合成服务未配置,请设置 tts.external-api.url");
}
// 更新状态为合成中
task.setStatus("1");
ttsTaskMapper.updateTtsTask(task);

View File

@ -13,6 +13,7 @@ public class RotaryBaseResourcesTest {
ResourceRobotMapper robots=mock(ResourceRobotMapper.class);ResourceDeviceMapper devices=mock(ResourceDeviceMapper.class);ResourceRobot robot;
RotaryBaseResourceSynchronizer resources;
@Before public void setup() {
settings.setHost("127.0.0.1");
robot=new ResourceRobot();robot.setId("robot-record");robot.setArchivedStatus("0");when(robots.selectByRobotIdentity(settings.getRobotId())).thenReturn(robot);
when(devices.selectByIdentity(settings.getRobotId(),settings.getDeviceId())).thenReturn(List.of());
resources=new RotaryBaseResourceSynchronizer(settings,client,robots,devices);

View File

@ -59,14 +59,19 @@ public class ScannerMonitoringTest {
assertThrows(ScannerException.class,()->monitoring.image(bound));
verify(scanner,never()).submit(any(),any(),anyString(),anyString());
}
@Test public void continuousFramesAreBoundToCurrentProjectAndRequireSequence() throws Exception {
@Test public void continuousFramesUseLocalBindingAndReconnectRevalidatesProject() throws Exception {
var bound=capture();
clearInvocations(scanner);
var frame=new ScannerMonitoringService.Frame(new byte[]{1},Map.of("X-Frame-Sequence",List.of("11")));
assertEquals(11,monitoring.streamSequence(bound,frame));
for(int i=0;i<100;i++)assertEquals(11,monitoring.streamSequence(bound,frame));
assertEquals("invalid_frame",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,new ScannerMonitoringService.Frame(new byte[0],Map.of()))).scannerCode);
verifyNoInteractions(scanner);
settings.setPort(18889);
assertEquals("device_changed",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,frame)).scannerCode);
settings.setPort(18888);
when(scanner.get(ScannerOperation.STATUS,null)).thenReturn(status("S1","other-project"));
assertEquals("project_changed",assertThrows(ScannerException.class,()->monitoring.streamSequence(bound,frame)).scannerCode);
assertThrows(ScannerException.class,()->monitoring.stream(bound));
verify(scanner).get(ScannerOperation.STATUS,null);
verify(scanner,never()).binary(ScannerOperation.PREVIEW_STREAM,null);
}
@Test public void snapshotAndItsFilesBelongToOneExecutionOnly() {

View File

@ -163,7 +163,7 @@ public class DimensionService {
long executionId=num(execution.get("id"));
for(var asset:scannerArchives.list(executionId)){
String name=asset.path("name").asText();if(!name.toLowerCase(Locale.ROOT).matches(".*\\.(ply|stl)$"))continue;
candidates.add(map("id","scanner:"+executionId+":"+asset.path("fileId").asText(),"file_id",asset.path("fileId").asText(),"file_name",name,"execution_id",executionId,"size_bytes",asset.path("bytes").asLong(),"source_type","SCANNER_ARCHIVE"));
candidates.add(map("id","scanner:"+executionId+":"+asset.path("fileId").asText(),"file_id",asset.path("fileId").asText(),"file_name",name,"execution_id",executionId,"size_bytes",asset.path("bytes").asLong(),"create_time",asset.path("capturedAt").asLong(),"source_type","SCANNER_ARCHIVE"));
}
}
return map("task",task,"units",unitSummaries(taskId),"case",state,"stage",stage(state),"files",fileList,"deliveries",outputs,"scanFiles",candidates,"events",rows("SELECT id,unit_id,event_type,detail_json,creator,create_time FROM lab_dimension_event WHERE task_id=? AND tenant_id=? ORDER BY id DESC LIMIT 200",taskId,tenant()),"uploadMaxBytes",files.uploadLimit(),"comparisonIntegrated",true,"comparisonConnected",inspectionGateway!=null&&inspectionGateway.knownAvailable());

View File

@ -490,7 +490,7 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
}
@Override public List<Map<String,Object>> fixtureOptions(Long taskId,BigDecimal length,BigDecimal width,BigDecimal height){return fixtureOptions(taskId,length,width,height,null);}
@Override public List<Map<String,Object>> fixtureOptions(Long taskId,BigDecimal length,BigDecimal width,BigDecimal height,BigDecimal weight){primary();required(taskId,false);ScanTaskConfigDO c=config(taskId);if(weight!=null)c.setWeightKg(weight);return recommend(c,length==null?c.getLengthMm():length,width==null?c.getWidthMm():width,height==null?c.getHeightMm():height);}
@Override public List<Map<String,Object>> fixtureOptions(Long taskId,BigDecimal length,BigDecimal width,BigDecimal height,BigDecimal weight){primary();required(taskId,false);ScanTaskConfigDO c=config(taskId);c.setWeightKg(weight);return recommend(c,length,width,height);}
@Override @Transactional(rollbackFor=Exception.class)
public void updateFixtureRange(ScanTaskRequests.FixtureRange request){
primary();ScanFixtureDO f=fixtures.selectById(request.getFixtureId());if(f==null)throw invalidParamException("夹具不存在");
@ -677,18 +677,23 @@ public class ScanOnlyTaskServiceImpl implements ScanOnlyTaskService {
}
private List<Map<String,Object>> recommend(ScanTaskConfigDO c,BigDecimal length,BigDecimal width,BigDecimal height){
List<Map<String,Object>> result=new ArrayList<>();
boolean complete=positive(length)&&positive(width)&&positive(height);
for(ScanFixtureDO f:fixtures.selectList(ScanFixtureDO::getStatus,"ENABLED")){
String reason=null;
if(!fixtureApplicable(f.getId(),c.getTaskId()))reason="夹具的适用样品或零件号不包含当前任务样品";
else if(!positive(length)||!positive(width)||!positive(height))reason="请补充样件长宽高(mm)";
else if(!positive(f.getMaxLengthMm())||!positive(f.getMaxWidthMm())||!positive(f.getMaxHeightMm()))reason="夹具未配置可装夹尺寸范围";
else if(length.compareTo(f.getMaxLengthMm())>0||width.compareTo(f.getMaxWidthMm())>0||height.compareTo(f.getMaxHeightMm())>0)reason="样件尺寸超过夹具范围(按确认装夹方向比较长宽高)";
else if((length!=null&&!positive(length))||(width!=null&&!positive(width))||(height!=null&&!positive(height)))reason="已填写的样件尺寸必须大于0";
else if(exceedsFixtureLimit(length,f.getMaxLengthMm())||exceedsFixtureLimit(width,f.getMaxWidthMm())||exceedsFixtureLimit(height,f.getMaxHeightMm()))reason="样件尺寸超过夹具范围(按确认装夹方向比较长宽高)";
else if(complete&&(!positive(f.getMaxLengthMm())||!positive(f.getMaxWidthMm())||!positive(f.getMaxHeightMm())))reason="夹具未配置可装夹尺寸范围,无法按尺寸匹配";
else if(c.getWeightKg()!=null&&!positive(c.getWeightKg()))reason="已填写的样件重量必须大于0";
else if(c.getWeightKg()!=null&&f.getMaxWeightKg()!=null&&c.getWeightKg().compareTo(f.getMaxWeightKg())>0)reason="样件重量超过夹具承重";
result.add(map("id",f.getId(),"fixtureCode",f.getFixtureCode(),"fixtureName",f.getFixtureName(),"fixtureSize",f.getFixtureSize(),"compatible",reason==null,"reason",reason==null?"尺寸与承重匹配,请确认装夹":reason,
boolean recommended=reason==null&&complete;
String basis=complete?"尺寸匹配,请现场确认装夹及承重":"尺寸未填全,可手动选择,请现场确认装夹及承重";
result.add(map("id",f.getId(),"fixtureCode",f.getFixtureCode(),"fixtureName",f.getFixtureName(),"fixtureSize",f.getFixtureSize(),"compatible",reason==null,"recommended",recommended,"reason",reason==null?basis:reason,
"maxLengthMm",f.getMaxLengthMm(),"maxWidthMm",f.getMaxWidthMm(),"maxHeightMm",f.getMaxHeightMm(),"maxWeightKg",f.getMaxWeightKg()));
}
result.sort(Comparator.comparing(row->!Boolean.TRUE.equals(row.get("compatible"))));return result;
}
private static boolean exceedsFixtureLimit(BigDecimal actual,BigDecimal limit){return actual!=null&&positive(limit)&&actual.compareTo(limit)>0;}
private boolean fixtureApplicable(Long fixtureId,Long taskId){
List<LabFixtureApplicableDO> restrictions=fixtureApplicables.selectListByFixtureId(fixtureId);if(restrictions.isEmpty())return true;
List<LabTaskSampleDO> requested=taskSamples.selectListByTaskId(taskId);if(requested.isEmpty())return false;

View File

@ -14,14 +14,14 @@ spring:
strict: true
datasource:
master:
url: ${AM_FREESCAN_DB_URL}
username: ${AM_FREESCAN_DB_USER}
url: ${AM_FREESCAN_DB_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: ${AM_FREESCAN_REDIS_HOST}
host: ${AM_FREESCAN_REDIS_HOST:127.0.0.1}
port: ${AM_FREESCAN_REDIS_PORT:6379}
database: ${AM_FREESCAN_REDIS_DATABASE}
database: ${AM_FREESCAN_REDIS_DATABASE:15}
password: ${AM_FREESCAN_REDIS_PASSWORD}
boot:
admin:
@ -33,6 +33,13 @@ spring:
key-prefix: '${spring.application.name}:'
cmvr:
scanner:
host: ${AM_FREESCAN_SCANNER_HOST:}
port: ${AM_FREESCAN_SCANNER_PORT:18888}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
rotary-base:
host: ${AM_FREESCAN_ROTARY_BASE_HOST:}
port: ${AM_FREESCAN_ROTARY_BASE_PORT:50052}
quic:
# 启用时必须提供部署主机的证书和私钥文件路径。
enabled: ${CMVR_QUIC_ENABLED:false}

View File

@ -1,6 +1,6 @@
cmvr:
rotary-base:
host: ${AM_FREESCAN_ROTARY_BASE_HOST:192.168.0.203}
host: ${AM_FREESCAN_ROTARY_BASE_HOST:}
port: ${AM_FREESCAN_ROTARY_BASE_PORT:50052}
robot-id: ${AM_FREESCAN_ROTARY_BASE_ROBOT_ID:am-freescan-rotary-base-station-001}
device-id: ${AM_FREESCAN_ROTARY_BASE_DEVICE_ID:aima_motor}
@ -14,9 +14,9 @@ cmvr:
- ${AM_FREESCAN_ROTARY_BASE_ROBOT_ID:am-freescan-rotary-base-station-001}
scanner:
# 通用模板随应用打包;本地由私有 YAML 覆盖,生产从环境变量读取。
host: ${AM_FREESCAN_SCANNER_HOST:192.168.0.112}
host: ${AM_FREESCAN_SCANNER_HOST:}
port: ${AM_FREESCAN_SCANNER_PORT:18888}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:00da1ea59c601b3ed292879e75d22b41d9bbaeaa02c2fbc3f97f9e191fe0be2d}
api-key: ${AM_FREESCAN_SCANNER_API_KEY:}
robot-id: ${AM_FREESCAN_SCANNER_ROBOT_ID:am-freescan-station-001}
device-id: ${AM_FREESCAN_SCANNER_DEVICE_ID:am-freescan-scanner-001}
connect-timeout-ms: 5000
@ -28,7 +28,7 @@ spring:
application:
name: am-freescan
profiles:
active: local
active: ${SPRING_PROFILES_ACTIVE:prod}
main:
allow-circular-references: true
servlet:

View File

@ -3,8 +3,8 @@ NODE_ENV=production
VITE_DEV=false
# 请求路径
VITE_BASE_URL=http://localhost:48090
# 生产通过同一站点反向代理访问接口,兼容本机和局域网客户端。
VITE_BASE_URL=
# 文件上传类型:server - 后端上传, client - 前端直连上传,仅支持S3服务
VITE_UPLOAD_TYPE=server

View File

@ -62,6 +62,7 @@ export interface FixtureOption {
fixtureName: string
fixtureSize?: string
compatible: boolean
recommended?: boolean
reason: string
maxLengthMm?: number
maxWidthMm?: number

View File

@ -3,6 +3,12 @@
@use './theme.scss';
@use 'element-plus/theme-chalk/dark/css-vars.css';
.required-confirmation-mark {
color: var(--el-color-danger);
margin-right: 4px;
font-weight: 600;
}
.reset-margin [class*='el-icon'] + span {
margin-left: 2px !important;
}

View File

@ -54,9 +54,33 @@
:closable="false"
/>
<div ref="sectionAnchor" />
<nav ref="sectionNavigation" class="workbench-switcher" role="tablist" aria-label="任务工作台">
<div class="section-buttons"><button v-for="section in sections" :key="section.value" type="button" role="tab" :aria-selected="tab === section.value" :tabindex="tab === section.value ? 0 : -1" :class="{ selected: tab === section.value }" @click="switchSection(section.value)" @keydown.right.prevent="nextSection(1)" @keydown.left.prevent="nextSection(-1)">{{ section.label }}</button></div>
<el-button text size="small" @click="pageStart?.scrollIntoView({ block: 'start', behavior: 'smooth' })">回到顶部</el-button>
<nav
ref="sectionNavigation"
class="workbench-switcher"
role="tablist"
aria-label="任务工作台"
>
<div class="section-buttons"
><button
v-for="section in sections"
:key="section.value"
type="button"
role="tab"
:aria-selected="tab === section.value"
:tabindex="tab === section.value ? 0 : -1"
:class="{ selected: tab === section.value }"
@click="switchSection(section.value)"
@keydown.right.prevent="nextSection(1)"
@keydown.left.prevent="nextSection(-1)"
>{{ section.label }}</button
></div
>
<el-button
text
size="small"
@click="pageStart?.scrollIntoView({ block: 'start', behavior: 'smooth' })"
>回到顶部</el-button
>
</nav>
<el-tabs v-model="tab" class="workbench-nav">
<el-tab-pane v-if="data.task.processType === 'SCAN_ONLY'" label="扫描准备" name="prepare" />
@ -123,7 +147,11 @@
><el-table :data="data.scanFiles" size="small"
><el-table-column label="文件" prop="file_name" /><el-table-column
label="来源执行"
prop="execution_id" /><el-table-column label="操作" width="190"
prop="execution_id" /><el-table-column label="生成时间" width="185"
><template #default="{ row }">{{
formatNullableDate(row.create_time)
}}</template></el-table-column
><el-table-column label="操作" width="190"
><template #default="{ row }"
><el-button
link
@ -157,6 +185,10 @@
><template #default="{ row }">{{
row.source_type === 'SCAN_EXPORT' ? '扫描执行归档' : '本地上传'
}}</template></el-table-column
><el-table-column label="上传/归档时间" width="185"
><template #default="{ row }">{{
formatNullableDate(row.create_time)
}}</template></el-table-column
><el-table-column label="校验值" prop="sha256" show-overflow-tooltip /><el-table-column
label="操作"
width="145"
@ -185,7 +217,22 @@
selectedName(r.key) || '尚未选用'
}}</el-descriptions-item></el-descriptions
>
<ComparisonPanel ref="comparisonPanel" :task-id="taskId" :unit-id="String(data.case.unit_id || '0')" :revision="data.case.revision" :ready="allSelected" :dirty="dirty" :source-changed="data.stage === 'SCAN_CHANGED'" :active="tab === 'delivery'" :inputs="{modelId:data.case.model_id,drawingId:data.case.drawing_id,cloudId:data.case.cloud_id}" @changed="load()" />
<ComparisonPanel
ref="comparisonPanel"
:task-id="taskId"
:unit-id="String(data.case.unit_id || '0')"
:revision="data.case.revision"
:ready="allSelected"
:dirty="dirty"
:source-changed="data.stage === 'SCAN_CHANGED'"
:active="tab === 'delivery'"
:inputs="{
modelId: data.case.model_id,
drawingId: data.case.drawing_id,
cloudId: data.case.cloud_id
}"
@changed="load()"
/>
<div class="actions"
><el-button
:loading="busy"
@ -225,7 +272,11 @@
></el-table-column
><el-table-column label="来源" min-width="160"
><template #default="{ row }"
>{{ String(row.external_no || '').startsWith('CMP-') ? '本机计算服务' : '人工登记外部结果' }}<div class="secondary">{{ row.reason }}</div></template
>{{
String(row.external_no || '').startsWith('CMP-')
? '本机计算服务'
: '人工登记外部结果'
}}<div class="secondary">{{ row.reason }}</div></template
></el-table-column
><el-table-column label="成果" min-width="190"
><template #default="{ row }"
@ -319,6 +370,7 @@
><el-form-item label="PDF报告" required
><input type="file" accept=".pdf" @change="(e) => pickResult(e, 'pdf')" /></el-form-item
><el-checkbox v-model="result.checked"
><span class="required-confirmation-mark" aria-hidden="true">*</span
>已核对这两个文件与本次选用输入及当前样件一致</el-checkbox
></el-form
>
@ -361,6 +413,7 @@
</template>
<script setup lang="ts">
import * as Api from '@/api/lab/dimension'
import { formatNullableDate } from '@/utils/formatTime'
import { checkPermi } from '@/utils/permission'
import { useUserStore } from '@/store/modules/user'
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
@ -396,11 +449,34 @@ const scanWorkbench = ref<any>(),
scanView = ref('prepare'),
scanSummary = ref<any>()
const isScanSection = computed(() => ['prepare', 'scan'].includes(tab.value))
const sectionNavigation=ref<HTMLElement>()
const sectionAnchor=ref<HTMLElement>(),pageStart=ref<HTMLElement>()
const sections=computed(()=>[...(data.value?.task.processType==='SCAN_ONLY'?[{value:'prepare',label:'扫描准备'},{value:'scan',label:'扫描执行'}]:[]),{value:'materials',label:'比对资料'},{value:'delivery',label:'比对与成果'},{value:'trace',label:'操作追溯'}])
async function switchSection(value:string){if(tab.value===value)return;tab.value=value;await nextTick();sectionAnchor.value?.scrollIntoView({block:'start',behavior:'instant'})}
async function nextSection(offset:number){const list=sections.value,index=list.findIndex(section=>section.value===tab.value);await switchSection(list[(index+offset+list.length)%list.length].value);sectionNavigation.value?.querySelector<HTMLButtonElement>('[aria-selected="true"]')?.focus({preventScroll:true})}
const sectionNavigation = ref<HTMLElement>()
const sectionAnchor = ref<HTMLElement>(),
pageStart = ref<HTMLElement>()
const sections = computed(() => [
...(data.value?.task.processType === 'SCAN_ONLY'
? [
{ value: 'prepare', label: '扫描准备' },
{ value: 'scan', label: '扫描执行' }
]
: []),
{ value: 'materials', label: '比对资料' },
{ value: 'delivery', label: '比对与成果' },
{ value: 'trace', label: '操作追溯' }
])
async function switchSection(value: string) {
if (tab.value === value) return
tab.value = value
await nextTick()
sectionAnchor.value?.scrollIntoView({ block: 'start', behavior: 'instant' })
}
async function nextSection(offset: number) {
const list = sections.value,
index = list.findIndex((section) => section.value === tab.value)
await switchSection(list[(index + offset + list.length) % list.length].value)
sectionNavigation.value
?.querySelector<HTMLButtonElement>('[aria-selected="true"]')
?.focus({ preventScroll: true })
}
function updateScanSummary(value: any) {
scanSummary.value = value
}
@ -762,15 +838,52 @@ onBeforeUnmount(() => {
.workbench-nav {
margin-top: 0;
}
.task-workbench { overflow: visible; }
.workbench-switcher { position:sticky;top:0;z-index:8;display:flex;align-items:center;justify-content:space-between;gap:12px;background:var(--el-bg-color);border-bottom:1px solid var(--el-border-color-lighter);margin-top:18px;margin-bottom:16px;padding:4px 0; }
.section-buttons { display:flex;gap:20px;overflow-x:auto;min-width:0; }
.section-buttons button { flex-shrink:0;border:0;border-bottom:2px solid transparent;background:none;color:var(--el-text-color-regular);padding:12px 2px;font-size:14px;cursor:pointer; }
.section-buttons button.selected { color:var(--el-color-primary);border-bottom-color:var(--el-color-primary); }
.section-buttons button:focus-visible { outline:2px solid var(--el-color-primary);outline-offset:-2px; }
.workbench-switcher>.el-button { flex-shrink:0; }
.task-workbench {
overflow: visible;
}
.workbench-switcher {
position: sticky;
top: 0;
z-index: 8;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
background: var(--el-bg-color);
border-bottom: 1px solid var(--el-border-color-lighter);
margin-top: 18px;
margin-bottom: 16px;
padding: 4px 0;
}
.section-buttons {
display: flex;
gap: 20px;
overflow-x: auto;
min-width: 0;
}
.section-buttons button {
flex-shrink: 0;
border: 0;
border-bottom: 2px solid transparent;
background: none;
color: var(--el-text-color-regular);
padding: 12px 2px;
font-size: 14px;
cursor: pointer;
}
.section-buttons button.selected {
color: var(--el-color-primary);
border-bottom-color: var(--el-color-primary);
}
.section-buttons button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
.workbench-switcher > .el-button {
flex-shrink: 0;
}
.workbench-nav :deep(.el-tabs__header) {
display:none;
display: none;
}
.workbench-nav :deep(.el-tabs__item) {
height: 46px;

View File

@ -335,7 +335,8 @@
><el-button :disabled="!selectedTemplate || busy" @click="applyTemplate"
>载入模板</el-button
><el-button :disabled="busy" @click="importInput?.click()">导入计划</el-button
><el-button @click="router.push('/lab/dimension/inspection-templates')">模板维护</el-button
><el-button @click="router.push('/lab/dimension/inspection-templates')"
>模板维护</el-button
><input
ref="importInput"
type="file"
@ -402,8 +403,7 @@
><p>测量结果、表面色谱和报告下载集中展示,历史成果版本返回任务查看。</p></div
><div class="workspace-actions"
><el-button @click="switchPanel('plan')">调整计划与选点</el-button
><el-button @click="emit('history')">历史成果</el-button
></div
><el-button @click="emit('history')">历史成果</el-button></div
></div
><div class="result-metrics"
><div
@ -427,7 +427,8 @@
><el-button :loading="busy" @click="download('report_signed_chromatogram.pdf')"
>下载 PDF</el-button
><el-button :loading="busy" @click="download('result.zip')">下载结果包</el-button
><el-button :loading="busy" :disabled="!current.platform_job?.delivery_id" @click="download('platform-result.stl')">下载归档STL</el-button
><el-button :loading="busy" @click="download('aligned_colored.ply')"
>下载处理后点云</el-button
><el-button :loading="busy" @click="download('worker.log')">处理日志</el-button></div
><el-empty
v-else
@ -490,7 +491,12 @@
referrerpolicy="no-referrer"
title="三维检测报告预览"
class="inspect-report-frame"
/><iframe v-else-if="reportPdfUrl" :src="reportPdfUrl" title="归档PDF报告预览" class="inspect-report-frame" /><template #footer
/><iframe
v-else-if="reportPdfUrl"
:src="reportPdfUrl"
title="归档PDF报告预览"
class="inspect-report-frame"
/><template #footer
><el-button @click="download('report_signed_chromatogram.pdf')"
>下载 PDF</el-button
></template
@ -639,7 +645,10 @@ async function refresh() {
const result = await Api.state(props.recordId)
if (!active) return
current.value = result
if (result.engine_unavailable) { timer = setTimeout(refresh, 5000); return }
if (result.engine_unavailable) {
timer = setTimeout(refresh, 5000)
return
}
if (result.status === 'review' && panel.value === 'model') switchPanel('cleanup')
if (result.inputs) inputs.value = result.inputs
if (processing.value && !result.engine_unavailable) {
@ -928,7 +937,8 @@ function release() {
const previewReport = () =>
guard(async () => {
if (reportPdfUrl.value) URL.revokeObjectURL(reportPdfUrl.value)
reportPdfUrl.value = ''; reportHtml.value = ''
reportPdfUrl.value = ''
reportHtml.value = ''
try {
const blob = await Api.artifact(props.recordId, 'report_signed_chromatogram.html')
reportHtml.value = (await blob.text()).replace(/<nav[\s\S]*?<\/nav>/gi, '')
@ -968,7 +978,10 @@ async function confirmLeave() {
}
}
defineExpose({ confirmLeave })
watch(() => [current.value.status, current.value.report_revision], () => emit('changed'))
watch(
() => [current.value.status, current.value.report_revision],
() => emit('changed')
)
onMounted(async () => {
if (!panels.some((p) => p.id === panel.value)) panel.value = 'model'
window.addEventListener('keydown', escape)

View File

@ -20,14 +20,14 @@
</el-radio-group>
<template v-if="entryMode === 'local'">
<FrameworkLocalUpload v-if="visible" :key="generation" v-model="localFiles" :disabled="busy || loading" @busy="uploading = $event" />
<el-checkbox v-model="importConfirmed" :disabled="busy || loading" class="confirmation">已确认文件属于此夹具,允许保存为可复用框架点</el-checkbox>
<el-checkbox v-model="importConfirmed" :disabled="busy || loading" class="confirmation"><span class="required-confirmation-mark" aria-hidden="true">*</span>已确认文件属于此夹具,允许保存为可复用框架点</el-checkbox>
<div class="actions"><el-button :disabled="busy" @click="visible=false">关闭</el-button><el-button type="primary" :loading="busy" :disabled="!importConfirmed || !localFiles.length || uploading || busy || loading" @click="importFiles">{{ data.current?.id ? '导入并替换框架点' : '保存导入的框架点' }}</el-button></div>
</template>
<template v-else>
<el-alert v-if="definitionError" :title="definitionError" type="warning" :closable="false" />
<h4 v-if="definition.caseName">录入流程:{{ definition.caseName }}</h4>
<RuntimeAssignmentsEditor v-if="definition.caseName" ref="resourceEditor" v-model="assignments" :roles="roles" />
<el-checkbox v-model="confirmed">已确认当前为此夹具,现场已准备好,可开始框架点采集</el-checkbox>
<el-checkbox v-model="confirmed"><span class="required-confirmation-mark" aria-hidden="true">*</span>已确认当前为此夹具,现场已准备好,可开始框架点采集</el-checkbox>
<div class="actions"><el-button :disabled="busy" @click="visible=false">关闭</el-button><el-button type="primary" :loading="busy || definitionLoading" :disabled="!confirmed || busy || loading || !!definitionError || !definition.caseName" @click="start">{{ data.current?.id ? '重新录入框架点' : '开始录入框架点' }}</el-button></div>
</template>
</template>

View File

@ -17,9 +17,9 @@
<el-form label-position="top" :disabled="busy || checking || !option?.available">
<el-form-item label="补扫原因" required><el-input v-model="form.reason" type="textarea" :maxlength="2000" show-word-limit placeholder="例如:背面局部漏扫,需要补充采集" /></el-form-item>
<el-form-item label="最长采集时长(秒)" required><el-input-number v-model="form.durationSeconds" :min="1" :max="1800" :precision="0" /><span class="ml-12px">到时自动结束,也可提前结束采集。</span></el-form-item>
<el-checkbox v-model="form.sampleConfirmed">已核对是原任务的同一件实物样件</el-checkbox><br />
<el-checkbox v-model="form.fixtureConfirmed">已重新确认夹具、装夹及扫描位置适合继续采集</el-checkbox><br />
<el-checkbox v-model="form.loadedConfirmed">已确认原工程和现场条件,允许撤销当前网格并开始补扫</el-checkbox>
<el-checkbox v-model="form.sampleConfirmed"><span class="required-confirmation-mark" aria-hidden="true">*</span>已核对是原任务的同一件实物样件</el-checkbox><br />
<el-checkbox v-model="form.fixtureConfirmed"><span class="required-confirmation-mark" aria-hidden="true">*</span>已重新确认夹具、装夹及扫描位置适合继续采集</el-checkbox><br />
<el-checkbox v-model="form.loadedConfirmed"><span class="required-confirmation-mark" aria-hidden="true">*</span>已确认原工程和现场条件,允许撤销当前网格并开始补扫</el-checkbox>
</el-form>
</div>
<template #footer><el-button :disabled="busy" @click="visible = false">返回</el-button><el-button :disabled="checking || !validSupplement(form, option)" :loading="busy" type="primary" @click="start">开始补扫</el-button></template>

View File

@ -3,7 +3,7 @@
<div class="view-heading">
<div><h3>实时扫描画面</h3><span class="view-hint">{{ view.executionNo || executionNo || '本次执行' }} · 画面跟随扫描软件当前视角</span></div>
<div class="view-controls">
<el-tag :type="view.executionStatus === 'PAUSED' && view.scanning ? 'warning' : view.available && !error ? 'success' : 'info'">{{ caption }}</el-tag>
<el-tag :type="props.status === 'PAUSED' ? 'warning' : view.available && !error ? 'success' : 'info'">{{ caption }}</el-tag>
<el-switch v-model="watching" active-text="实时查看" :disabled="!live" />
<el-button :disabled="!imageUrl" @click="expanded = true">放大查看</el-button>
</div>
@ -48,7 +48,9 @@ const loading = ref(false)
const expanded = ref(false)
const streamFps = ref(0)
const live = computed(() => isLiveScannerExecution(props.status) && !(props.scope === 'fixture' && view.value.state === 'execution_finished'))
const caption = computed(() => scannerViewCaption(view.value, props.active, watching.value))
const caption = computed(() => imageUrl.value && !error.value && props.active && watching.value
? props.status === 'PAUSED' ? '流程已暂停,画面已连接' : '实时画面已连接'
: scannerViewCaption(view.value, props.active, watching.value))
let generation = 0
let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
@ -108,7 +110,9 @@ async function tick(token: number, signal: AbortSignal) {
if (id == null || token !== generation || !props.active || document.hidden || suspended) return
const delay = 1000
try {
if (Date.now() >= nextMetadata) {
// A healthy stream already supplies frames. Query status only before connecting
// or after a disconnect; do not poll the SDK while video is flowing.
if (!streamController && Date.now() >= nextMetadata) {
const result = await getScannerExecutionView(id, signal, props.scope)
if (token !== generation) return
view.value = result

View File

@ -104,11 +104,11 @@
>
<el-form-item label="实物接收"
><el-checkbox v-model="form.sampleReceived" @change="markDirty"
>已收到并核对本任务样件</el-checkbox
><span class="required-confirmation-mark" aria-hidden="true">*</span>已收到并核对本任务样件</el-checkbox
></el-form-item
>
<el-form-item label="尺寸(mm)"
><div class="dimensions"
<el-form-item label="尺寸(mm,选填)"
><div class="w-full"><div class="dimensions"
><el-input-number
v-model="form.lengthMm"
@change="dimensionsChanged"
@ -124,12 +124,12 @@
@change="dimensionsChanged"
:min="0.001"
placeholder="高"
:controls="false" /></div
:controls="false" /></div><div class="hint">不填尺寸可直接选择夹具;填全长宽高后可根据尺寸推荐。</div></div
></el-form-item>
<el-form-item label="重量(kg)"
><el-input-number
v-model="form.weightKg"
:min="0"
:min="0.001"
:controls="false"
@change="dimensionsChanged"
/></el-form-item>
@ -143,7 +143,7 @@
>
<template v-if="form.requireFixture">
<el-form-item label="推荐夹具"
><el-button :loading="fixtureLoading" @click="recommendFixtures"
><el-button :loading="fixtureLoading" :disabled="!completeDimensions" @click="recommendFixtures"
>根据尺寸推荐</el-button
></el-form-item
>
@ -163,7 +163,7 @@
:disabled="!fixture.compatible"
:label="`${fixture.fixtureCode} ${fixture.fixtureName}`"><div>{{ fixture.fixtureName }} · {{ fixture.fixtureCode }}</div><div v-if="!fixture.compatible" class="fixture-option-reason">{{ fixture.reason }}</div></el-option></el-select
></el-form-item>
<el-form-item v-if="selectedFixture" label="匹配依据"
<el-form-item v-if="selectedFixture" label="选择说明"
><span>{{ selectedFixture.reason }}</span></el-form-item
>
<el-form-item v-if="frameworkNeeded" label="夹具框架点"><el-alert :title="frameworkHint" :type="frameworkReady ? 'success' : 'warning'" :closable="false" /></el-form-item>
@ -172,7 +172,7 @@
v-model="form.fixtureConfirmed"
:disabled="locked || busy || !form.fixtureId"
@change="markDirty"
>已确认所选夹具及装夹条件</el-checkbox
><span class="required-confirmation-mark" aria-hidden="true">*</span>已确认所选夹具及装夹条件</el-checkbox
></el-form-item
>
</template>
@ -183,10 +183,10 @@
size="small"
class="mb-16px"
><el-table-column label="夹具" prop="fixtureName" /><el-table-column
label="匹配"
width="70"
label="选择方式"
width="90"
><template #default="{ row }">{{
row.compatible ? '可用' : '不匹配'
row.compatible ? (row.recommended ? '尺寸推荐' : '手动选择') : '不匹配'
}}</template></el-table-column
><el-table-column
label="依据"
@ -604,7 +604,7 @@
/></el-form-item>
<el-form-item
><el-checkbox v-model="startForm.loadedConfirmed"
>已核对当前样件编号,确认换件、装夹和现场执行条件</el-checkbox
><span class="required-confirmation-mark" aria-hidden="true">*</span>已核对当前样件编号,确认换件、装夹和现场执行条件</el-checkbox
></el-form-item
>
</el-form>
@ -803,6 +803,9 @@ const caseChanged = computed(
const selectedFixture = computed(() =>
recommendations.value.find((item) => String(item.id) === String(form.fixtureId))
)
const completeDimensions = computed(() =>
[form.lengthMm, form.widthMm, form.heightMm].every(value => typeof value === 'number' && value > 0)
)
const completedCount = computed(
() =>
detail.value?.units.filter((unit) => ['SUCCEEDED', 'COMPLETED'].includes(unit.status)).length ||

63
deploy/quic/README.md Normal file
View File

@ -0,0 +1,63 @@
# QUIC 固定认证名称:边端改动简版手册
固定名称:`am-freescan.internal`。直接连接平台实际 IP,不需要 DNS 或 hosts。本次CA与服务端证书均续签到2086年,沿用原CA身份及密钥、原服务端私钥。
## 1. 边端只改两处
在 **cmvr-es 仓库根目录**执行(补丁文件路径替换为收到的实际路径):
```bash
git apply --check /path/to/cmvr-es-fixed-identity.patch
git apply /path/to/cmvr-es-fixed-identity.patch
```
补丁修改:
- `cmvr-es/service/quic_edge/src/msquic_transport.cpp`:在连接前设置实际 IP,TLS 仍按 `server_name` 验证。原来的 IP 连接方式保留,失败不会跳过认证或自动降级。
- `cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt`:仅将主平台的 `tls.server_name` 改为 `am-freescan.internal`。
实际运行配置核对这几项,其他配置、机器人身份、心跳、媒体和 gRPC 参数原样保留:
```protobuf
server_host: "平台当前IP"
server_port: 4433
alpn: "cmvr-quic-edge/1"
tls {
ca_file: "certs/cmvr-quic-ca.crt"
server_name: "am-freescan.internal"
allow_insecure: false
}
```
不要把 `server_host` 写成固定名称。固定名称模式的 `server_host` 必须是实际 IPv4/IPv6 地址。如果使用 `platforms` 中的连接,修改对应项的 `server_name`,不要误改其他平台。
补丁校验不通过说明来源版本有差异,应按上述两处合并;不要强行套用。源码基线 SHA256 记录在 `edge-patch-source.json`。
## 2. 编译和替换
边端按原有方式编译,更新构建后的边端程序及上述运行配置;其他部署步骤保持不变。**只换证书文件不能代替这次代码适配。** 本包不含已编译的边端程序,需在边端构建环境完成编译。
## 3. 平台更换服务端证书
先确认现场无采集、标定或设备运动,暂停自动启动任务,再协调两端切换:
1. 备份平台原 `quic-gateway.crt` 与边端原程序、配置。
2. 将本包的 `quic-gateway.crt` 替换到平台正在配置的服务端证书路径;沿用原平台私钥 `quic-gateway.key`。将本包续签后的 `cmvr-quic-ca.crt` 替换到边端 `ca_file` 对应路径,先备份原CA证书。
3. 启动更新后的边端,并安全重启平台后端加载新证书。转换期间短暂离线属于预期,不发起运动任务。
原CA证书2036年到期。本包保留原CA名称、公钥和私钥,只续签CA证书的有效期;为真正使用到2086年,边端的CA证书文件仍须替换一次,证书指纹会变化。本包只含公开证书,**不要把 CA 私钥或平台私钥发给边端**。证书指纹与有效期见 `identity.json`。
## 4. 验证与以后换 IP
- 核对 QUIC 连接成功、机器人在线、设备状态和心跳正常;先不执行使能、运动或扫描。
- 若证书名称错误、CA 不受信任或证书过期,必须连接失败,不能改成 `allow_insecure: true`。
- 此后平台 IP 变化,只修改边端 `server_host` 并按原方式重载/重启边端;`server_name`、CA 和服务端证书不变,UDP4433 要能互通。该方案不自动发现新 IP,也不保证已有连接不中断。
- 回退时,恢复平台原证书和边端原程序、原配置、原CA证书,再安全重启两端。不能仅恢复其中一端。
证书包本身不会修改边端仓库、替换现网证书或重启程序。补丁的可应用性和新证书的认证行为已在本机检查;是否已完成现场切换,以实际配置、当前证书指纹及真实 QUIC 握手结果为准。边端完整编译及联调按以上步骤完成。
## 平台维护:到期前重新签发
安装 `deploy/quic/requirements.txt` 中的依赖,然后使用 `scripts/prepare_quic_identity.py --ca-cert <原CA证书> --ca-key <原CA私钥> --server-key <现有服务端私钥> --output-dir <新的输出目录>`。默认认证名称为 `am-freescan.internal`,默认有效期365天。此次60年续签增加 `--years 60 --renew-ca-years 60`,会用原密钥续签自签根CA,既有CA源文件不被修改。脚本只生成公开证书和指纹清单,不导出密钥、不修改运行配置、不重启服务。长有效期不代表密钥泄露后仍可继续使用,届时须协调更换密钥与证书。
实现依据:[MsQuic ConnectionStart](https://github.com/microsoft/msquic/blob/v2.5.9/docs/api/ConnectionStart.md)、[REMOTE_ADDRESS 参数实现](https://github.com/microsoft/msquic/blob/v2.5.9/src/core/connection.c)。设置真实目标地址后,`ConnectionStart` 的名称用于 TLS 身份认证,无须对该固定名称进行 DNS 解析。

View File

@ -0,0 +1,67 @@
--- a/cmvr-es/service/quic_edge/src/msquic_transport.cpp
+++ b/cmvr-es/service/quic_edge/src/msquic_transport.cpp
@@ -75,6 +75,7 @@
{
disconnect();
QUIC_STATUS status = QUIC_STATUS_SUCCESS;
+ const char* connect_operation = "ConnectionOpen/Start";
{
// Configuration creation and connection publication are one API
// operation. A concurrent disconnect can therefore never close a
@@ -112,20 +113,40 @@
const std::string& server_name =
config.tls().allow_insecure() || config.tls().server_name().empty()
? config.server_host() : config.tls().server_name();
+ // Pin the network destination independently of the TLS identity.
+ // Same-name/IP configurations retain the original MsQuic path.
+ if (server_name != config.server_host()) {
+ QUIC_ADDR remote_address{};
+ if (!QuicAddrFromString(config.server_host().c_str(),
+ static_cast<std::uint16_t>(config.server_port()),
+ &remote_address)) {
+ connect_operation = "server_host must be a literal IPv4/IPv6 address when tls.server_name differs";
+ status = QUIC_STATUS_INVALID_PARAMETER;
+ } else {
+ connect_operation = "SetParam(REMOTE_ADDRESS)";
+ status = api_->SetParam(opened_connection,
+ QUIC_PARAM_CONN_REMOTE_ADDRESS,
+ static_cast<std::uint32_t>(sizeof(remote_address)),
+ &remote_address);
+ }
+ }
CMVR_LOG(INFO) << "[MsQuicTransport] ConnectionStart"
<< ", connect_host=" << server_name
<< ", configured_server_host=" << config.server_host()
<< ", port=" << config.server_port()
<< ", ca_file=" << config.tls().ca_file()
<< ", allow_insecure=" << config.tls().allow_insecure();
- status = api_->ConnectionStart(
- opened_connection, configuration_, QUIC_ADDRESS_FAMILY_UNSPEC,
- server_name.c_str(),
- static_cast<std::uint16_t>(config.server_port()));
+ if (QUIC_SUCCEEDED(status)) {
+ connect_operation = "ConnectionStart";
+ status = api_->ConnectionStart(
+ opened_connection, configuration_, QUIC_ADDRESS_FAMILY_UNSPEC,
+ server_name.c_str(),
+ static_cast<std::uint16_t>(config.server_port()));
+ }
}
}
if (QUIC_FAILED(status)) {
- setError(error, statusText("ConnectionOpen/Start", status));
+ setError(error, statusText(connect_operation, status));
closeConnectionHandles();
return false;
}
--- a/cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt
+++ b/cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt
@@ -25,7 +25,7 @@
tls {
ca_file: "certs/cmvr-quic-ca.crt"
- server_name: "192.168.0.222"
+ server_name: "am-freescan.internal"
allow_insecure: false
}

View File

@ -0,0 +1,10 @@
# Merge ONLY these fields into the existing quic_edge or the intended platforms entry.
# This is a fragment, NOT a complete replacement for the task configuration.
# Apply cmvr-es-fixed-identity.patch and rebuild the edge before using it.
server_host: "<平台当前IP>"
server_port: 4433
tls {
ca_file: "certs/cmvr-quic-ca.crt"
server_name: "am-freescan.internal"
allow_insecure: false
}

View File

@ -0,0 +1,16 @@
{
"serverName": "am-freescan.internal",
"files": [
{
"path": "cmvr-es/service/quic_edge/src/msquic_transport.cpp",
"sourceSha256": "6628b4cee6b01efa629ad305ab084256174704704e5390b38e846a5f3476e736"
},
{
"path": "cmvr-es/config/tasks/quic_edge_task/quic_edge_task.pb.txt",
"sourceSha256": "bda5a400a584f7a77a97ba7ba1c789a56431002a50732d8a7b8d1dd1e9c6764f"
}
],
"preserveLegacy": true,
"requiresRebuild": true,
"appliedToEdgeSource": false
}

View File

@ -0,0 +1 @@
cryptography>=46,<51

128
deploy/windows11/HANDOFF.md Normal file
View File

@ -0,0 +1,128 @@
# 正式环境接管、最终全量同步与日常代码更新
日期:2026-11-12。适用于已经按之前手册和早先数据包装好的 Windows 11 专业版电脑。保留现有安装,不重装中间件,不重新运行 Init/Bootstrap。
## 1. 交给正式环境 AI 的指令
> 先读本仓库 AGENTS.md、deploy/windows11/HANDOFF.md 和 README.md。当前电脑已安装 standalone 环境并导入早先数据包,目前尚未投入业务使用。源电脑稍后提供最后一次全量数据包,现在不要重建数据库,也不要用早先包再次导入。先从 https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git 的 main 分支取得最新代码,核对已有 .local/standalone/runtime.json、私有 YAML、数据目录、Docker Compose 项目及启动方式,不输出密码或私钥。按第3节完成更新和只读验收,等待最后全量包。收到源端最终包及“双方均已停止现场操作、源后端已停止”的确认后,按第4节只执行一次 sync-full.ps1。用户确认正式环境当前未使用,本次不备份正式业务数据;脚本使用新的空目录和新数据卷导入,保留原卷而不删除它。迁移后账号、用例、夹具、任务和文件以源端最终包为准,目标电脑的中间件密码、入口地址、现场连接和证书保持目标配置。验收前不执行机械臂/电机使能、运动、回零、标定或采集。完成后在正式环境录入所有业务;以后仅执行 update.ps1 拉取、构建、升级程序,不再导入开发机数据。遇到本地源码修改、非 standalone 进程、实例身份不符、活动任务/占用、构建或数据库升级失败时停止并报告具体原因,不 reset --hard、不删除数据卷、不重置密码、不强行释放设备。记录部署提交号、全量包快照号、健康检查及真实缺失文件情况。
## 2. 两条互相独立的流程
| 流程 | 时机 | 内容 | 不执行的操作 |
|---|---|---|---|
| 最后一次全量数据同步 | 用户确认可以暂停操作并收到新包后,仅一次 | 最新全库、用例/冻结版本、夹具/框架点/轨迹关联、任务、执行/日志、平台已有文件 | 不备份当前未使用的目标业务数据;不合并两边新增记录;不删除旧卷 |
| 日常代码更新 | 开发修复并推送后 | 公网 Git main → Windows 本机构建 → 安全停止 → 替换前后端 → 必要增量表结构 → 健康检查 | 不导入源库、不覆盖正式业务、不更换现场配置/密码/证书、不自动启动设备动作 |
全量切换完成后,**正式环境是唯一业务数据源**。开发电脑只修改代码、模拟验证、提交并推送。正式环境 AI 只拉取、构建、部署并验收。不要再两边同时录入后要求“全量合并”;本方案不解决双向数据冲突。
公网仓库:`https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git`,分支 `main`。账号使用组织已有 Git 凭据,保存在系统凭据管理器;不要把密码拼进 URL 或脚本。
## 3. 现在可完成:正式环境先更新代码
以下在**正式电脑的原仓库目录**、PowerShell7 执行。路径以原安装实际位置为准,不假设必须为 D 盘。
```powershell
cd D:\apps\am-freescan
git status --short
# 必须没有本地源码修改;私有配置在忽略目录,不受拉取影响。
git remote set-url origin https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git
git pull --ff-only origin main
python -m pip install -r deploy/windows11/requirements.txt
pwsh -NoProfile -File deploy/windows11/update.ps1 -CheckOnly
```
如果电脑上启动方式被修改过,不再通过 `.local/standalone/backend-process.json` 管理,需要先让正式 AI 核对并接管**本实例**的启动方式;脚本不结束任意 java.exe。不得把开发电脑 `.local/runtime.json` 复制过来。
确认现场无采集/运动、平台任务已结束、资源已正常释放后:
```powershell
pwsh -NoProfile -File deploy/windows11/update.ps1 -ConfirmStopped
pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Status
```
`-ConfirmStopped` 是现场事实确认,不是强制跳过检查。脚本还核对运行/暂停/排队/停止待确认任务、资源占用和待确认扫描命令。构建期间旧程序文件保留,最终停止前再次校验空闲。两个更新/同步不能并行。
更新不重装中间件、不拉新 Docker 镜像、不启动供应商 EXE。MySQL仍为 `127.0.0.1:3306/am-freescan`,Redis仍为 `127.0.0.1:6379/15`。尺寸比对 EXE 保持正式电脑既有安装和配置,由现场既有方式运行;它及边端本地轨迹实体不是 Git 仓库里的软件或数据,不能靠程序更新凭空复制。
构建成功后保留上一版 JAR/前端;不做正式数据库/业务文件全量备份。脚本使用已批准的增量迁移,不做删表、清库或重建用户。**涉及删除/改写既有业务数据的未来版本,必须另附专用迁移方案,不能塞进通用更新脚本。**
## 4. 稍后执行:最后一次全量同步
### 4.1 冻结窗口与源电脑交付
现在先不生成新包。等用户确认暂时不需要操作时:
1. 两边停止业务录入和现场操作,结束任务并正常释放资源。源端确认全部代码已提交、推送。
2. 核对源端扫描/机械臂等真实状态空闲,通过现有方式停止源后端;导出工具还会拒绝48090仍在监听或数据库仍有活动任务/占用的情况。
3. 在源电脑执行,`MySqlDump`填官方客户端实际路径;`Output`必须为全新的目录:
```powershell
pwsh -NoProfile -File deploy/windows11/export-final.ps1 `
-MySqlDump 'D:/tools/mysql/bin/mysqldump.exe' `
-Output 'D:/transfer/am-freescan-final-填写实际日期时间' `
-ConfirmSourceStopped
```
交付**整个目录**,包括 `database.sql`、`artifacts/`、`uploads/`、`private/`、`manifest.json`;不能只传SQL或Git。记录导出返回的 manifest SHA256、`snapshotId`、`createdUtc`、`sourceCommit`。通过受限共享或移动介质交付,不提交Git、不贴出密码/私钥。文件级SHA256和表行数在清单内。
新包包含快照号和时间,接收脚本拒绝此前的早先包。历史缺失原文件仍按 `missingReferences` 如实列出;此前发现的53条不是“新包一定仍为53条”,以最终清单为准。未曾归档、源端也已不存在的扫描服务临时文件无法补出。源后端导出后保持停止,避免出现未交付的新记录;需要临时恢复录入则本包作废,重新安排冻结并导出新包。
### 4.2 正式电脑接收
1. 核对用户给出的 manifest SHA256,确认该包是最后一次导出。
2. 正式电脑代码和已部署版本须等于清单的 `sourceCommit`。默认通过第3节更新到最新;如果 main 又有新提交,先核对源端是否需要重导,不能改写清单来绕过版本核对。
3. 现场和源端均已停止后执行:
```powershell
Get-FileHash -Algorithm SHA256 D:/transfer/am-freescan-final/manifest.json
python scripts/migrate_standalone.py verify --package D:/transfer/am-freescan-final
pwsh -NoProfile -File deploy/windows11/sync-full.ps1 `
-MigrationPath D:/transfer/am-freescan-final `
-NewDataRoot D:/am-freescan-data-final `
-ConfirmStopped -ConfirmSourceStopped -ConfirmReplaceUnusedTarget
```
`NewDataRoot`须是不存在的新目录,不能嵌套于旧数据目录或仓库内。此脚本专门适用于用户确认“正式环境还未使用”的这次切换,**不用于将来覆盖已投入业务的正式环境**。
脚本停本实例前后端及旧MySQL/Redis容器,保留原卷;将旧私有目录移入 `.local/standalone-history/<批次>/`。新实例采用独立Compose项目/空卷,继续使用同样的本机端口,导入最终数据并校验。不会向非空库强灌SQL,不执行 `DROP DATABASE`、`docker compose down -v` 或删除旧文件,不生成正式数据备份包。
目标的数据库/Redis密码、浏览器入口、设备私有配置和证书沿用;证书路径位于旧dataRoot下的会复制并调整到新目录,位于其他受控目录的保留原路径。源包内的私有配置仅供核对,不整体覆盖目标私有配置。源账号和业务数据以全量包为准,登录会话重新建立;不迁移旧Redis运行锁。
数据库中的机器人/设备地址、角色和关联会随源库导入,不保证保留目标先前在页面中改过的地址;正式AI必须在启用现场连接前核对它们。早先部署包还可能使用旧QUIC证书:检查目标实际证书是否包含 `DNS:am-freescan.internal`,并核对边端当前使用的CA。若仍是旧证书,按 [QUIC简版手册](../quic/README.md) 协调换成最终包 `private/certificate.pem`、匹配的 `private/private-key.pem` 及 `private/client-ca.pem`,保留目标路径和其他配置,不盲目覆盖整份YAML。未完成这一步就不能宣称固定名称认证已在正式电脑生效。
成功后生成 `.local/standalone/full-sync.json`,记录快照、提交和缺失文件数量;有这个记录后脚本拒绝再次全量覆盖。旧卷、旧目录暂留不额外复制,之后是否清理由用户另行决定。
### 4.3 切换验收
- 登录原账号;核对新清单的表行数(导入阶段已自动检查;OAuth令牌清理等运行态变化已明确排除)。
- 核对最新用例/发布版本、夹具框架点及轨迹关联、任务/执行日志、扫描PLY、数模、PDF及已归档处理成果。
- 下载几个真实文件核对内容和来源;文件链接应由目标平台提供,不能指回开发机。
- 确认设备连接配置/QUIC信任关系正确,48090和启用后的UDP4433属于同一个后端;源控制平台继续停止。
- 打开任务页面、用例配置及比对工作区。仅做只读验收;现场运动/采集由用户另行操作。
- 记录最终快照号、代码提交号、JAR SHA256、新数据目录、Compose项目、缺失文件清单。验收后只在正式环境录入业务。
## 5. 后续每次更新只用一条命令
开发端:修复 → 模拟回归 → 提交 → 推送 `main` → 告知正式AI提交号。
正式端:收到提交号并确认现场空闲后:
```powershell
pwsh -NoProfile -File deploy/windows11/update.ps1 -ConfirmStopped
```
读取 `.local/standalone/deployment.json` 确认实际部署的提交,与开发端通知核对。脚本部署的是运行当时公网 `main` 最新提交,不会偷偷切到其他分支;如果出现未预期的新提交,先核对发布范围。
本机密码、现场IP/端口、QUIC证书/私钥、artifacts、uploads、正式数据库不放Git。以后不通过全量包同步正式业务,开发环境也不回写正式库。厂商尺寸比对EXE或边端程序升级独立交付,不由本脚本擅自升级。
后续修复如果涉及菜单、字典或数据库配置,开发端也要把相应的受控增量迁移随代码提交并验证;仅修改开发数据库不能让正式环境得到修复。通用更新只执行已纳入批准迁移清单的变更,遇到未登记的新迁移会停止,不能自行猜测执行SQL。
## 6. 失败处理
- 拉取/构建失败:旧运行包不替换;保留错误,解决后再运行。若Git有本地修改,不能强制重置。
- 活动任务/占用未解除:正常在平台结束和确认停止,不删锁记录、不让更新脚本代替设备停止。
- 激活/表结构升级/健康检查失败:维护标记保留,普通自启拒绝启动,前端入口停止;正式AI查看本机日志并诊断。没有“成功”记录就不算部署成功。
- 全量导入失败:新实例的部分数据留待诊断,旧卷和旧私有目录仍在;不反复导入到半成品库。未恢复任何业务前,可由正式AI核对新后端已停止后,将新私有目录另存、恢复旧私有目录,删除**旧目录中的本次维护标记**后通过 manage.ps1 Start 恢复旧实例;不删卷、不混用新旧运行目录。源端同时保持停止。
- 代码升级后如数据库结构已经变化,不仅凭上一版JAR就盲目回滚。通用脚本没有正式数据自动恢复功能,本次按用户要求不做目标业务备份。
本开发电脑没有可用Docker环境,因此脚本在源端进行解析、隔离模拟和失败路径验证;真实Docker容器创建、挂载、SQL导入及正式端健康验收必须由正式AI按本方案完成,不能把源端验证当成已经在正式电脑同步成功。

View File

@ -2,6 +2,8 @@
适用:招商车研三维尺寸快检平台,Windows 11 专业版 x64。目标是迁移现有测试用例、发布版本、夹具、框架点、任务、执行日志及平台已有文件,数据库和Redis改为新电脑本机服务。
**2026-11-12 后续交接:目标电脑已经按早先数据包完成安装,不要重新安装或初始化。下一步按 [正式环境接管与更新方案](HANDOFF.md) 执行:先更新代码,等待最终全量包,再一次性切换;之后仅运行更新脚本。用户确认目标尚未使用,本次全量切换不备份目标业务数据。**
## 1. 给目标电脑 AI 的完整任务指令
把下面这段和本手册一起交给目标电脑 AI:
@ -62,7 +64,7 @@ Git网络可达不代表Docker Hub、Maven仓库、npm或PyPI可达。联网失
## 4. 拉取代码,创建永久配置
```powershell
git clone http://192.168.28.10:18088/SmartBench/am-freescan.git D:\apps\am-freescan
git clone https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git D:\apps\am-freescan
cd D:\apps\am-freescan
git pull --ff-only origin main
git rev-parse HEAD
@ -179,10 +181,25 @@ pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Firewall
- 扫描仪:实际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来“解决连接”。
- QUIC初始为关闭状态。把合规的证书/私钥放到目标dataRoot/certs,在私有YAML中填写绝对路径再启用。推荐证书SAN固定为`DNS:am-freescan.internal`,边端`server_host`填写实际平台IP、`tls.server_name`固定为`am-freescan.internal`,IP变化只更新前者。首次切换须先应用边端配套补丁并使用原CA签发的新证书,步骤见[固定认证名称接入](../quic/README.md)。旧的按IP校验证书方式仍须由证书SAN覆盖该IP。不能关闭TLS验证或随便换自签CA来“解决连接”。
- 源、目标不能同时作为现场活动控制平台。最终切换前用户确认源端已停止,源自动启动任务不再把旧平台拉起来;目标验收完成前不让同一边端在两边来回切换。
- 私有配置变更后按第10节安全重启。界面“在线”仅代表对应真实通道状态,不能作为夹具安装正确、机械臂已使能或扫描精度验收的替代。
### 地址配置核对
| 功能 | 正式环境地址来源 | 换电脑时的处理 |
| --- | --- | --- |
| MySQL、Redis | `standalone`固定使用`127.0.0.1`;`prod`默认也使用本机,可由`AM_FREESCAN_DB_URL`、`AM_FREESCAN_REDIS_HOST`等环境变量覆盖 | 使用目标本机账号密码,不复制开发库连接 |
| 网页、登录、API、WebSocket、实时预览 | `prod`和`standalone`前端都使用当前站点的相对接口地址,由Nginx代理到后端 | 不把浏览器接口地址设置成`localhost:48090`,其他电脑的localhost不是服务器 |
| 平台上传文件 | `infra_file_config`的`basePath`、`domain`,以及实例的`publicBaseUrl` | Restore会重映射源目录及文件URL;之后若访问入口再次变化,须同步修改文件服务域名和旧的绝对文件URL,不能只修改网页入口 |
| 扫描成果、框架点、比对成果 | `lab.artifact.nas-root`;standalone为`AM_FREESCAN_HOME/artifacts` | 随数据包迁移实际文件;缺失的源文件不会靠修改IP恢复 |
| 扫描仪、旋转底座 | 私有YAML/环境变量;“机器人→连接配置”保存的设备地址优先 | 原地址不会因迁移自动变成新现场地址,切换前逐一核对 |
| 机械臂、AGV | QUIC快照发现的边端地址及gRPC端口 | 基础系统验收后再让边端连接新平台;不把历史在线记录当作已连接 |
| 尺寸比对EXE | `INSPECTION_PYTHON_BASE_URL`,默认`http://127.0.0.1:8769` | EXE部署在同机时无需修改;异机部署时配置可达地址 |
| 旧媒体功能(非扫描业务必需) | `minio.url/access-key/secret-key`、`tts.external-api.url` | 菜单虽已隐藏,旧功能仍保留。若启用须单独配置;主扫描文件链路使用平台文件存储,不依赖MinIO |
无参数直接启动JAR时默认选择`prod`,不再自动连接开发环境;开发需显式指定`dev/local`,独立部署仍按本手册显式指定`standalone`。`127.0.0.1`是本机调用地址,`0.0.0.0`是监听所有网卡,两者都不是某台电脑的固定LAN IP。源仓库内`dev/local`、历史文档、边端补丁基线中的旧IP不代表正式运行配置。
## 9. AI验收清单与交付记录
基础验收全部可以不运动:
@ -209,17 +226,14 @@ pwsh -NoProfile -File deploy/windows11/manage.ps1 -Action Stop -ConfirmStopped
脚本还会检查活动任务和占用;未确认停止则拒绝。只停止它保存并核对过身份的Java进程,不终止全部java.exe,也不删除数据卷。
更新前先备份;源/目标均无活动现场操作后:
已安装实例后续更新按 [交接方案](HANDOFF.md) 使用统一脚本;现场采集、运动停止并结束活动任务后:
```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
pwsh -NoProfile -File deploy/windows11/update.ps1 -CheckOnly
pwsh -NoProfile -File deploy/windows11/update.ps1 -ConfirmStopped
```
模板升级不会覆盖`.local/standalone`。数据库结构升级需要阅读对应迁移说明,不能把空库Bootstrap当作业务库升级工具。
脚本从公网 main 分支快进拉取,先构建暂存包,成功后才停止后端并替换程序,执行已批准的增量表结构升级及健康检查。保留目标私有配置、证书和全部业务数据;不会导入全量包或运行空库Bootstrap,不复制整套正式数据。保留上一版程序以供故障分析;数据库升级失败时保持维护状态,不擅自回滚数据库。首次获取此脚本见交接方案。
尺寸比对集成新增`017_dimension_comparison.sql`中的三张独立表。迁移包恢复会自动执行增量结构升级,保留原任务、用例、用户及菜单。已有独立实例更新代码后,在停止后端并完成备份的维护窗口执行:

View File

@ -15,6 +15,9 @@ cmvr:
alpn: cmvr-quic-edge/1
allowed-node-ids: []
tls:
# QUIC certificate SAN: DNS:am-freescan.internal. The edge uses the actual
# platform IP as server_host and am-freescan.internal as tls.server_name.
# Apply deploy/quic/cmvr-es-fixed-identity.patch before switching the edge.
certificate: ""
private-key: ""
client-ca: ""

View File

@ -0,0 +1,63 @@
# Shared implementation for Update and the one-time full-data cutover. No actions on import.
$deployRepo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$deployPrivate = Join-Path $deployRepo '.local/standalone'
$deployRuntime = Join-Path $deployPrivate 'runtime.json'
$deployManager = Join-Path $PSScriptRoot 'manage.ps1'
$deployPython = Join-Path $deployRepo 'scripts/bootstrap_standalone.py'
$deployCompose = Join-Path $PSScriptRoot 'compose.yaml'
function Run-DeployCommand([string]$Program, [string[]]$Arguments) {
& $Program @Arguments
if ($LASTEXITCODE -ne 0) { throw "$Program failed ($LASTEXITCODE); deployment stopped" }
}
function Read-DeployConfig {
if (-not (Test-Path -LiteralPath $deployRuntime)) { throw 'Existing standalone instance not found. Follow README first; do not run Init over an existing deployment.' }
$value = Get-Content -LiteralPath $deployRuntime -Raw | ConvertFrom-Json
if ($value.mysql.host -ne '127.0.0.1' -or $value.mysql.port -ne 3306 -or $value.mysql.database -ne 'am-freescan' -or $value.mysql.user -ne 'freescan' -or $value.redis.host -ne '127.0.0.1' -or $value.redis.port -ne 6379 -or $value.redis.database -ne 15) { throw 'This script only operates on the existing localhost standalone instance' }
return $value
}
function Run-DeployCompose($Config, [string[]]$Arguments) {
$project = if ($Config.composeProject) { $Config.composeProject } else { 'am-freescan-standalone' }
if ($project -notmatch '^[a-z0-9][a-z0-9_-]*$') { throw 'Invalid Compose project' }
Run-DeployCommand 'docker' (@('compose','-p',$project,'--env-file',(Join-Path $deployPrivate 'compose.env'),'-f',$deployCompose) + $Arguments)
}
function Get-DeployLock {
$path = Join-Path $deployRepo '.local/deployment.lock'
try { return [IO.File]::Open($path,[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None) }
catch { throw 'Another deployment is running or the deployment lock is inaccessible; do not run concurrent updates' }
}
function Assert-CleanDeployTree {
$changes = & git -C $deployRepo status --porcelain
if ($LASTEXITCODE -ne 0 -or $changes) { throw 'Repository has local changes or Git failed; preserve changes and resolve them first. No reset/stash is performed.' }
$branch = & git -C $deployRepo branch --show-current
if ($LASTEXITCODE -ne 0 -or $branch -ne 'main') { throw 'Deployment requires the main branch' }
}
function Assert-DeployIdle {
Run-DeployCommand 'python' @($deployPython,'--config',$deployRuntime,'--check-idle')
}
function New-DeployMaintenance([string]$Token, [string]$Kind) {
$file = Join-Path $deployPrivate 'maintenance.json'
if (Test-Path -LiteralPath $file) { throw 'An unfinished maintenance operation exists; inspect it before continuing' }
@{token=$Token;kind=$Kind;createdUtc=[datetime]::UtcNow.ToString('o')} | ConvertTo-Json | Set-Content -LiteralPath $file -Encoding utf8NoBOM
}
function Complete-DeployMaintenance([string]$Token) {
$file = Join-Path $deployPrivate 'maintenance.json'
if (Test-Path -LiteralPath $file) {
$marker = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json
if ($marker.token -ne $Token) { throw 'Maintenance identity changed; refusing to clear it' }
Remove-Item -LiteralPath $file
}
}
function Start-DeployInstance([string]$Token) {
Run-DeployCommand 'pwsh' @('-NoProfile','-File',$deployManager,'-Action','Start','-MaintenanceToken',$Token)
$reply = Invoke-RestMethod 'http://127.0.0.1:5180/admin-api/system/tenant/simple-list' -TimeoutSec 15
if ($reply.code -ne 0 -or @($reply.data | Where-Object { $_.id -eq 1 }).Count -ne 1) { throw 'Frontend proxy health check failed' }
$html = Invoke-WebRequest 'http://127.0.0.1:5180/' -TimeoutSec 15
if ($html.StatusCode -ne 200 -or $html.Content -notmatch '<html') { throw 'Frontend index health check failed' }
}
function Save-DeployRecord([string]$Commit, [string]$Kind, [string]$Id) {
$jar = Join-Path $deployPrivate 'backend/yudao-server.jar'
$Commit | Set-Content -LiteralPath (Join-Path $deployPrivate 'deployed-commit.txt') -Encoding utf8NoBOM
(Get-FileHash -LiteralPath $jar -Algorithm SHA256).Hash | Set-Content -LiteralPath (Join-Path $deployPrivate 'backend-sha256.txt') -Encoding utf8NoBOM
@{commit=$Commit;kind=$Kind;releaseId=$Id;healthyUtc=[datetime]::UtcNow.ToString('o');jarSha256=(Get-FileHash -LiteralPath $jar).Hash} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $deployPrivate 'deployment.json') -Encoding utf8NoBOM
}

View File

@ -0,0 +1,22 @@
#requires -Version 7.2
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$MySqlDump,
[Parameter(Mandatory)][string]$Output,
[switch]$ConfirmSourceStopped
)
$ErrorActionPreference='Stop'
$repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
if(-not $ConfirmSourceStopped){throw 'Stop physical acquisition/motion and the source backend first, then pass -ConfirmSourceStopped'}
$changes=& git -C $repo status --porcelain
if($LASTEXITCODE -ne 0 -or $changes){throw 'Commit and push all source changes before the final data export'}
$env:PYTHONDONTWRITEBYTECODE='1'
& python (Join-Path $repo 'scripts/migrate_standalone.py') export --mysqldump $MySqlDump --source-runtime (Join-Path $repo '.local/runtime.json') --artifacts (Join-Path $repo '.local/artifacts') --output $Output --confirm-source-stopped
if($LASTEXITCODE -ne 0){throw 'Source export failed; do not deliver the incomplete directory'}
& python (Join-Path $repo 'scripts/migrate_standalone.py') verify --package $Output
if($LASTEXITCODE -ne 0){throw 'Source package verification failed'}
$manifest=Join-Path $Output 'manifest.json'
$checksum=(Get-FileHash -LiteralPath $manifest -Algorithm SHA256).Hash
Write-Output "Final package ready: $Output"
Write-Output "manifest.json SHA256: $checksum"
Write-Output 'This package contains SQL, business files and private connection/certificate material. Transfer through restricted storage; never add it to Git.'

View File

@ -5,7 +5,8 @@ param(
[string]$DataRoot = 'D:/am-freescan-data',
[string]$PublicBaseUrl = 'http://127.0.0.1:5180',
[switch]$ConfirmStopped,
[string]$MigrationPath
[string]$MigrationPath,
[string]$MaintenanceToken
)
$ErrorActionPreference = 'Stop'
$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
@ -22,7 +23,9 @@ function Invoke-Checked([string]$Program, [string[]]$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)
$project = if ($cfg.composeProject) { $cfg.composeProject } else { 'am-freescan-standalone' }
if ($project -notmatch '^[a-z0-9][a-z0-9_-]*$') { throw 'Invalid Compose project name' }
Invoke-Checked 'docker' (@('compose','-p',$project,'--env-file',$envFile,'-f',$compose) + $Arguments)
}
function Read-Runtime {
if (-not (Test-Path -LiteralPath $runtimeFile)) { throw 'Run Init first' }
@ -129,6 +132,11 @@ switch ($Action) {
Invoke-Checked 'python' @($bootstrap,'--config',$runtimeFile,'--verify')
}
'Start' {
$maintenanceFile = Join-Path $private 'maintenance.json'
if (Test-Path -LiteralPath $maintenanceFile) {
$maintenance = Get-Content -LiteralPath $maintenanceFile -Raw | ConvertFrom-Json
if (-not $MaintenanceToken -or $maintenance.token -ne $MaintenanceToken) { throw 'Deployment maintenance is active; normal/autostart startup is blocked until the deployment finishes' }
}
$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' }
@ -152,7 +160,7 @@ switch ($Action) {
$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 @('up','-d','--force-recreate','web')
Compose @('exec','-T','web','nginx','-t')
Write-Output "Backend healthy; browser entry: $($cfg.publicBaseUrl)"
}

View File

@ -0,0 +1,86 @@
#requires -Version 7.2
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$MigrationPath,
[Parameter(Mandatory)][string]$NewDataRoot,
[switch]$ConfirmStopped,
[switch]$ConfirmSourceStopped,
[switch]$ConfirmReplaceUnusedTarget
)
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'deployment-common.ps1')
$cfg=Read-DeployConfig
$lock=Get-DeployLock
$token=[guid]::NewGuid().ToString('N')
$id='full-sync-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+$token.Substring(0,8)
$switched=$false
$maintenance=$false
try {
if(-not $ConfirmStopped -or -not $ConfirmSourceStopped -or -not $ConfirmReplaceUnusedTarget){throw 'Confirm both sites are physically stopped and the unused target data may be replaced. No target data backup will be created.'}
Assert-CleanDeployTree
if(Test-Path -LiteralPath (Join-Path $deployPrivate 'full-sync.json')){throw 'Final full synchronization already completed. Future updates must use update.ps1, not another source-data import.'}
$MigrationPath=(Resolve-Path -LiteralPath $MigrationPath).Path
Run-DeployCommand 'python' @((Join-Path $deployRepo 'scripts/migrate_standalone.py'),'verify','--package',$MigrationPath)
$manifest=Get-Content -LiteralPath (Join-Path $MigrationPath 'manifest.json') -Raw | ConvertFrom-Json
if(-not $manifest.snapshotId -or -not $manifest.createdUtc -or -not $manifest.sourceCommit){throw 'Use a fresh final export with snapshotId/createdUtc/sourceCommit, not the earlier deployment package.'}
$commit=(& git -C $deployRepo rev-parse HEAD).Trim()
if($LASTEXITCODE -ne 0 -or $commit -notmatch '^[0-9a-f]{40}$'){throw 'Cannot identify target code commit'}
if($manifest.sourceCommit -ne $commit){throw 'Source package and target code differ. Update target to the package sourceCommit first.'}
$deployedFile=Join-Path $deployPrivate 'deployed-commit.txt'
if(!(Test-Path -LiteralPath $deployedFile) -or (Get-Content -LiteralPath $deployedFile -Raw).Trim() -ne $commit){throw 'Run update.ps1 successfully before the final data cutover'}
if(-not [IO.Path]::IsPathFullyQualified($NewDataRoot)){throw 'NewDataRoot must be an absolute new directory'}
$NewDataRoot=[IO.Path]::GetFullPath($NewDataRoot).TrimEnd('\','/')
$oldRoot=[IO.Path]::GetFullPath($cfg.dataRoot).TrimEnd('\','/')
foreach($protected in @($oldRoot,$deployRepo)){
if($NewDataRoot.Equals($protected,[StringComparison]::OrdinalIgnoreCase) -or $NewDataRoot.StartsWith($protected+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase) -or $protected.StartsWith($NewDataRoot+[IO.Path]::DirectorySeparatorChar,[StringComparison]::OrdinalIgnoreCase)){throw 'NewDataRoot must not overlap the old data root or repository'}
}
if(Test-Path -LiteralPath $NewDataRoot){throw 'NewDataRoot must not already exist; old data is never overwritten'}
Assert-DeployIdle
New-DeployMaintenance $token 'final-full-sync';$maintenance=$true
Run-DeployCompose $cfg @('stop','web')
Run-DeployCommand 'pwsh' @('-NoProfile','-File',$deployManager,'-Action','Stop','-ConfirmStopped')
Assert-DeployIdle
# Retain the unused old volumes, without copying/dumping target business data.
Run-DeployCompose $cfg @('stop','mysql','redis')
$history=Join-Path $deployRepo ".local/standalone-history/$id"
New-Item -ItemType Directory -Path (Split-Path -Parent $history) -Force | Out-Null
Move-Item -LiteralPath $deployPrivate -Destination $history
$switched=$true
New-Item -ItemType Directory -Path $deployPrivate,$NewDataRoot -Force | Out-Null
New-DeployMaintenance $token 'final-full-sync'
$principal=[Security.Principal.WindowsIdentity]::GetCurrent().Name
foreach($directory in @($deployPrivate,$NewDataRoot)){Run-DeployCommand 'icacls.exe' @($directory,'/inheritance:r','/grant:r',"${principal}:(OI)(CI)F",'*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F')}
foreach($entry in Get-ChildItem -LiteralPath $history -Force){
if($entry.Name -notin @('backend-process.json','maintenance.json','full-sync.json')){Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $deployPrivate $entry.Name) -Recurse}
}
foreach($name in @('artifacts','uploads','web','backups','logs','certs','tmp')){New-Item -ItemType Directory -Path (Join-Path $NewDataRoot $name) -Force | Out-Null}
Copy-Item -Path (Join-Path $oldRoot 'web/*') -Destination (Join-Path $NewDataRoot 'web') -Recurse
if(Test-Path -LiteralPath (Join-Path $oldRoot 'certs')){Get-ChildItem -LiteralPath (Join-Path $oldRoot 'certs') -Force | ForEach-Object {Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $NewDataRoot 'certs' $_.Name) -Recurse}}
$cfg.dataRoot=$NewDataRoot.Replace('\','/');$cfg.uploadRoot=$cfg.dataRoot+'/uploads';$cfg.instanceId=[guid]::NewGuid().ToString('N')
$cfg | Add-Member -NotePropertyName composeProject -NotePropertyValue ('am-freescan-'+$token.Substring(0,12)) -Force
$cfg | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath $deployRuntime -Encoding utf8NoBOM
$yaml=Join-Path $deployPrivate 'application-private.yaml'
if(Test-Path -LiteralPath $yaml){
$text=Get-Content -LiteralPath $yaml -Raw
$text=$text.Replace($oldRoot.Replace('\','/'),$cfg.dataRoot).Replace($oldRoot,$NewDataRoot)
$text | Set-Content -LiteralPath $yaml -Encoding utf8NoBOM
}
Run-DeployCommand 'pwsh' @('-NoProfile','-File',$deployManager,'-Action','Middleware')
Run-DeployCommand 'pwsh' @('-NoProfile','-File',$deployManager,'-Action','Restore','-MigrationPath',$MigrationPath,'-ConfirmStopped')
Start-DeployInstance $token
Save-DeployRecord $commit 'final-full-sync' $id
@{snapshotId=$manifest.snapshotId;sourceCommit=$manifest.sourceCommit;createdUtc=$manifest.createdUtc;importedUtc=[datetime]::UtcNow.ToString('o');manifestSha256=(Get-FileHash -LiteralPath (Join-Path $MigrationPath 'manifest.json')).Hash;oldPrivate=$history;oldDataRoot=$oldRoot;missingHistoricalFiles=@($manifest.missingReferences).Count;targetDataBackupCreated=$false} | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $deployPrivate 'full-sync.json') -Encoding utf8NoBOM
Complete-DeployMaintenance $token;$maintenance=$false
Write-Output 'Final full sync succeeded. Use only this production instance for business data; future releases use update.ps1.'
}
catch {
if($maintenance -and -not $switched){
try{Run-DeployCompose $cfg @('up','-d','--wait','mysql','redis');Start-DeployInstance $token;Complete-DeployMaintenance $token;$maintenance=$false}catch{Write-Warning 'Old instance requires inspection; maintenance retained.'}
}
if($switched){
if(Test-Path -LiteralPath (Join-Path $deployPrivate 'compose.env')){try{Run-DeployCompose $cfg @('stop','web')}catch{Write-Warning 'Check frontend container state.'}}
Write-Warning "Cutover incomplete. Old volumes/data remain intact; old private config: $history. Do not start either instance until the target AI diagnoses the failure. Do not delete volumes or re-import over a partial database."
}
throw
}
finally{$lock.Dispose()}

View File

@ -0,0 +1,88 @@
#requires -Version 7.2
[CmdletBinding()]
param(
[switch]$ConfirmStopped,
[switch]$CheckOnly,
[string]$RemoteUrl = 'https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git'
)
$ErrorActionPreference='Stop'
. (Join-Path $PSScriptRoot 'deployment-common.ps1')
$cfg=Read-DeployConfig
$lock=Get-DeployLock
$maintenance=$false
$activation=$false
$backendStopped=$false
$token=[guid]::NewGuid().ToString('N')
$id='release-'+(Get-Date -Format 'yyyyMMdd-HHmmss')+'-'+$token.Substring(0,8)
$stage=Join-Path $deployRepo ".local/release-builds/$id"
try {
Assert-CleanDeployTree
foreach($program in @('git','java','mvn','node','pnpm','python','docker','pwsh')) { Get-Command $program -ErrorAction Stop | Out-Null }
if ((& java -version 2>&1 | Out-String) -notmatch 'version "17\.') { throw 'JDK17 is required' }
if ((& mvn -version 2>&1 | Out-String) -notmatch 'Apache Maven 3\.9\.') { throw 'Maven3.9.x is required' }
if ($RemoteUrl -ne 'https://p20001.svc.cmvr-iot.icu/SmartBench/am-freescan.git') { throw 'Unexpected Git repository; review the script before changing its destination' }
Run-DeployCompose $cfg @('config','--quiet')
Run-DeployCommand 'python' @($deployPython,'--config',$deployRuntime,'--check-instance')
if ($CheckOnly) { Write-Output 'Preflight passed. No pull, build, restart or data import was performed.'; return }
if (-not $ConfirmStopped) { throw 'Confirm acquisition and physical motion have stopped, then pass -ConfirmStopped' }
Assert-DeployIdle
$env:GIT_TERMINAL_PROMPT='0'
Run-DeployCommand 'git' @('-C',$deployRepo,'fetch','--no-tags',$RemoteUrl,'main')
$commit=(& git -C $deployRepo rev-parse FETCH_HEAD).Trim()
if ($LASTEXITCODE -ne 0 -or $commit -notmatch '^[0-9a-f]{40}$') { throw 'Unable to identify the fetched commit' }
Run-DeployCommand 'git' @('-C',$deployRepo,'merge','--ff-only',$commit)
Assert-CleanDeployTree
New-Item -ItemType Directory -Path (Join-Path $stage 'web') -Force | Out-Null
Write-Output "Building $commit. The current runtime package is preserved until both builds succeed."
Push-Location (Join-Path $deployRepo 'am-backend')
try { Run-DeployCommand 'mvn' @('-pl','yudao-server','-am','package','-DskipTests','-DskipITs') } finally { Pop-Location }
Copy-Item -LiteralPath (Join-Path $deployRepo 'am-backend/yudao-server/target/yudao-server.jar') -Destination (Join-Path $stage 'yudao-server.jar')
Push-Location (Join-Path $deployRepo 'am-web')
try {
Run-DeployCommand 'pnpm' @('install','--frozen-lockfile')
Run-DeployCommand 'pnpm' @('build:standalone','--outDir',(Join-Path $stage 'web'))
} finally { Pop-Location }
if (-not (Test-Path -LiteralPath (Join-Path $stage 'web/index.html'))) { throw 'Frontend build has no index.html' }
Assert-CleanDeployTree
Assert-DeployIdle
New-DeployMaintenance $token 'code-update';$maintenance=$true
Run-DeployCompose $cfg @('stop','web')
Run-DeployCommand 'pwsh' @('-NoProfile','-File',$deployManager,'-Action','Stop','-ConfirmStopped')
$backendStopped=$true
Assert-DeployIdle
# Preserve only the previous program and frontend. No business data copy/import.
$previous=Join-Path $deployRepo ".local/release-history/$id"
New-Item -ItemType Directory -Path $previous -Force | Out-Null
$runtimeJar=Join-Path $deployPrivate 'backend/yudao-server.jar'
Copy-Item -LiteralPath $runtimeJar -Destination (Join-Path $previous 'yudao-server.jar')
foreach($name in @('deployed-commit.txt','backend-sha256.txt','deployment.json')) {
$source=Join-Path $deployPrivate $name
if(Test-Path -LiteralPath $source){Copy-Item -LiteralPath $source -Destination (Join-Path $previous $name)}
}
$web=Join-Path $cfg.dataRoot 'web'
$activation=$true
if(Test-Path -LiteralPath $web){Move-Item -LiteralPath $web -Destination (Join-Path $cfg.dataRoot "web-before-$id")}
Copy-Item -LiteralPath (Join-Path $stage 'yudao-server.jar') -Destination $runtimeJar -Force
Copy-Item -LiteralPath (Join-Path $stage 'web') -Destination $web -Recurse
Run-DeployCommand 'python' @($deployPython,'--config',$deployRuntime,'--upgrade')
Run-DeployCommand 'python' @($deployPython,'--config',$deployRuntime,'--verify')
Start-DeployInstance $token
Save-DeployRecord $commit 'code-update' $id
Complete-DeployMaintenance $token;$maintenance=$false
Write-Output "Deployment succeeded: $commit. Business data and private device/QUIC configuration were preserved."
}
catch {
if($maintenance){
if(-not $activation){
try {
if($backendStopped){Start-DeployInstance $token}else{Run-DeployCompose $cfg @('up','-d','web')}
Complete-DeployMaintenance $token;$maintenance=$false
} catch { Write-Warning 'Old application could not be restarted; maintenance marker retained.' }
} else {
try { Run-DeployCompose $cfg @('stop','web') } catch { Write-Warning 'Could not stop the frontend; inspect its container.' }
Write-Warning 'Activation failed. Maintenance remains active; inspect logs and the saved previous program. Do not rerun Init/Bootstrap or reset the database.'
}
}
throw
}
finally { $lock.Dispose() }

View File

@ -17,6 +17,19 @@ import bootstrap_cmvr as native
from apply_scan_only import apply_schema, load_migration
OWNER = "am-freescan/standalone-v1"
IDLE_QUERIES = (
"SELECT COUNT(*) FROM te_task_inst WHERE status IN ('1','3')",
"SELECT COUNT(*) FROM lab_execution WHERE status IN ('RUNNING','PAUSED','QUEUED','STOPPING','STOP_PENDING') AND deleted=0",
"SELECT COUNT(*) FROM lab_resource_occupation WHERE deleted=0",
"SELECT COUNT(*) FROM lab_scanner_command WHERE active_endpoint IS NOT NULL",
)
def ensure_idle(cursor):
for sql in IDLE_QUERIES:
cursor.execute(sql)
if cursor.fetchone()[0]:
raise ValueError("Active execution, occupation or unconfirmed scanner command remains; stop safely through the platform first")
MIGRATIONS = (
"005_scan_only.sql", "006_resource_scheduling.sql", "007_scanner_integration.sql",
"008_scanner_execution_view.sql", "009_rotary_base_integration.sql",
@ -85,9 +98,10 @@ def main(argv=None):
mode.add_argument("--verify", action="store_true")
mode.add_argument("--upgrade", action="store_true", help="Add approved schema structures to this owned instance without rewriting users or menus")
mode.add_argument("--check-idle", action="store_true")
mode.add_argument("--check-instance", action="store_true", help="Validate instance ownership before upgrading an older schema")
args = parser.parse_args(argv)
schema, seeds, cmvr, reference, migrations = plan()
if not any((args.apply, args.verify, args.check_idle, args.upgrade)):
if not any((args.apply, args.verify, args.check_idle, args.check_instance, args.upgrade)):
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)))
@ -100,6 +114,9 @@ def main(argv=None):
with connect(cfg) as connection:
with connection.cursor() as cursor:
ownership(cursor, cfg, allow_empty=args.apply)
if args.check_instance:
print("Local standalone instance ownership verified; no schema or business data changed")
return 0
if args.upgrade:
cursor.execute("SELECT GET_LOCK(%s,10)", (OWNER,))
if cursor.fetchone() != (1,):
@ -114,14 +131,7 @@ def main(argv=None):
cursor.execute("SELECT RELEASE_LOCK(%s)", (OWNER,))
return 0
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")
ensure_idle(cursor)
print("No active platform execution or occupation; physical state still requires onsite confirmation")
return 0
if args.verify:

View File

@ -3,6 +3,7 @@ Requires official mysqldump on the source; the target imports with its local MyS
"""
from __future__ import annotations
import argparse, hashlib, json, os, re, shutil, socket, subprocess, sys, tempfile, uuid
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
import bootstrap_db as source_bootstrap
@ -33,12 +34,7 @@ def copy_tree(source,target):
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')
standalone.ensure_idle(cursor)
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')
@ -107,7 +103,9 @@ def export_bundle(args):
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'))
source_commit=subprocess.run(['git','-C',str(ROOT),'rev-parse','HEAD'],capture_output=True,text=True,check=True).stdout.strip()
manifest=dict(format='am-freescan-migration-v1',sourceDatabase='am-freescan',sourceConfirmedStopped=True,
createdUtc=datetime.now(timezone.utc).isoformat(),sourceCommit=source_commit,snapshotId=uuid.uuid4().hex,
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()]
@ -157,7 +155,9 @@ def import_bundle(args):
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)
project=cfg.get('composeProject','am-freescan-standalone')
if not re.fullmatch(r'[a-z0-9][a-z0-9_-]*',project):raise ValueError('Invalid standalone Compose project')
result=subprocess.run(['docker','compose','-p',project,'--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')

View File

@ -0,0 +1,155 @@
"""Issue a QUIC server certificate with a stable DNS identity using the existing CA.
This prepares files only: it never changes live YAML, restarts a service, or exports keys.
Install the optional dependency from deploy/quic/requirements.txt before running.
"""
import argparse
import ipaddress
import json
import re
from datetime import datetime, timedelta, timezone
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
def public_bytes(key):
return key.public_key().public_bytes(
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
)
def anniversary(now, years):
try:
return now.replace(year=now.year + years)
except ValueError: # A February 29 anniversary in a non-leap year.
return now.replace(year=now.year + years, day=28)
def prepare(ca_cert, ca_key, server_key, output, server_name="am-freescan.internal", days=365,
years=None, renew_ca_years=None):
name = server_name.lower()
labels = name.split(".")
if len(name) > 253 or len(labels) < 2 or any(
not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) for label in labels
):
raise ValueError("认证名称必须为明确的DNS名称,不能含通配符")
try:
ipaddress.ip_address(name)
except ValueError:
pass
else:
raise ValueError("认证名称不能是IP地址")
if not 1 <= days <= 21960:
raise ValueError("证书有效天数必须在1–21960之间")
if years is not None and not 1 <= years <= 60:
raise ValueError("有效年数必须在1–60之间")
if renew_ca_years is not None and not 1 <= renew_ca_years <= 60:
raise ValueError("CA续签年数必须在1–60之间")
ca = x509.load_pem_x509_certificate(Path(ca_cert).read_bytes())
original_ca_fingerprint = ca.fingerprint(hashes.SHA256()).hex()
authority = serialization.load_pem_private_key(Path(ca_key).read_bytes(), password=None)
server = serialization.load_pem_private_key(Path(server_key).read_bytes(), password=None)
if not isinstance(authority, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)):
raise ValueError("签发CA须使用RSA或EC密钥")
if not isinstance(server, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey)):
raise ValueError("服务端须使用RSA或EC密钥")
ca_public = ca.public_key().public_bytes(
serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
)
if ca_public != public_bytes(authority):
raise ValueError("CA证书与CA私钥不匹配")
if not ca.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
raise ValueError("提供的证书不是CA证书")
try:
if not ca.extensions.get_extension_for_class(x509.KeyUsage).value.key_cert_sign:
raise ValueError("CA不允许签发证书")
except x509.ExtensionNotFound:
pass
now = datetime.now(timezone.utc)
if not ca.not_valid_before_utc <= now < ca.not_valid_after_utc:
raise ValueError("CA证书尚未生效或已过期")
if renew_ca_years is not None:
if ca.subject != ca.issuer:
raise ValueError("仅支持用原密钥续签自签根CA;中间CA须由原上级签发")
ca.verify_directly_issued_by(ca)
renewal = (x509.CertificateBuilder().subject_name(ca.subject).issuer_name(ca.issuer)
.public_key(ca.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(ca.not_valid_before_utc)
.not_valid_after(anniversary(now, renew_ca_years)))
for extension in ca.extensions:
renewal = renewal.add_extension(extension.value, extension.critical)
ca = renewal.sign(authority, hashes.SHA256())
expires = min(anniversary(now, years) if years is not None else now + timedelta(days=days),
ca.not_valid_after_utc)
if expires - now < timedelta(days=1):
raise ValueError("CA剩余有效期不足一天")
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(ca.subject)
.public_key(server.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(max(now - timedelta(minutes=5), ca.not_valid_before_utc))
.not_valid_after(expires)
.add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical=False)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(x509.KeyUsage(
digital_signature=True, content_commitment=False,
key_encipherment=isinstance(server, rsa.RSAPrivateKey),
data_encipherment=False, key_agreement=False, key_cert_sign=False,
crl_sign=False, encipher_only=None, decipher_only=None
), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(server.public_key()), critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca.public_key()), critical=False)
.sign(authority, hashes.SHA256())
)
output = Path(output).resolve()
output.mkdir(parents=True, exist_ok=False)
(output / "quic-gateway.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
(output / "cmvr-quic-ca.crt").write_bytes(ca.public_bytes(serialization.Encoding.PEM))
manifest = {
"serverName": name,
"subjectAltName": {"dns": [name], "ip": []},
"certificateSha256": cert.fingerprint(hashes.SHA256()).hex(),
"caSha256": ca.fingerprint(hashes.SHA256()).hex(),
"originalCaSha256": original_ca_fingerprint,
"caCertificateRenewed": renew_ca_years is not None,
"caPublicKeyUnchanged": True,
"caNotAfter": ca.not_valid_after_utc.isoformat(),
"notBefore": cert.not_valid_before_utc.isoformat(),
"notAfter": cert.not_valid_after_utc.isoformat(),
"serverKeyReused": True,
"privateKeysIncluded": False,
"activated": False,
}
(output / "identity.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return manifest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ca-cert", type=Path, required=True)
parser.add_argument("--ca-key", type=Path, required=True)
parser.add_argument("--server-key", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--server-name", default="am-freescan.internal")
parser.add_argument("--days", type=int, default=365)
parser.add_argument("--years", type=int, help="按日历年签发,优先于days,最多60年")
parser.add_argument("--renew-ca-years", type=int, help="明确选择用原密钥续签自签根CA,不改变CA身份")
args = parser.parse_args()
try:
result = prepare(args.ca_cert, args.ca_key, args.server_key, args.output_dir,
args.server_name, args.days, args.years, args.renew_ca_years)
except (ValueError, OSError, x509.ExtensionNotFound) as error:
parser.exit(1, f"证书准备失败:{error}\n")
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()