refactor(registry): 生产环境数据库访问迁移至 SQLx 并统一测试端口策略

将 rusqlite 从生产依赖移至 dev-dependencies,正式数据库操作全部
由 SQLx 完成;rusqlite 仅保留用于测试夹具及旧数据库兼容验证。

UI 验收脚本移除 HTTP 代理和动态端口分配,统一通过
ui-test-port.mjs 的 assertUiPortAvailable 直连 8787 端口,
确保测试与正式实例串行执行。

新增 doc/registry/rust/axum-sqlx-architecture.md 记录模块职责、
数据兼容、退出资源回收及验证维护规范。

修复接收器页面按钮缺少显式 height 导致的布局偏差。
```
This commit is contained in:
2026-10-27 20:04:34 +08:00
parent a68dc50798
commit 281af4fe3d
42 changed files with 2435 additions and 1301 deletions
+8 -14
View File
@@ -1,3 +1,6 @@
import {UI_URL, assertUiPortAvailable} from './ui-test-port.mjs';
const base=UI_URL;
await assertUiPortAvailable();
// Real Rust/Wasm acceptance in an isolated database. Never opens receiver transports.
import {mkdtemp,writeFile,readFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
@@ -5,27 +8,18 @@ import path from 'node:path';
import {spawn} from 'node:child_process';
import {createRequire} from 'node:module';
import assert from 'node:assert/strict';
import http from 'node:http';
import net from 'node:net';
const {chromium}=createRequire(import.meta.url)('playwright');
const root=await mkdtemp(path.join(tmpdir(),'RID-realtime-layout-'));
const exe=process.argv[2]||'D:/Rust_Contact/util/target/Rid_Drone_Receivev/release/fpv-rid-registry-fullstack.exe';
const base='http://127.0.0.1:18887';
// Keep production origin checks unchanged. Only this isolated proxy maps the test origin.
const sockets=new Set();
const proxy=http.createServer(async(req,res)=>{if(process.env.RID_SOURCE_ASSETS==='1'&&!req.url.startsWith('/api/')){const pathname=new URL(req.url,'http://localhost').pathname;const relative=pathname==='/'||pathname==='/realtime'?'index.html':pathname.slice(1);if(!relative.includes('..'))try{let bytes;try{bytes=await readFile(path.join('crates/web-ui/public',relative));}catch{bytes=await readFile(path.join('dist/web-ui',relative));}res.writeHead(200,{'content-type':relative.endsWith('.html')?'text/html':relative.endsWith('.css')?'text/css':relative.endsWith('.wasm')?'application/wasm':relative.endsWith('.svg')?'image/svg+xml':relative.endsWith('.png')?'image/png':'text/javascript'});res.end(bytes);return}catch{}}const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';const upstream=http.request({hostname:'127.0.0.1',port:18888,path:req.url,method:req.method,headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});upstream.on('error',()=>{res.writeHead(502);res.end()});req.pipe(upstream)});
proxy.on('upgrade',(req,socket,head)=>{const upstream=net.connect(18888,'127.0.0.1');sockets.add(socket);sockets.add(upstream);upstream.on('connect',()=>{const headers={...req.headers,host:'127.0.0.1:8787'};if(headers.origin===base)headers.origin='http://127.0.0.1:8787';upstream.write(`GET ${req.url} HTTP/1.1\r\n${Object.entries(headers).map(([k,v])=>`${k}: ${v}`).join('\r\n')}\r\n\r\n`);if(head.length)upstream.write(head);socket.pipe(upstream);upstream.pipe(socket)});upstream.on('error',()=>socket.destroy());socket.on('error',()=>upstream.destroy());socket.on('close',()=>{upstream.destroy();sockets.delete(socket);sockets.delete(upstream)})});
let occupied=false;try{await fetch(base,{signal:AbortSignal.timeout(800)});occupied=true;}catch{}if(occupied)throw Error('18887 occupied; preserving existing service');
const backendOccupied=await new Promise(resolve=>{const socket=net.connect(18888,'127.0.0.1');socket.once('connect',()=>{socket.destroy();resolve(true)});socket.once('error',()=>resolve(false));socket.setTimeout(800,()=>{socket.destroy();resolve(false)})});if(backendOccupied)throw Error('18888 occupied; preserving existing service');
let output='',child,browser;const errors=[],csp=[];
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',RID_TEST_PORT:'18888'},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message);}
function start(){child=spawn(exe,['--data-root',root,'--simulation-api'],{env:{...process.env,PATH:'C:\\Windows\\System32',},windowsHide:true,stdio:['ignore','pipe','pipe']});child.stdout.on('data',b=>output+=b);child.stderr.on('data',b=>output+=b);child.on('error',e=>output+=e.message);}
async function ready(){for(let i=0;i<150;i++){if(child.exitCode!==null)throw Error(output);try{if((await fetch(base+'/api/appearance')).ok)return;}catch{}await new Promise(r=>setTimeout(r,100));}throw Error('server timeout '+output);}
async function stop(){if(child&&child.exitCode===null){const done=new Promise(r=>child.once('exit',r));child.kill();await done;}}
const key='rid.realtime.layout.v1';
let report={};let heartbeat;let sequence=1;
const wait=ms=>new Promise(r=>setTimeout(r,ms));
try {
await new Promise((resolve,reject)=>{proxy.once('error',reject);proxy.listen(18887,'127.0.0.1',resolve)});start();await ready();
start();await ready();
browser=await chromium.launch({headless:true,executablePath:process.env.RID_BROWSER_PATH||'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'});
const context=await browser.newContext({viewport:{width:1600,height:1000}});const page=await context.newPage();
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(/violates.*Content Security|Refused.*policy/i.test(m.text()))csp.push(m.text())});
@@ -66,11 +60,11 @@ try {
const afterStart=requests.status;await wait(3200);const afterRate=requests.status-afterStart;assert.ok(afterRate<=beforeRate+2,{beforeRate,afterRate});
await page.getByRole('button',{name:'目标快照与事件',exact:true}).click();
// Generate real transport events without writing receiver configuration.
for(let i=0;i<23;i++){for(const socket of [...sockets])socket.destroy();await page.locator('.rt-status').filter({hasText:'连接断开'}).waitFor();assert.equal(await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled(),true);await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();}
for(let i=0;i<23;i++){await stop();await page.locator('.rt-status').filter({hasText:'连接断开'}).waitFor();assert.equal(await page.getByRole('button',{name:'聚焦此目标',exact:true}).isDisabled(),true);start();await ready();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();}
assert.equal(await page.locator('.live-events li').count(),64);
await grip.focus();await page.keyboard.press('Home');const scroller=page.locator('#rt-event-scroll');await scroller.evaluate(e=>e.scrollTop=Math.min(400,e.scrollHeight/2));
const anchor=await scroller.evaluate(e=>{const r=e.getBoundingClientRect();return [...e.querySelectorAll('li')].map(li=>({text:li.textContent,y:li.getBoundingClientRect().top-r.top})).find(x=>x.y>=0)});
for(const socket of [...sockets])socket.destroy();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(200);
await stop();start();await ready();await page.locator('.rt-status').filter({hasText:'已连接'}).waitFor();await wait(200);
if(anchor){const next=await scroller.evaluate((e,a)=>{const li=[...e.querySelectorAll('li')].find(li=>li.textContent===a.text);return li?li.getBoundingClientRect().top-e.getBoundingClientRect().top:null},anchor);assert.ok(next!==null&&Math.abs(next-anchor.y)<4,JSON.stringify({anchor,next}));}
// Restore a normal useful desktop frame with live Worker data.
await ingest(batch.map(x=>({...x,sequence:++sequence})));await page.getByRole('textbox',{name:'搜索实时目标'}).fill('LAYOUT-0000');await page.getByRole('button',{name:'LAYOUT-0000',exact:true}).click();
@@ -91,4 +85,4 @@ try {
const realtimeStatus=await (await fetch(base+'/api/realtime/status')).json();assert.equal(realtimeStatus.clients,1);
assert.deepEqual(errors,[]);assert.deepEqual(csp,[]);
report={status:'PASS',root,exe,serverPid:child.pid,clients:realtimeStatus.clients,frames,requests,beforeRate,afterRate,checks:['embedded-assets-match-build','empty','real-worker-120-targets','search-pagination','local-record-match-unmatched-error','long-id','safe-focus','drag-keyboard','reload-persistence','hide-restore-focus','receiver-20-switches','events-bounded-at-64','event-scroll-anchor','three-themes-six-sizes-including-low-height','hidden-workspace-keeps-preferences','compact-select-focus','zoom-125-150','corrupt-storage'],note:'Synthetic input; no physical receiver transport opened.'};console.log(JSON.stringify(report));
}finally{clearInterval(heartbeat);if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({layout:document.getElementById('rt-layout')?.outerHTML.slice(0,2000),metrics:window.ridMap?.metrics()})).catch(()=>null)}));}}await browser.close();}await stop();for(const s of sockets)s.destroy();const closed=new Promise(r=>proxy.close(r));proxy.closeAllConnections();await closed;await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'layout-report.json'),JSON.stringify({...report,errors,csp},null,2));}
}finally{clearInterval(heartbeat);if(browser){if(report.status!=='PASS'){const p=browser.contexts()[0]?.pages()[0];if(p){await p.screenshot({path:path.join(root,'failure.png')}).catch(()=>{});console.log(JSON.stringify({root,errors,csp,diagnostic:await p.evaluate(()=>({layout:document.getElementById('rt-layout')?.outerHTML.slice(0,2000),metrics:window.ridMap?.metrics()})).catch(()=>null)}));}}await browser.close();}await stop();await writeFile(path.join(root,'server.log'),output);await writeFile(path.join(root,'layout-report.json'),JSON.stringify({...report,errors,csp},null,2));}