feat(registry): 迁移至 Rust + Axum + SQLite 并新增编辑、分页和档案同步功能

- 后端从 Node.js 迁移到 Rust,使用 Axum 框架和 SQLite 存储
- 新增档案编辑对话框,支持修改机型、登记人及替换/删除照片
- 档案列表增加分页导航(每页20条)
- 新增档案同步状态提示及手动重试同步按钮
- Node.js 原版后端及网页保留为回退方案,移至 legacy-web 目录
- 更新 .gitignore 添加 Rust 构建产物(target、dist)
- 更新 README 文档,补充 Rust 启动、开发、检查及打包说明
- 启动源码版.cmd 默认转发至 Rust 版启动脚本
```
This commit is contained in:
2026-10-21 11:54:38 +08:00
parent 85924f35ff
commit 4d55796cb3
39 changed files with 5925 additions and 39 deletions
+72
View File
@@ -0,0 +1,72 @@
param([string]$OutputRoot)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'rust-env.ps1')
$ridRepo = Split-Path $PSScriptRoot -Parent
if (-not $OutputRoot) { $OutputRoot = Join-Path $ridRepo 'dist' }
$ridOutputRoot = [IO.Path]::GetFullPath($OutputRoot)
$ridDestination = Join-Path $ridOutputRoot 'FPV-RID-Rust'
$ridWhitelist = @('fpv-rid-registry.exe', '启动Rust版.cmd', '使用说明.md', 'qrcode-LICENSE.txt', 'dependency-licenses.txt', 'SHA256SUMS.txt')
function Assert-CleanDestination {
if (Test-Path -LiteralPath $ridDestination) {
foreach ($ridEntry in Get-ChildItem -LiteralPath $ridDestination -Force) {
if ($ridEntry.PSIsContainer -or $ridEntry.Name -notin $ridWhitelist -or
($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "发布目录含运行数据或非发布文件,已停止打包并保留原内容:$($ridEntry.FullName)。请通过 -OutputRoot 指定单独的输出目录。"
}
}
}
}
# Refuse a used deployment folder before building or changing any published files.
Assert-CleanDestination
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
$ridTemporaryZip = Join-Path $ridStageRoot 'release.zip'
Push-Location $ridRepo
try {
cargo build --release --locked
if ($LASTEXITCODE -ne 0) { throw 'Release build failed' }
$ridMetadata = cargo metadata --locked --format-version 1 --no-deps | ConvertFrom-Json
if ($LASTEXITCODE -ne 0) { throw 'Cargo metadata failed' }
New-Item -ItemType Directory -Force -Path $ridStage | Out-Null
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory 'release/fpv-rid-registry.exe') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo '启动Rust版.cmd') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'doc/registry/rust/使用说明.md') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'registry/web/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'qrcode-LICENSE.txt')
$ridLicenses = cargo tree --locked --prefix none --format '{p} {l}'
if ($LASTEXITCODE -ne 0) { throw 'Dependency inventory failed' }
$ridLicenses | Set-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
$ridWhitelist | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
'{0} {1}' -f (Get-FileHash -LiteralPath (Join-Path $ridStage $_) -Algorithm SHA256).Hash, $_
} | Set-Content -LiteralPath (Join-Path $ridStage 'SHA256SUMS.txt') -Encoding utf8
$ridActual = @(Get-ChildItem -LiteralPath $ridStage -Force)
if ($ridActual.Count -ne $ridWhitelist.Count -or @($ridActual | Where-Object { $_.PSIsContainer -or $_.Name -notin $ridWhitelist }).Count) {
throw 'Staging directory does not match the release whitelist'
}
# Only the fresh, checked staging tree is ever compressed.
Compress-Archive -LiteralPath $ridStage -DestinationPath $ridTemporaryZip
Assert-CleanDestination
New-Item -ItemType Directory -Force -Path $ridDestination | Out-Null
foreach ($ridName in $ridWhitelist) {
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination (Join-Path $ridDestination $ridName)
}
$ridZip = Join-Path $ridOutputRoot 'FPV-RID-Rust-Windows-x64.zip'
Move-Item -LiteralPath $ridTemporaryZip -Destination $ridZip -Force
'{0} FPV-RID-Rust-Windows-x64.zip' -f (Get-FileHash -LiteralPath $ridZip -Algorithm SHA256).Hash |
Set-Content -LiteralPath "$ridZip.sha256" -Encoding utf8
Write-Output $ridDestination
Write-Output $ridZip
} finally {
Pop-Location
# Clean only files this invocation created. Never recursively delete an output directory.
foreach ($ridName in $ridWhitelist) {
$ridOwnedFile = Join-Path $ridStage $ridName
if (Test-Path -LiteralPath $ridOwnedFile -PathType Leaf) { Remove-Item -LiteralPath $ridOwnedFile }
}
if (Test-Path -LiteralPath $ridTemporaryZip -PathType Leaf) { Remove-Item -LiteralPath $ridTemporaryZip }
if ((Test-Path -LiteralPath $ridStage -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStage -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStage }
if ((Test-Path -LiteralPath $ridStageRoot -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStageRoot -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStageRoot }
}
+6
View File
@@ -0,0 +1,6 @@
# Dot-source this file for the workspace's shared Rust installation.
$env:CARGO_HOME = 'D:\Rust_Contact\util\cargo'
$env:RUSTUP_HOME = 'D:\Rust_Contact\util\rustup'
if (($env:Path -split ';') -notcontains "$env:CARGO_HOME\bin") {
$env:Path = "$env:CARGO_HOME\bin;$env:Path"
}
+41
View File
@@ -0,0 +1,41 @@
// Browser acceptance against a real Rust process and a disposable database.
import {createRequire} from 'node:module';
import {mkdtemp,mkdir,writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import {DatabaseSync} from 'node:sqlite';
import assert from 'node:assert/strict';
const require=createRequire(import.meta.url);
const {chromium}=require('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-浏览器验收-'));
const exe=path.resolve(process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry.exe');
const base='http://127.0.0.1:8787';
try{const r=await fetch(base);if(r)throw Error('8787 已有服务,请先关闭');}catch(e){if(e.message.includes('已有服务'))throw e;}
await mkdir(path.join(root,'registry/data'),{recursive:true});
const db=new DatabaseSync(path.join(root,'registry/data/registry.sqlite'));
db.exec("CREATE TABLE records(id TEXT PRIMARY KEY,serial_no TEXT NOT NULL UNIQUE,uas_code TEXT NOT NULL UNIQUE,model_name TEXT NOT NULL DEFAULT '',owner_name TEXT NOT NULL DEFAULT '',created_at TEXT NOT NULL); CREATE TABLE photos(record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,slot INTEGER NOT NULL CHECK(slot IN(1,2)),mime_type TEXT NOT NULL,image BLOB NOT NULL,PRIMARY KEY(record_id,slot));");
for(let i=1;i<=21;i++)db.prepare('INSERT INTO records VALUES(?,?,?,?,?,?)').run(String(i).padStart(36,'0'),`BROWSER-${String(i).padStart(3,'0')}`,`FPV${String(i).padStart(8,'0')}`,'演示机型','验收数据','2020-01-01T00:00:00.000Z');db.close();
const png=Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=','base64');
const child=spawn(exe,['--data-root',root],{windowsHide:true,env:{...process.env,PATH:'C:\\Windows\\System32'},stdio:['ignore','pipe','pipe']});let output='';let spawnError;
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>spawnError=e);
let browser;
try{
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch(base+'/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||undefined});const page=await browser.newPage({viewport:{width:1366,height:1000},acceptDownloads:true});let errors=[];page.on('pageerror',e=>errors.push(e.message));
await page.goto(base);await page.locator('#page-status').filter({hasText:'共 21 条'}).waitFor();
await page.fill('#serial-no','UI-NEW-001');await page.fill('#model-name','待清空机型');await page.fill('#owner-name','原登记人');await page.setInputFiles('#photo-1',{name:'photo.png',mimeType:'image/png',buffer:png});await page.click('#register-button');await page.locator('#form-message').filter({hasText:'登记成功'}).waitFor();
const card=page.locator('.archive-card').filter({has:page.getByRole('heading',{name:'UI-NEW-001',exact:true})});
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();assert.equal(await page.locator('#edit-model').evaluate(el=>el===document.activeElement),true);await page.click('#edit-cancel');assert.equal(await page.locator('#edit-dialog').isVisible(),false);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-model','');await page.fill('#edit-owner','修改后的登记人');await page.check('#edit-delete-1');await page.setInputFiles('#edit-photo-2',{name:'new.png',mimeType:'image/png',buffer:png});
let patches=0;const listener=req=>{if(req.method()==='PATCH')patches++;};page.on('request',listener);await page.click('#edit-save');await page.locator('#edit-dialog').waitFor({state:'hidden'});assert.equal(patches,1);page.off('request',listener);
let records=(await (await fetch(base+'/api/records')).json()).records;let r=records.find(r=>r.serialNo==='UI-NEW-001');assert.equal(r.modelName,'');assert.equal(r.ownerName,'修改后的登记人');assert.equal(r.photo1Url,null);assert.ok(r.photo2Url);
await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.fill('#edit-owner','不得保存');await page.setInputFiles('#edit-photo-1',{name:'bad.png',mimeType:'image/png',buffer:Buffer.from('invalid image')});await page.click('#edit-save');await page.locator('#edit-message').filter({hasText:'照片内容与格式不符'}).waitFor();assert.equal((await(await fetch(base+'/api/records')).json()).records.find(item=>item.id===r.id).ownerName,'修改后的登记人');await page.keyboard.press('Escape');
await page.click('#next-page');await page.locator('#page-status').filter({hasText:'第 2 / 2 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),2);
await page.fill('#history-query','UI-NEW-001');await page.locator('#page-status').filter({hasText:'第 1 / 1 页'}).waitFor();assert.equal(await page.locator('.archive-card').count(),1);
await page.fill('#history-query','');await page.locator('#page-status').filter({hasText:'共 22 条'}).waitFor();await page.check('#select-all');assert.equal(await page.locator('.archive-select input:checked').count(),20);
const downloadPromise=page.waitForEvent('download');const exportRequest=page.waitForRequest(req=>req.url().endsWith('/api/export/excel'));await page.click('#export-excel');assert.equal((await exportRequest).postDataJSON().ids.length,20);const download=await downloadPromise;await download.saveAs(path.join(root,'browser-export.xlsx'));
await page.screenshot({path:path.join(root,'desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});await card.getByRole('button',{name:'编辑资料 / 照片'}).click();await page.screenshot({path:path.join(root,'mobile-dialog.png'),fullPage:false});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),true);assert.equal(await page.locator('#edit-dialog').evaluate(el=>el.getBoundingClientRect().right<=innerWidth),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'PASS',root,scenarios:['real Rust without Node PATH','registration and photo','cancel','focus','atomic edit','invalid photo rollback','pagination','search resets page','current-page selection and XLSX download','desktop and narrow viewport','no browser errors']}));
}finally{if(browser)await browser.close();if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}await writeFile(path.join(root,'server.log'),output);}
+18
View File
@@ -0,0 +1,18 @@
import fs from 'node:fs';
import vm from 'node:vm';
import assert from 'node:assert/strict';
const source=fs.readFileSync(new URL('../registry/web/app.js',import.meta.url),'utf8');
const elements=new Map();
const $=id=>{if(!elements.has(id))elements.set(id,{textContent:'',value:'',disabled:false,checked:false,classList:{toggle(){},remove(){}},replaceChildren(){},append(){}});return elements.get(id);};
const context={$,currentPage:1,totalPages:3,listRequestId:0,selectedIds:new Set(),listedRecords:[],document:{createElement(){throw Error('unexpected record rendering');}},updateSelectionControls(){},fetch:async()=>{throw Error('network failure');}};
vm.createContext(context);
vm.runInContext(source.slice(source.indexOf('function updatePageButtons'),source.indexOf('function archiveStatus')),context);
vm.runInContext(source.slice(source.indexOf('async function loadRecords'),source.indexOf("$('register-form')")),context);
await assert.rejects(context.loadRecords(2),/network failure/);assert.equal(context.currentPage,1);assert.equal($('next-page').disabled,false);
let calls=[];
context.fetch=async url=>{calls.push(url);return{ok:true,json:async()=>({records:[],page:2,pageSize:20,total:45,totalPages:3})};};
await context.loadRecords(2);assert.equal(context.currentPage,2);assert.match(calls[0],/page=2&/);
let releaseOld;context.fetch=()=>new Promise(resolve=>releaseOld=resolve);const older=context.loadRecords(1);
context.fetch=async()=>({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await context.loadRecords(3);
releaseOld({ok:true,json:async()=>({records:[],total:45,totalPages:3})});await older;assert.equal(context.currentPage,3);
console.log('PASS: failed pagination retains page, successful page commits, stale response ignored');
+50
View File
@@ -0,0 +1,50 @@
$ErrorActionPreference = 'Stop'
$ridRepo = Split-Path $PSScriptRoot -Parent
$ridRoot = Join-Path ([IO.Path]::GetTempPath()) ('RID-package-review-' + [guid]::NewGuid().ToString('N'))
$ridOutput = Join-Path $ridRoot 'output'
$ridDeployment = Join-Path $ridOutput 'FPV-RID-Rust'
$ridData = Join-Path $ridDeployment 'registry/data'
New-Item -ItemType Directory -Force -Path $ridData | Out-Null
$ridSentinel = Join-Path $ridData 'registry.sqlite'
[IO.File]::WriteAllText($ridSentinel, 'sentinel data: must not be touched or packaged')
$ridBefore = (Get-FileHash -LiteralPath $ridSentinel -Algorithm SHA256).Hash
$ridRejected = $false
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridOutput } catch { $ridRejected = $true }
if (-not $ridRejected) { throw 'Dirty deployment folder was accepted' }
if ((Get-FileHash -LiteralPath $ridSentinel -Algorithm SHA256).Hash -ne $ridBefore) { throw 'Deployment data was modified' }
if (Test-Path -LiteralPath (Join-Path $ridOutput 'FPV-RID-Rust-Windows-x64.zip')) { throw 'Dirty package was published' }
$ridCleanOutput = Join-Path $ridRoot 'clean'
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
if ($LASTEXITCODE -ne 0) { throw 'Clean package failed' }
# Repackage the same clean output, proving repeat builds remain supported.
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
if ($LASTEXITCODE -ne 0) { throw 'Repeat package failed' }
$ridExistingZip = Join-Path $ridCleanOutput 'FPV-RID-Rust-Windows-x64.zip'
$ridOriginalZipHash = (Get-FileHash -LiteralPath $ridExistingZip -Algorithm SHA256).Hash
$ridUsedData = Join-Path $ridCleanOutput 'FPV-RID-Rust/registry/data'
New-Item -ItemType Directory -Force -Path $ridUsedData | Out-Null
[IO.File]::WriteAllText((Join-Path $ridUsedData 'registry.sqlite'), 'used deployment sentinel')
$ridRejected = $false
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput } catch { $ridRejected = $true }
if (-not $ridRejected) { throw 'Repackaging a used release folder was accepted' }
if ((Get-FileHash -LiteralPath $ridExistingZip -Algorithm SHA256).Hash -ne $ridOriginalZipHash) { throw 'Existing clean ZIP was overwritten on rejection' }
if ([IO.File]::ReadAllText((Join-Path $ridUsedData 'registry.sqlite')) -ne 'used deployment sentinel') { throw 'Existing deployment data was changed' }
Add-Type -AssemblyName System.IO.Compression.FileSystem
$ridZipPath = Join-Path $ridCleanOutput 'FPV-RID-Rust-Windows-x64.zip'
$ridZip = [IO.Compression.ZipFile]::OpenRead($ridZipPath)
try {
$ridExpected = @('fpv-rid-registry.exe','启动Rust版.cmd','使用说明.md','qrcode-LICENSE.txt','dependency-licenses.txt','SHA256SUMS.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
$ridActual = @($ridZip.Entries | ForEach-Object { $_.FullName.Replace('\','/') })
if ($ridActual.Count -ne $ridExpected.Count -or @(Compare-Object $ridActual $ridExpected).Count) { throw 'Archive contains unexpected files' }
} finally { $ridZip.Dispose() }
$ridZipHash = (Get-FileHash -LiteralPath $ridZipPath -Algorithm SHA256).Hash
if (-not (Get-Content -LiteralPath "$ridZipPath.sha256" -Raw).StartsWith($ridZipHash)) { throw 'ZIP checksum mismatch' }
foreach ($ridLine in Get-Content -LiteralPath (Join-Path $ridCleanOutput 'FPV-RID-Rust/SHA256SUMS.txt')) {
if ($ridLine -notmatch '^([A-F0-9]{64}) (.+)$') { throw 'Invalid checksum entry' }
$ridHash = $Matches[1]
$ridFile = Join-Path (Join-Path $ridCleanOutput 'FPV-RID-Rust') $Matches[2]
if ((Get-FileHash -LiteralPath $ridFile -Algorithm SHA256).Hash -ne $ridHash) { throw 'Release file checksum mismatch' }
}
if (@(Get-ChildItem -LiteralPath $ridCleanOutput -Directory -Filter '.package-*').Count) { throw 'Owned staging files were left behind' }
Write-Output "PASS: dirty deployment refused and preserved; repeat package, whitelist, ZIP and file checksums verified. Evidence: $ridRoot"
+17
View File
@@ -0,0 +1,17 @@
import {mkdtemp,cp,access} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
const repo=path.resolve(import.meta.dirname,'..');const root=await mkdtemp(path.join(tmpdir(),'RID-便携验收-'));const app=path.join(root,'发布程序');
await cp(path.join(repo,'dist/FPV-RID-Rust'),app,{recursive:true});
let occupied=false;try{await fetch('http://127.0.0.1:8787/');occupied=true;}catch{}if(occupied)throw Error('8787 已被占用');
const exe=path.join(app,'fpv-rid-registry.exe');let output='';
const child=spawn(exe,[],{cwd:root,windowsHide:true,env:{...process.env,PATH:'C:\\Windows\\System32'},stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);let spawnError;child.on('error',e=>spawnError=e);
try{
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output||String(spawnError));try{if((await fetch('http://127.0.0.1:8787/api/records')).ok)break;}catch{}await new Promise(r=>setTimeout(r,100));}
await access(path.join(app,'registry/data/registry.sqlite'));await assert.rejects(access(path.join(root,'registry/data/registry.sqlite')));
const page=await fetch('http://127.0.0.1:8787/');assert.equal(page.status,200);assert.match(await page.text(),/edit-dialog/);
const second=spawn(exe,['--data-root',path.join(root,'第二实例')],{windowsHide:true,stdio:['ignore','pipe','pipe']});let stderr='';second.stderr.on('data',b=>stderr+=b);const code=await new Promise((resolve,reject)=>{second.on('exit',resolve);second.on('error',reject);});assert.notEqual(code,0);assert.match(stderr,/8787/);await assert.rejects(access(path.join(root,'第二实例/registry/data/registry.sqlite')));
console.log(JSON.stringify({status:'PASS',root,scenarios:['published exe','Chinese install path','different working directory','no Node PATH','embedded webpage','port conflict without new database']}));
}finally{if(child.exitCode===null&&!spawnError){const exit=new Promise(r=>child.once('exit',r));child.kill();await exit;}}
+115
View File
@@ -0,0 +1,115 @@
// Uses built-in Node APIs as test tooling. Runs only Rust against disposable data.
import {mkdtemp,mkdir,writeFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import path from 'node:path';
import {spawn,execFileSync} from 'node:child_process';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {inflateRawSync} from 'node:zlib';
const repo=path.resolve(import.meta.dirname,'..');
const root=await mkdtemp(path.join(tmpdir(),'RID-中文验证-'));
const base='http://127.0.0.1:8787';
const png='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aocsAAAAASUVORK5CYII=';
let child;let output='';
let spawnError;
async function start(command,args){
// Never attach to, or mutate, an unrelated service already listening on this port.
let occupied=false;try{await fetch(base+'/api/records',{signal:AbortSignal.timeout(1000)});occupied=true;}catch{}
if(occupied)throw Error('8787 已被占用,请关闭登记站再执行独立验收');
output='';spawnError=null;child=spawn(command,args,{cwd:root,windowsHide:true,stdio:['ignore','pipe','pipe']});
child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);
child.on('error',e=>{spawnError=e;output+=e.message;});
for(let i=0;i<150;i++){if(spawnError||child.exitCode!==null)throw Error(output);try{const r=await fetch(base+'/api/records');if(r.ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('启动超时 '+output);
}
async function stop(){if(child&&!spawnError&&child.exitCode===null){const exited=new Promise(r=>child.once('exit',r));if(child.kill())await exited;}child=null;}
async function api(route,method='GET',body,status=200){const r=await fetch(base+route,{method,headers:body?{'content-type':'application/json'}:{},body:body?JSON.stringify(body):undefined});const v=await r.json();assert.equal(r.status,status,JSON.stringify(v));return v;}
function unzip(bytes){
const end=bytes.lastIndexOf(Buffer.from([0x50,0x4b,0x05,0x06]));assert.ok(end>=0);
const entries=new Map();let offset=bytes.readUInt32LE(end+16);
for(let i=0;i<bytes.readUInt16LE(end+10);i++){
assert.equal(bytes.readUInt32LE(offset),0x02014b50);
const method=bytes.readUInt16LE(offset+10),size=bytes.readUInt32LE(offset+20),rawSize=bytes.readUInt32LE(offset+24);
const nameLength=bytes.readUInt16LE(offset+28),extra=bytes.readUInt16LE(offset+30),comment=bytes.readUInt16LE(offset+32),local=bytes.readUInt32LE(offset+42);
const name=bytes.toString('utf8',offset+46,offset+46+nameLength);
assert.equal(bytes.readUInt32LE(local),0x04034b50);
const start=local+30+bytes.readUInt16LE(local+26)+bytes.readUInt16LE(local+28);
const compressed=bytes.subarray(start,start+size);assert.ok(method===0||method===8);
const data=method===8?inflateRawSync(compressed):compressed;assert.equal(data.length,rawSize);
entries.set(name,data);offset+=46+nameLength+extra+comment;
}return entries;
}
async function exports(id,label){
for(const kind of ['archive','excel']){
const r=await fetch(base+'/api/export/'+kind,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({ids:[id]})});assert.equal(r.status,200);
const bytes=Buffer.from(await r.arrayBuffer());const entries=unzip(bytes);
if(kind==='archive'){
const manifest=JSON.parse(entries.get('档案库/records.json').toString());assert.equal(manifest[0].id,id);assert.equal(manifest[0].fpvCode,'FPV00000001');
assert.deepEqual(entries.get('档案库/照片/TEST-SN-001-1.png'),Buffer.from(png.split(',')[1],'base64'));
assert.match(entries.get('档案库/档案卡/TEST-SN-001.html').toString(),/data:image\/png;base64,/);
}else{
assert.ok(entries.has('[Content_Types].xml'));assert.ok(entries.has('xl/workbook.xml'));assert.ok(entries.has('xl/worksheets/sheet1.xml'));
const xml=[...entries.values()].map(b=>b.toString()).join('');assert.ok(xml.includes(id));assert.ok(xml.includes('TEST-SN-001'));assert.ok(xml.includes('模块 SN'));
}
await writeFile(path.join(root,`${label}-${kind}.zip`),bytes);
}
const r=await fetch(base+`/api/records/${id}/archive`);const html=await r.text();assert.match(html,/data:image\/png;base64,/);assert.ok(!html.includes('${'));assert.ok(html.includes('&lt;测试&gt;'));
}
try{
const cargo=process.env.CARGO_HOME?path.join(process.env.CARGO_HOME,'bin/cargo.exe'):'D:/Rust_Contact/util/cargo/bin/cargo.exe';
const metadata=process.argv[2]?null:JSON.parse(execFileSync(cargo,['metadata','--format-version','1','--no-deps'],{cwd:repo,encoding:'utf8',windowsHide:true}));
const exe=path.resolve(process.argv[2]||path.join(metadata.target_directory,'release/fpv-rid-registry.exe'));
await start(exe,['--data-root',root]);
const a=await api('/api/records','POST',{serialNo:'TEST-SN-001',uasCode:'FPV00000001',modelName:'<测试>',ownerName:'原登记人',photo1:png});
const id=a.record.id;assert.match(id,/^[0-9a-f]{36}$/);assert.equal(a.existing,false);
const b=await api('/api/records','POST',{serialNo:'TEST-SN-001',modelName:'',ownerName:''});assert.equal(b.existing,true);assert.equal(b.record.modelName,'<测试>');
await api('/api/records','POST',{serialNo:'TEST-SN-002',uasCode:'FPV00000001'},400);
await api('/api/records','POST',{serialNo:'x'},400);
assert.equal((await api('/api/records?q='+encodeURIComponent('原登记人'))).records.length,1);
await exports(id,'rust-initial');await stop();
const dbPath=path.join(root,'registry/data/registry.sqlite');
let db=new DatabaseSync(dbPath);const before=db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes;db.close();
await start(exe,['--data-root',root]);
assert.equal((await api('/api/records')).records[0].id,id);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).id,id);
await api('/api/resolve?url='+encodeURIComponent('http://example.com/r/'+id),'GET',undefined,400);
await exports(id,'rust');db=new DatabaseSync(dbPath);assert.equal(db.prepare('SELECT hex(image) AS bytes FROM photos').get().bytes,before);db.close();
const blocked=await fetch(base+'/api/records',{headers:{origin:'https://example.com'}});assert.equal(blocked.status,403);
const p=await api('/api/records?page=1&pageSize=1');assert.equal(p.total,1);assert.equal(p.records.length,1);
await api('/api/records?page=0','GET',undefined,400);
const edited=await api('/api/records/'+id,'PATCH',{modelName:'',ownerName:'新登记人'});assert.equal(edited.record.modelName,'');
await api('/api/records/'+id,'PATCH',{serialNo:'OTHER-SN'},400);
await api('/api/records/'+id,'PATCH',{ownerName:'must rollback',photo1:'invalid'},400);
assert.equal((await api('/api/resolve?url='+encodeURIComponent(base+'/r/'+id))).ownerName,'新登记人');
await api('/api/records/'+id,'PATCH',{photo1:null,photo2:png});
assert.equal((await fetch(base+'/api/records/'+id+'/photos/2')).status,200);
await api('/api/records/'+id+'/photos/1','DELETE');await api('/api/records/'+id+'/photos/1','GET',undefined,404);
await api('/api/records','POST',{serialNo:'TEST-SN-001',photo1:png});
// Simulate an archive directory failure without modifying the active database.
await stop();await rm(path.join(root,'档案库'),{recursive:true});await writeFile(path.join(root,'档案库'),'blocked');
await start(exe,['--data-root',root]);
const pending=await api('/api/records','POST',{serialNo:'TEST-SN-003',ownerName:'已保存'});assert.equal(pending.archiveStatus,'pending');assert.ok(pending.warning);
assert.equal((await api('/api/archive/status')).archiveStatus,'pending');
await api('/api/archive/retry','POST',{},500);
db=new DatabaseSync(dbPath);assert.ok(db.prepare("SELECT value FROM registry_meta WHERE key='archive_pending'").get());db.close();
await rm(path.join(root,'档案库'));await api('/api/archive/retry','POST',{});
assert.equal((await api('/api/records')).records.length,2);
await api('/api/records/'+id,'DELETE');assert.equal((await api('/api/records')).records.length,1);
await api('/api/records/'+id,'PATCH',{ownerName:'resurrect',photo1:png},404);
await stop();await start(exe,['--data-root',root]);assert.equal((await api('/api/records')).records.length,1);await stop();
db=new DatabaseSync(path.join(root,'档案库/登记数据库.sqlite'));assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,1);assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check,'ok');db.close();
const legacyRoot=path.join(root,'legacy-regression');
await mkdir(path.join(legacyRoot,'registry/data'),{recursive:true});
const legacyRows=[{id:'1'.repeat(36),serialNo:'IMPORT-001',uasCode:'FPV00000001',createdAt:'2020-01-01T00:00:00.000Z'},{id:'2'.repeat(36),serialNo:'IMPORT-002',uasCode:'FPV00000002'}];
const legacyFile=path.join(legacyRoot,'registry/data/records.json');
await writeFile(legacyFile,JSON.stringify(legacyRows));
const rejected=spawn(exe,['--data-root',legacyRoot],{windowsHide:true,stdio:['ignore','pipe','pipe']});
let importError='';rejected.stderr.on('data',b=>importError+=b);
const exitCode=await new Promise((resolve,reject)=>{rejected.once('exit',resolve);rejected.once('error',reject);});
assert.notEqual(exitCode,0);assert.match(importError,/第 2 条/);
db=new DatabaseSync(path.join(legacyRoot,'registry/data/registry.sqlite'));
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM records').get().n,0);
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM registry_meta').get().n,0);db.close();
legacyRows[1].createdAt='2020-01-01T00:00:00.000Z';await writeFile(legacyFile,JSON.stringify(legacyRows));
await start(exe,['--data-root',legacyRoot]);assert.equal((await api('/api/records')).records.length,2);await stop();
console.log(JSON.stringify({status:'PASS',root,scenarios:['Rust registration','Rust database restart','photo bytes','QR','ZIP/XLSX contents','HTML escaping','origin','PATCH','photo deletion','pagination','archive fault and retry','restart','backup integrity','invalid legacy import fails visibly and rolls back','corrected legacy file retries successfully']}));
}finally{await stop();}