feat(registry): 迁移至 Rust + Axum + SQLite 并新增编辑、分页和档案同步功能 - 后端从 Node.js 迁移到 Rust,使用 Axum 框架和 SQLite 存储 - 新增档案编辑对话框,支持修改机型、登记人及替换/删除照片 - 档案列表增加分页导航(每页20条) - 新增档案同步状态提示及手动重试同步按钮 - Node.js 原版后端及网页保留为回退方案,移至 legacy-web 目录 - 更新 .gitignore 添加 Rust 构建产物(target、dist) - 更新 README 文档,补充 Rust 启动、开发、检查及打包说明 - 启动源码版.cmd 默认转发至 Rust 版启动脚本 ```
116 lines
9.9 KiB
JavaScript
116 lines
9.9 KiB
JavaScript
// 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('<测试>'));
|
|
}
|
|
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();}
|