feat(receiver): 持久化接收机发现端点并支持位置备注信息

This commit is contained in:
zyp
2026-11-30 09:29:33 +08:00
parent 1d6d7a277e
commit 5e761fc064
95 changed files with 15744 additions and 701 deletions
+8 -3
View File
@@ -1,13 +1,18 @@
$ErrorActionPreference = 'Stop'
$ErrorActionPreference = 'Stop'
$ridTools = 'D:/Rust_Contact/util/tools/rid-map-downloader/0.1.0'
$env:GOCACHE = 'D:/Rust_Contact/util/tools/go-cache'
$env:GOMODCACHE = 'D:/Rust_Contact/util/tools/go-modules'
$ridGo = (Get-Command go -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1).Source
if (-not $ridGo) { $ridGo = 'D:/Rust_Contact/util/tools/go/1.27.4/go/bin/go.exe' }
if (-not (Test-Path -LiteralPath $ridGo -PathType Leaf)) {
throw '找不到 Go。请将 go.exe 加入 PATH 或安装到项目统一工具目录。'
}
New-Item -ItemType Directory -Force $ridTools | Out-Null
Push-Location (Join-Path $PSScriptRoot 'map-downloader')
try {
go test ./...
& $ridGo test ./...
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader tests failed' }
go build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
& $ridGo build -trimpath -ldflags '-s -w' -o (Join-Path $ridTools 'rid-map-downloader.exe') .
if ($LASTEXITCODE -ne 0) { throw 'Go map downloader build failed' }
Copy-Item -LiteralPath 'LICENSE-upstream.txt' -Destination $ridTools
$env:RID_MAP_DOWNLOADER = Join-Path $ridTools 'rid-map-downloader.exe'
+93 -11
View File
@@ -1,4 +1,4 @@
param([string]$OutputRoot)
param([string]$OutputRoot, [string]$MapSeedRoot)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'rust-env.ps1')
@@ -7,10 +7,21 @@ 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', 'rid-map-downloader.exe', 'map-downloader-LICENSE.txt', '启动Rust版.cmd', '使用说明.md', 'config.example.json', 'third-party-licenses.txt', 'dependency-licenses.txt', 'build-info.json', 'SHA256SUMS.txt')
$ridTarget = 'x86_64-pc-windows-msvc'
$ridMapReadme = '程序自动读取 EXE 同目录的 map_cache。请从地图管理下载离线瓦片,或将已有瓦片放入此目录。'
function Assert-CleanDestination {
if (Test-Path -LiteralPath $ridDestination) {
foreach ($ridEntry in Get-ChildItem -LiteralPath $ridDestination -Force) {
if ($ridEntry.PSIsContainer -and $ridEntry.Name -eq 'map_cache' -and
!($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
$files = @(Get-ChildItem -LiteralPath $ridEntry.FullName -Force)
if ($files.Count -eq 0 -or ($files.Count -eq 1 -and $files[0].Name -eq 'README.txt' -and
!$files[0].PSIsContainer -and !($files[0].Attributes -band [IO.FileAttributes]::ReparsePoint) -and
([IO.File]::ReadAllText($files[0].FullName).TrimEnd() -ceq $ridMapReadme))) {
continue
}
}
if ($ridEntry.PSIsContainer -or ($ridEntry.Name -notin $ridWhitelist -and $ridEntry.Name -ne 'qrcode-LICENSE.txt') -or
($ridEntry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "发布目录含运行数据或非发布文件,已停止打包并保留原内容:$($ridEntry.FullName)。请通过 -OutputRoot 指定单独的输出目录。"
@@ -19,6 +30,41 @@ function Assert-CleanDestination {
}
}
function Get-RidMapSeed([string]$Root) {
$rootItem = Get-Item -LiteralPath $Root -Force
if (-not $rootItem.PSIsContainer -or ($rootItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "地图种子目录必须为普通目录:$Root"
}
$kinds = if ($rootItem.Name -eq 'map_cache') { @('portable') } else { @('cache', 'offline') }
foreach ($kind in $kinds) {
$source = if ($kind -eq 'portable') { $rootItem.FullName } else { Join-Path $rootItem.FullName $kind }
$destination = if ($kind -eq 'portable') { 'map_cache' } else { "maps/$kind" }
if (-not (Test-Path -LiteralPath $source)) { continue }
$sourceItem = Get-Item -LiteralPath $source -Force
if (-not $sourceItem.PSIsContainer -or ($sourceItem.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "不能从链接或非目录读取地图:$source"
}
foreach ($item in Get-ChildItem -LiteralPath $source -Recurse -Force) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "地图种子目录含链接:$($item.FullName)"
}
if ($item.PSIsContainer) { continue }
$relative = $item.FullName.Substring($source.Length + 1).Replace('\','/')
$layer = '(vec_w|cva_w|img_w|cia_w)'
if ($kind -ne 'cache' -and $relative -cmatch "^$layer[.]mbtiles$") {
[pscustomobject]@{ Source=$item.FullName; Path="$destination/$relative" }
} elseif ($relative -cmatch "^$layer/([0-9]{1,2})/([0-9]{1,7})/([0-9]{1,7})[.](tile|png|jpg|jpeg)$") {
$z = [int]$Matches[2]
$x = [int]$Matches[3]
$y = [int]$Matches[4]
if ($z -le 18 -and $x -lt (1 -shl $z) -and $y -lt (1 -shl $z) -and ($kind -ne 'cache' -or $Matches[5] -eq 'tile')) {
[pscustomobject]@{ Source=$item.FullName; Path="$destination/$relative" }
}
}
}
}
}
function Get-RidSourceManifest {
$ridInputs = @('Cargo.toml','Cargo.lock','rust-toolchain.toml','build.rs','config.example.json') | ForEach-Object { Get-Item -LiteralPath (Join-Path $ridRepo $_) }
$ridInputs += @('src','crates','xtask','scripts','.cargo') | ForEach-Object { Get-ChildItem -LiteralPath (Join-Path $ridRepo $_) -Recurse -File }
@@ -27,6 +73,13 @@ function Get-RidSourceManifest {
# Refuse a used deployment folder before building or changing any published files.
Assert-CleanDestination
$ridSeedFiles = @()
$ridPaths = $ridWhitelist + 'map_cache/README.txt'
if ($MapSeedRoot) {
$ridSeedFiles = @(Get-RidMapSeed $MapSeedRoot | Sort-Object Path)
$ridPaths += 'registry/data/README.txt'
$ridPaths += @($ridSeedFiles | ForEach-Object Path)
}
& (Join-Path $PSScriptRoot 'build-map-downloader.ps1')
$ridStageRoot = Join-Path $ridOutputRoot ('.package-' + [guid]::NewGuid().ToString('N'))
$ridStage = Join-Path $ridStageRoot 'FPV-RID-Rust'
@@ -41,24 +94,37 @@ try {
$ridInitialManifestJson = ConvertTo-Json -InputObject $ridInitialManifest -Depth 5 -Compress
cargo xtask web
if ($LASTEXITCODE -ne 0) { throw 'Rust frontend build failed' }
cargo build --release --locked -p fpv-rid-registry
cargo build --release --locked -p fpv-rid-registry --target $ridTarget
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-fullstack.exe') -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
Copy-Item -LiteralPath (Join-Path $ridMetadata.target_directory "$ridTarget/release/fpv-rid-registry-fullstack.exe") -Destination (Join-Path $ridStage 'fpv-rid-registry.exe')
Copy-Item -LiteralPath $env:RID_MAP_DOWNLOADER -Destination (Join-Path $ridStage 'rid-map-downloader.exe')
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'map-downloader/LICENSE-upstream.txt') -Destination (Join-Path $ridStage 'map-downloader-LICENSE.txt')
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 'config.example.json') -Destination $ridStage
Copy-Item -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') -Destination (Join-Path $ridStage 'third-party-licenses.txt')
Get-Content -LiteralPath (Join-Path $ridRepo 'crates/web-ui/workbench/leaflet/LICENSE.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'third-party-licenses.txt') -Encoding utf8
$ridLicenses = cargo tree --workspace --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
Get-Content -LiteralPath (Join-Path $ridRepo 'crates/web-ui/public/vendor/LICENSE.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
Get-Content -LiteralPath (Join-Path $ridStage 'third-party-licenses.txt') | Add-Content -LiteralPath (Join-Path $ridStage 'dependency-licenses.txt') -Encoding utf8
$ridSourceManifest = @(Get-RidSourceManifest)
if ((ConvertTo-Json -InputObject $ridSourceManifest -Depth 5 -Compress) -ne $ridInitialManifestJson) { throw '源码在构建期间发生变化,已停止发布并保留原发布包;请在源码稳定后重新构建。' }
foreach ($ridSeed in $ridSeedFiles) {
$ridSeedDestination = Join-Path $ridStage $ridSeed.Path
New-Item -ItemType Directory -Force -Path (Split-Path $ridSeedDestination -Parent) | Out-Null
Copy-Item -LiteralPath $ridSeed.Source -Destination $ridSeedDestination
}
New-Item -ItemType Directory -Force -Path (Join-Path $ridStage 'map_cache') | Out-Null
$ridMapReadme | Set-Content -LiteralPath (Join-Path $ridStage 'map_cache/README.txt') -Encoding utf8
if ($MapSeedRoot) {
New-Item -ItemType Directory -Force -Path (Join-Path $ridStage 'registry/data') | Out-Null
'应用首次启动时在此创建 SQLite 数据库。已有业务数据请在停机备份后单独迁移。' |
Set-Content -LiteralPath (Join-Path $ridStage 'registry/data/README.txt') -Encoding utf8
}
$ridBuildInfo = [ordered]@{
builtAtUtc=[DateTime]::UtcNow.ToString('o')
gitRevision=(git rev-parse HEAD)
@@ -67,23 +133,31 @@ try {
trunk='0.22.0'
wasmBindgen='0.2.129'
executableSha256=(Get-FileHash -LiteralPath (Join-Path $ridStage 'fpv-rid-registry.exe') -Algorithm SHA256).Hash
mapSeedFileCount=$ridSeedFiles.Count
sourceManifest=$ridSourceManifest
}
$ridBuildInfo | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $ridStage 'build-info.json') -Encoding utf8
$ridWhitelist | Where-Object { $_ -ne 'SHA256SUMS.txt' } | ForEach-Object {
$ridPaths | 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) {
$ridActual = @(Get-ChildItem -LiteralPath $ridStage -Recurse -File -Force | ForEach-Object {
$_.FullName.Substring($ridStage.Length + 1).Replace('\','/')
})
if ($ridActual.Count -ne $ridPaths.Count -or @(Compare-Object $ridActual $ridPaths -CaseSensitive).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)
foreach ($ridName in $ridPaths) {
$ridPublishFile = Join-Path $ridDestination $ridName
$ridParent = Split-Path $ridPublishFile -Parent
if (-not (Test-Path -LiteralPath $ridParent)) {
New-Item -ItemType Directory -Force -Path $ridParent | Out-Null
}
Copy-Item -LiteralPath (Join-Path $ridStage $ridName) -Destination $ridPublishFile
}
$ridObsoleteLicense = Join-Path $ridDestination 'qrcode-LICENSE.txt'
if (Test-Path -LiteralPath $ridObsoleteLicense -PathType Leaf) { Remove-Item -LiteralPath $ridObsoleteLicense }
@@ -98,11 +172,19 @@ try {
if ($ridBuildLock) { $ridBuildLock.Dispose() }
Pop-Location
# Clean only files this invocation created. Never recursively delete an output directory.
foreach ($ridName in $ridWhitelist) {
foreach ($ridName in $ridPaths) {
$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 $ridStage -PathType Container) {
Get-ChildItem -LiteralPath $ridStage -Directory -Recurse -Force |
Sort-Object { $_.FullName.Length } -Descending | ForEach-Object {
if (@(Get-ChildItem -LiteralPath $_.FullName -Force).Count -eq 0) {
[IO.Directory]::Delete($_.FullName, $false)
}
}
if (@(Get-ChildItem -LiteralPath $ridStage -Force).Count -eq 0) { [IO.Directory]::Delete($ridStage, $false) }
}
if ((Test-Path -LiteralPath $ridStageRoot -PathType Container) -and @(Get-ChildItem -LiteralPath $ridStageRoot -Force).Count -eq 0) { Remove-Item -LiteralPath $ridStageRoot }
}
+55 -15
View File
@@ -7,38 +7,78 @@ import vm from 'node:vm';
const source=(await readFile(new URL('../crates/web-ui/public/history-map-adapter.js',import.meta.url),'utf8'))
.replace(/^import .*;$/gm,'').replaceAll('export function ','function ');
test('historical segments stay separate and playback moves only the marker',()=>{
const markerSource=await readFile(new URL('../crates/web-ui/workbench/drone-map.js',import.meta.url),'utf8');
test('replay keeps real segments, changes its basemap and advances the marker on the route',async()=>{
let map,marker,fitCount=0,removed=false;
const sources=new Map();
class FakeMap{
constructor(){map=this;this.handlers={};}
constructor(options){
map=this;this.handlers={};this.style=options.style;
for(const [id,value] of Object.entries(this.style.sources)) this.addSource(id,value);
}
on(name,fn){this.handlers[name]=fn;}
addControl(){}
addSource(id,value){sources.set(id,{data:value.data,setData(data){this.data=data;}});}
addSource(id,value){sources.set(id,{...value,setData(data){this.data=data;},setTiles(tiles){this.tiles=tiles;}});}
addLayer(){}
getSource(id){return sources.get(id);}
getLayer(id){return this.style.layers.find(layer=>layer.id===id);}
setLayoutProperty(id,key,value){this.getLayer(id).layout[key]=value;}
fitBounds(){fitCount++;}
resize(){}
remove(){removed=true;}
}
class Marker{setLngLat(point){this.position=[...point];marker=this;return this;}addTo(){return this;}remove(){}}
class Marker{
constructor({element}){this.element=element;}
getElement(){return this.element;}
setLngLat(point){this.position=[...point];marker=this;return this;}
getLngLat(){return {lng:this.position[0],lat:this.position[1]};}
setRotation(angle){this.angle=angle;return this;}
getRotation(){return this.angle;}
addTo(){return this;}
remove(){}
}
class MercatorCoordinate{
constructor(x,y){Object.assign(this,{x,y});}
static fromLngLat([lng,lat]){return new MercatorCoordinate(lng/360,lat/360);}
toLngLat(){return {toArray:()=>[this.x*360,this.y*360]};}
}
class Bounds{constructor(){this.points=[];}extend(point){this.points.push(point);}isEmpty(){return this.points.length===0;}}
const context=vm.createContext({window:{dispatchEvent(){}},document:{getElementById(){return {};}},
ResizeObserver:class{observe(){}disconnect(){}},Event:class{},Number,Array,Math,
ml:{setWorkerUrl(){},Map:FakeMap,Marker,LngLatBounds:Bounds,NavigationControl:class{},AttributionControl:class{}},
attachTileBuffer:()=>({destroy(){}})});
function element(){
const styles = new Map();
return {setAttribute(){},append(){},style:{setProperty:(name,value)=>styles.set(name,value),getPropertyValue:name=>styles.get(name)}};
}
const context=vm.createContext({window:{dispatchEvent(){}},document:{getElementById(){return {};},createElement:element},
ResizeObserver:class{observe(){}disconnect(){}},Event:class{},Number,Array,Math,URLSearchParams,
fetch:async()=>({ok:true,json:async()=>({entries:[{registered:true}]})}),
ml:{setWorkerUrl(){},Map:FakeMap,Marker,MercatorCoordinate,LngLatBounds:Bounds,NavigationControl:class{},AttributionControl:class{}},
attachTileBuffer:()=>({destroy(){},schedule(){}})});
vm.runInContext(markerSource,context);
vm.runInContext(source,context);
vm.runInContext('open({longitude:118.77,latitude:32.04,zoom:15,basemap:"road"})',context);
vm.runInContext('setPoints([{longitude:118,latitude:32,segmentStart:true},{longitude:119,latitude:32,segmentStart:false},{longitude:120,latitude:32,segmentStart:true},{longitude:121,latitude:32,segmentStart:false}])',context);
vm.runInContext('open({longitude:118.77,latitude:32.04,zoom:15,basemap:"road",labels:false})',context);
vm.runInContext(`setPoints([
{longitude:118,latitude:32,timeMs:1000,headingDeg:90,segmentStart:true},
{longitude:119,latitude:32,timeMs:2000,headingDeg:90,segmentStart:false},
{longitude:120,latitude:32,timeMs:40000,headingDeg:180,segmentStart:true},
{longitude:121,latitude:32,timeMs:41000,headingDeg:180,segmentStart:false}
], 'TEST-OWN')`,context);
map.handlers['style.load']();
await new Promise(resolve=>setImmediate(resolve));
assert.equal(marker.getElement().style.getPropertyValue('--rid-drone-fill'),'#26ad72');
const features=sources.get('history-track').data.features;
assert.equal(features.length,2);
assert.deepEqual([...features[0].geometry.coordinates].map(p=>[...p]),[[118,32],[119,32]]);
assert.deepEqual([...features[1].geometry.coordinates].map(p=>[...p]),[[120,32],[121,32]]);
assert.deepEqual([...features].map(feature=>Array.from(feature.geometry.coordinates, point=>[...point])),
[[[118,32],[119,32]],[[120,32],[121,32]]]);
assert.equal(fitCount,1);
vm.runInContext('setIndex(2)',context);
vm.runInContext('setCursor(0,.5)',context);
assert.deepEqual(marker.position,[118.5,32]);
vm.runInContext('setCursor(1,.5)',context);
assert.deepEqual(marker.position,[119,32]);
vm.runInContext('setMapOptions({basemap:"imagery",labels:true}); setCursor(2,0)',context);
assert.deepEqual([...sources.get('base').tiles],['/api/maps/tile/img_w/{z}/{x}/{y}']);
assert.equal(map.getLayer('labels').layout.visibility,'visible');
assert.deepEqual(marker.position,[120,32]);
assert.equal(fitCount,1,'playback should not recenter the map repeatedly');
assert.equal(marker.angle,180);
assert.equal(fitCount,1);
vm.runInContext('close()',context);
assert.ok(removed);
});
+11 -2
View File
@@ -14,6 +14,15 @@ 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' }
$ridCacheOutput = Join-Path $ridRoot 'existing-map'
$ridExistingTiles = Join-Path $ridCacheOutput 'FPV-RID-Rust/map_cache/img_w/2/1'
New-Item -ItemType Directory -Path $ridExistingTiles -Force | Out-Null
$ridMapSentinel = Join-Path $ridExistingTiles '2.png'
[IO.File]::WriteAllText($ridMapSentinel, 'existing offline tile')
$ridRejected = $false
try { & (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCacheOutput } catch { $ridRejected = $true }
if (!$ridRejected -or [IO.File]::ReadAllText($ridMapSentinel) -ne 'existing offline tile') { throw 'Offline map directory was not protected' }
$ridCleanOutput = Join-Path $ridRoot 'clean'
& (Join-Path $PSScriptRoot 'package.ps1') -OutputRoot $ridCleanOutput
if ($LASTEXITCODE -ne 0) { throw 'Clean package failed' }
@@ -34,7 +43,7 @@ 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','rid-map-downloader.exe','map-downloader-LICENSE.txt','启动Rust版.cmd','使用说明.md','config.example.json','third-party-licenses.txt','dependency-licenses.txt','build-info.json','SHA256SUMS.txt') | ForEach-Object { 'FPV-RID-Rust/' + $_ }
$ridExpected = @('fpv-rid-registry.exe','rid-map-downloader.exe','map-downloader-LICENSE.txt','启动Rust版.cmd','使用说明.md','config.example.json','third-party-licenses.txt','dependency-licenses.txt','build-info.json','SHA256SUMS.txt','map_cache/README.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() }
@@ -47,4 +56,4 @@ foreach ($ridLine in Get-Content -LiteralPath (Join-Path $ridCleanOutput 'FPV-RI
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"
Write-Output "PASS: existing data and tiles preserved; repeat package, map_cache, ZIP and file checksums verified. Evidence: $ridRoot"
+28 -6
View File
@@ -6,12 +6,15 @@ import {spawn} from 'node:child_process';
import assert from 'node:assert/strict';
import {DatabaseSync} from 'node:sqlite';
import {inflateRawSync} from 'node:zlib';
import {randomBytes} from 'node:crypto';
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;
let sessionCookie='';
const account={username:'registry-verification',password:randomBytes(24).toString('base64url')};
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{}
@@ -19,10 +22,29 @@ async function start(command,args){
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);
sessionCookie='';
for(let i=0;i<150;i++){
if(spawnError||child.exitCode!==null)throw Error(output);
const status=output.includes('FPV-RID Rust 登记站')
?await fetch(base+'/api/auth/status',{signal:AbortSignal.timeout(1000)}).catch(()=>null)
:null;
if(status?.ok){
const {configured}=await status.json();
const session=await fetch(base+(configured?'/api/auth/login':'/api/auth/setup'),{
method:'POST',headers:{origin:base,'content-type':'application/json'},body:JSON.stringify(account)
});
assert.ok(session.ok,`验收账号登录失败:HTTP ${session.status}`);
sessionCookie=session.headers.get('set-cookie')?.split(';')[0]??'';
assert.match(sessionCookie,/^rid_session=/);
return;
}
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 authenticated(route,options={}){return fetch(base+route,{...options,headers:{cookie:sessionCookie,...options.headers}});}
async function api(route,method='GET',body,status=200){const r=await authenticated(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);
@@ -40,7 +62,7 @@ function unzip(bytes){
}
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 r=await authenticated('/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');
@@ -52,7 +74,7 @@ async function exports(id,label){
}
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;'));
const r=await authenticated(`/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 exe=path.resolve(process.argv[2]||path.join(repo,'dist/FPV-RID-Rust/fpv-rid-registry.exe'));
@@ -71,7 +93,7 @@ try{
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 blocked=await authenticated('/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,'');
@@ -79,7 +101,7 @@ try{
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);
assert.equal((await authenticated('/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.