fix(video): recover encoder capacity, pace RTP and isolate preview sessions
This commit is contained in:
@@ -5,7 +5,7 @@ const result=await build({entryPoints:[new URL('../../../packages/sensor-ui/src/
|
||||
b.onResolve({filter:/^(react|\.\/contracts|\.\/observationStart)$/},a=>({path:a.path,namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useEffect=f=>globalThis.previewUI.effects.push(f),useRef=v=>({current:v}),useState=v=>[v,next=>globalThis.previewUI.writes.push(next)];':a.path==='./contracts'?
|
||||
'export const perform=(...args)=>globalThis.previewUI.perform(...args);':'export const currentPreviewDevice=async d=>d;'}));
|
||||
'export const perform=(...args)=>globalThis.previewUI.perform(...args);':'export const currentPreviewDevice=async d=>d;export const observationSession=d=>d.snapshot.context.session_id;'}));
|
||||
}}]});
|
||||
const {useSensorPreview}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('stuck signaling expires, retires late answers and removes every retry/listener on unmount',async()=>{
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
|
||||
const result=await build({entryPoints:[new URL('../../../plugins/insta360-x4/frontend/src/useX4Preview.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onResolve({filter:/^\.\/observationStart$/},a=>a.importer.endsWith('/frontend/src/useX4Preview.ts')?{path:'start',namespace:'fixture'}:undefined);
|
||||
b.onResolve({filter:/^\.\/contracts$/},()=>({path:'contracts',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useState=v=>globalThis.sessionUI.state(v),useRef=v=>globalThis.sessionUI.ref(v),useEffect=(f,d)=>globalThis.sessionUI.effect(f,d),useCallback=f=>globalThis.sessionUI.callback(f);':a.path==='start'?
|
||||
'export const startX4Observation=(...args)=>globalThis.sessionUI.start(...args);':
|
||||
'export const perform=(...args)=>globalThis.sessionUI.perform(...args);'}));
|
||||
}}]});
|
||||
const {useX4Preview}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
|
||||
async function fixture(run){
|
||||
const keys=['sessionUI','window','document','performance','RTCPeerConnection','MediaStream','setTimeout','clearTimeout','setInterval','clearInterval'],old=new Map(keys.map(k=>[k,globalThis[k]]));
|
||||
const values=[],effects=[],tasks=[],timers=new Map(),intervals=new Map(),events=new Map(),peers=[];
|
||||
let cursor=0,dirty=true,now=100,id=0,closed=false,frame;
|
||||
const video={paused:false,muted:true,srcObject:null,dataset:{},videoWidth:1280,videoHeight:640,
|
||||
play:()=>Promise.resolve(),requestVideoFrameCallback(f){frame=f;return ++id;},cancelVideoFrameCallback(){frame=null;}};
|
||||
const device=session=>({id:'camera',online:true,prepared:true,camera_status:{connected:true,preview:1,recording:0},snapshot:{acquisition:'streaming',context:{session_id:session,execution:{node_id:'node'}}}});
|
||||
const h={device:device('old'),enabled:true,view:null,starts:[],offers:[],
|
||||
state(v){const i=cursor++;if(!(i in values))values[i]=v;return[values[i],next=>{const value=typeof next==='function'?next(values[i]):next;if(!Object.is(value,values[i])){values[i]=value;dirty=true;}}];},
|
||||
ref(v){const i=cursor++;return values[i]??={current:i===0?video:v};},callback(f){return values[cursor++]??=f;},
|
||||
effect(f,d){const i=cursor++,previous=effects[i];if(!previous||d.some((v,j)=>v!==previous.d[j])){tasks.push(()=>{previous?.cleanup?.();effects[i]={d,cleanup:f()};});}},
|
||||
start(d){h.starts.push(d.snapshot.context.session_id);return Promise.resolve('active');},
|
||||
perform(_transport,d,action){if(action==='offer'){h.offers.push(d.snapshot.context.session_id);return Promise.resolve({peer_id:'peer-'+h.offers.length,sdp:'answer',type:'answer'});}return Promise.resolve({});},
|
||||
async settle(){dirty=true;for(let n=0;n<60;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useX4Preview(h.device,transport,h.enabled,true);tasks.splice(0).forEach(f=>f());}}},
|
||||
async live(){const pc=peers.at(-1);pc.connectionState='connected';pc.onconnectionstatechange();pc.ontrack({receiver:{},track:{}});frame();await h.settle();assert.equal(h.view.preview.live,true);},
|
||||
async replace(session,streaming=false){h.device=device(session);if(!streaming){h.device.snapshot.acquisition='idle';h.device.camera_status.preview=0;}await h.settle();},
|
||||
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},peers,
|
||||
};
|
||||
const transport={inventory:async()=>({fresh:true,items:[h.device]})};
|
||||
class Peer{constructor(){peers.push(this);this.iceGatheringState='complete';this.remoteDescription=null;this.connectionState='new';}createDataChannel(){return this.channel={readyState:'open',send(){}};}addTransceiver(){}async createOffer(){return{sdp:'fixture'};}async setLocalDescription(v){this.localDescription=v;}async setRemoteDescription(v){this.remoteDescription=v;}getStats(){return Promise.resolve(new Map());}close(){this.connectionState='closed';}}
|
||||
const eventAPI={addEventListener:(key,f)=>{const set=events.get(key)??new Set();set.add(f);events.set(key,set);},removeEventListener:(key,f)=>events.get(key)?.delete(f)};
|
||||
Object.assign(globalThis,{sessionUI:h,window:{...eventAPI},document:{...eventAPI,visibilityState:'visible'},performance:{now:()=>now},RTCPeerConnection:Peer,MediaStream:class{},
|
||||
setTimeout:(f,delay)=>{timers.set(++id,{f,at:now+delay});return id;},clearTimeout:id=>timers.delete(id),setInterval:f=>{intervals.set(++id,f);return id;},clearInterval:id=>intervals.delete(id)});
|
||||
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
|
||||
}
|
||||
|
||||
test('fast USB re-enumeration cannot carry live state into an idle replacement session',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();assert.deepEqual(h.starts,['old']);
|
||||
await h.replace('new');assert.equal(h.view.preview.live,false);
|
||||
assert.deepEqual(h.starts,['old','new'],'the new camera must start without leaving observation');
|
||||
}));
|
||||
test('an already-streaming replacement still verifies the new session and negotiates a new peer',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();await h.replace('new',true);
|
||||
assert.deepEqual(h.starts,['old','new']);assert.deepEqual(h.offers,['old','new']);
|
||||
await h.live();assert.equal(h.view.preview.live,true);
|
||||
}));
|
||||
test('ordinary live inventory refresh does not restart capture or its peer',()=>fixture(async h=>{
|
||||
await h.settle();await h.live();h.device={...h.device};await h.settle();
|
||||
assert.deepEqual(h.starts,['old']);assert.deepEqual(h.offers,['old']);
|
||||
}));
|
||||
@@ -0,0 +1,80 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// After a real blackout, repeated isolated 130 ms echoes on a 50 ms
|
||||
// baseline used to restart the capacity recovery timer forever. Exercise
|
||||
// the shared estimator AND feedback gate; testing either alone misses it.
|
||||
func TestVideoBudgetRecoversAfterBlackoutWithIsolatedEchoJitter(t *testing.T) {
|
||||
for _, control := range []bool{false, true} {
|
||||
b, now := testBudget(t)
|
||||
b.Configure(LinkPolicy{"missioncore.link-budget/v1", 6000, 512})
|
||||
b.SetControl(control)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(50*time.Millisecond, 0, 0)
|
||||
// A long interruption must close admission and lower the estimate.
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
for i := 0; i < 100; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandSilence()
|
||||
if b.optional(*now) != 0 && i >= 2 {
|
||||
t.Fatal("blackout admitted payload")
|
||||
}
|
||||
}
|
||||
if b.effective != 640 {
|
||||
t.Fatal("blackout failed to reduce budget", b.effective)
|
||||
}
|
||||
for i := 0; i < 600; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(control)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 30*time.Millisecond)
|
||||
b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
rtt := 50 * time.Millisecond
|
||||
if i%5 == 0 {
|
||||
rtt = 130 * time.Millisecond
|
||||
}
|
||||
b.ObserveDatagramFeedback(rtt, 0, b.DatagramFeedbackMark())
|
||||
// Current useful camera packets only, under existing admission.
|
||||
for packet := 0; packet < 45; packet++ {
|
||||
*now = now.Add(2 * time.Millisecond)
|
||||
b.Try("video", 1100)
|
||||
}
|
||||
}
|
||||
allocation, _ := b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
t.Logf("control=%v recovered capacity=%.0f allocation=%v", control, b.effective, allocation["allocation_bps"])
|
||||
if b.effective < 4500 || b.effective > 6000 || allocation["allocation_bps"].(int) < 3000000 {
|
||||
t.Fatal("isolated echo jitter stranded the recovered video budget", b.Snapshot())
|
||||
}
|
||||
// Return-path failure still blocks payload after recovery, immediately.
|
||||
*now = now.Add(400 * time.Millisecond)
|
||||
if b.optional(*now) != 0 {
|
||||
t.Fatal("recovered budget bypassed feedback silence")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSustainedModerateEchoDelayStillPreventsCapacityRecovery(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(50*time.Millisecond, 0, 0)
|
||||
b.effective = 640
|
||||
for i := 0; i < 150; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(false)
|
||||
b.allocateRole(testClockID, "video", true, 5000000, true)
|
||||
b.ObserveDatagramFeedback(130*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
b.Try("video", 1100)
|
||||
}
|
||||
if b.effective != 640 || !b.healthy.IsZero() {
|
||||
t.Fatal("continuing delay increased the budget", b.Snapshot())
|
||||
}
|
||||
if b.runtime.feedback.window > feedbackMinWindow {
|
||||
t.Fatal("continuing delay failed to constrain outstanding bytes")
|
||||
}
|
||||
}
|
||||
@@ -89,18 +89,30 @@ func (b *LinkBudget) feedbackLimited(now time.Time) bool {
|
||||
if !h.enabled {
|
||||
return false
|
||||
}
|
||||
// Previously earned capacity is usable only within the existing recovery
|
||||
// lifetime. Check even after echoes resume: an almost five-second outage
|
||||
// must not carry old capacity past the healthy-feedback settling period.
|
||||
if h.limited && !h.recoverUntil.IsZero() && !now.Before(h.recoverUntil) {
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
h.recoverWindow = 0
|
||||
}
|
||||
if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
|
||||
if !h.limited {
|
||||
h.recoverWindow = h.window
|
||||
h.recoverUntil = h.seen.Add(5 * time.Second)
|
||||
}
|
||||
h.recordPressure(now, "feedback_silence", now.Sub(h.seen), h.rtt, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
|
||||
// A silent return path invalidates the previously grown send window.
|
||||
// Latch pressure before updating seen: one fresh ACK after a blackout
|
||||
// must not release old optional credit as a burst. Caller holds b.mu.
|
||||
// Pause admission immediately, but distinguish a brief feedback gap
|
||||
// from a new path. Forgetting capacity on every pause creates a circular
|
||||
// recovery dependency with a receiver-limited camera. Keep only the
|
||||
// recently earned window; prolonged silence expires it. Tokens never
|
||||
// survive, and the unchanged healthy-feedback gate must still reopen.
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
if !now.Before(h.recoverUntil) {
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
h.recoverWindow = 0
|
||||
}
|
||||
h.adjusted = now
|
||||
b.healthy = time.Time{}
|
||||
b.tokens = 0
|
||||
@@ -154,11 +166,14 @@ func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
}
|
||||
b.healthy = time.Time{}
|
||||
// Delay-based admission must not mistake isolated RTT jitter for a
|
||||
// growing queue. Require a sustained trend before reducing its window;
|
||||
// severe delay and silence still suspend optional traffic immediately.
|
||||
if h.limited || now.Sub(h.delayed) >= 200*time.Millisecond {
|
||||
// The same sustained-pressure evidence must invalidate capacity
|
||||
// recovery. Resetting it for every isolated delayed echo strands
|
||||
// a recovered path at its blackout floor indefinitely.
|
||||
b.healthy = time.Time{}
|
||||
if h.adjusted.IsZero() || now.Sub(h.adjusted) >= 200*time.Millisecond {
|
||||
h.window = max(feedbackMinWindow, h.window/2)
|
||||
h.adjusted = now
|
||||
|
||||
@@ -142,8 +142,8 @@ func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) {
|
||||
b.Snapshot()
|
||||
}
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
if !b.runtime.feedback.limited || b.runtime.feedback.window > linkClassBurst {
|
||||
t.Fatal("fresh echo restored the old send window", b.runtime.feedback)
|
||||
if !b.runtime.feedback.limited || b.optional(*now) != 0 {
|
||||
t.Fatal("fresh echo restored old admission", b.runtime.feedback)
|
||||
}
|
||||
if b.tokens != 0 || b.classes["video"].tokens != 0 {
|
||||
t.Fatal("old burst credit survived silence")
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A receiver-limited camera cannot earn a collapsed admission window back by
|
||||
// sending more bytes: the receiver is also waiting for its rate to recover.
|
||||
// Brief silence must pause packets without forgetting recently earned capacity.
|
||||
func TestFeedbackPauseDoesNotStrandReceiverLimitedCamera(t *testing.T) {
|
||||
for _, gap := range []time.Duration{254 * time.Millisecond, 285 * time.Millisecond, 434 * time.Millisecond, time.Second} {
|
||||
t.Run(gap.String(), func(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = 35000
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = 64000 // Previously acknowledged path.
|
||||
for cycle := 0; cycle < 6; cycle++ {
|
||||
*now = now.Add(gap)
|
||||
if b.optional(*now) != 0 {
|
||||
t.Fatal("silent feedback admitted media")
|
||||
}
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
if ok, _ := b.Try("video", 1000); ok {
|
||||
t.Fatal("delayed first echo resumed media")
|
||||
}
|
||||
for tick := 0; tick < 4; tick++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(false)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, b.DatagramFeedbackMark())
|
||||
if tick < 2 && b.optional(*now) != 0 {
|
||||
t.Fatal("recovery bypassed continuous healthy feedback")
|
||||
}
|
||||
}
|
||||
if b.optional(*now) < 5000 {
|
||||
t.Fatal("brief pause stranded useful video despite healthy feedback", b.optional(*now))
|
||||
}
|
||||
if b.tokens != 0 || b.classes["video"].tokens != 0 {
|
||||
t.Fatal("remembered capacity restored old burst tokens")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeedbackPauseCapacityExpiresBeforeRecovery(t *testing.T) {
|
||||
for _, gap := range []time.Duration{4900 * time.Millisecond, 5100 * time.Millisecond, 10 * time.Second} {
|
||||
t.Run(gap.String(), func(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(false)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = 64000
|
||||
*now = now.Add(gap)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
for tick := 0; tick < 3; tick++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(15*time.Millisecond, 0, 0)
|
||||
}
|
||||
if b.runtime.feedback.window > linkClassBurst {
|
||||
t.Fatal("expired capacity survived a long outage", b.runtime.feedback.window)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -204,7 +204,7 @@ func roverReceiveDatagrams(ctx context.Context, conn *net.UDPConn, tx, rx *rover
|
||||
return errors.New("invalid datagram intent")
|
||||
}
|
||||
state.receivedFrame(frame.Reply, item.at)
|
||||
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44})
|
||||
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44, "socket_read_mono_ms": float64(item.at.Sub(state.origin).Microseconds()) / 1000, "receiver_queue_ms": float64(time.Since(item.at).Microseconds()) / 1000, "receive_gap_ms": float64(item.at.Sub(lastFrame).Microseconds()) / 1000})
|
||||
if !frame.Reply.Watch {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"schema": "missioncore.node.bundled-model/v1",
|
||||
"model_id": "insta360.x4",
|
||||
"version": "0.1.3-30",
|
||||
"revision": "6b548a3432798e8f8a06e208",
|
||||
"bytes": 58235788,
|
||||
"sha256": "a3312eab74d193498b8524674f4a60c77b0c04fcc4f45caa09bb4b44fbae4403"
|
||||
"version": "0.1.3-32",
|
||||
"revision": "32cb6bc3da452632d3e1301b",
|
||||
"bytes": 58236496,
|
||||
"sha256": "0af8654f8a766729a1869416256430fcb63ef3255d439f1d2e43bcd1e21e131d"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Revision a qualified Node package and its separately qualified camera SDK.
|
||||
|
||||
No compiler or installer runs. Admit the exact qualified camera SDK and,
|
||||
optionally, a separately tested Node executable. Preserve every OS/network
|
||||
helper and the motor-controller payload from the qualified predecessor.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from node_package_delta import parts
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(REPO / 'scripts/packaging'))
|
||||
from debian import package # noqa: E402
|
||||
from qualified_payloads import QualifiedPayloads # noqa: E402
|
||||
|
||||
SDK_FILES = ('codec_recovery.py', 'media_budget.py', 'diagnostic_options.py',
|
||||
'link_budget.py', 'rtp_send_clock.py')
|
||||
SDK = 'usr/lib/mission-core-node/sdk/missioncore_plugin_sdk/'
|
||||
MODEL = 'usr/share/mission-core-node/profiles/insta360-x4/'
|
||||
PROOF = 'usr/share/doc/mission-core-node/media-sdk-revision.json'
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def build(base, base_sha, model_dir, version, output, binary=None):
|
||||
if output.exists() or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*', version):
|
||||
raise ValueError('New immutable version/output required')
|
||||
evidence = json.loads((base.parent / 'qualification.json').read_text())
|
||||
if evidence['state'] != 'complete':
|
||||
raise ValueError('Qualified predecessor required')
|
||||
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
|
||||
raw = store.read(base.name)
|
||||
if sha(raw) != base_sha or evidence['artifacts'][base.name]['sha256'] != base_sha:
|
||||
raise ValueError('Predecessor identity mismatch')
|
||||
archives = parts(raw)
|
||||
old = dict((n, d) for n, d, _ in archives['data.tar.gz'])
|
||||
model = json.loads((model_dir / 'package-result.json').read_text())
|
||||
check = json.loads((model_dir / 'build-report.json').read_text())
|
||||
if check['state'] != 'complete':
|
||||
raise ValueError('Camera package qualification required')
|
||||
model_name = 'mission-core-insta360-x4_' + model['version'] + '_amd64.deb'
|
||||
model_bytes = (model_dir / model_name).read_bytes()
|
||||
if sha(model_bytes) != model['sha256'] or len(model_bytes) != model['bytes']:
|
||||
raise ValueError('Camera package identity mismatch')
|
||||
prior = json.loads(old[MODEL + 'profile.json'])
|
||||
old_model = MODEL + 'mission-core-insta360-x4_' + prior['version'] + '_amd64.deb'
|
||||
if sha(old[old_model]) != prior['sha256']:
|
||||
raise ValueError('Previous camera identity mismatch')
|
||||
sdk_root = REPO / 'packages/plugin-sdk/python/missioncore_plugin_sdk'
|
||||
sources = {name: (sdk_root / name).read_bytes() for name in SDK_FILES}
|
||||
# The shipped model predates passive DEV options. Admit the existing,
|
||||
# backward-compatible parser from this checkout in both SDK copies: old
|
||||
# capture choices keep their values, passive choices cannot enable uploads.
|
||||
options = {}
|
||||
exec(compile(sources['diagnostic_options.py'], 'diagnostic_options.py', 'exec'), options)
|
||||
legacy = {"live": True, "core_trace": True, "motor_samples": True,
|
||||
"network": True, "live_kbps": 32, "core_kbps": 32}
|
||||
normalized = options['diagnostic_options'](legacy)
|
||||
if any(normalized[k] != v for k, v in legacy.items()):
|
||||
raise ValueError('Legacy diagnostic behavior changed')
|
||||
passive = options['diagnostic_options'](options['PASSIVE_OPTIONS'])
|
||||
if not passive['passive'] or passive['live'] or passive['core_trace']:
|
||||
raise ValueError('Passive DEV unexpectedly transmits')
|
||||
# Both installed SDK copies must carry exactly the reviewed source. The
|
||||
# camera's native libraries, wheels and other SDK modules remain identical.
|
||||
previous_camera = dict((n, d) for n, d, _ in parts(old[old_model])['data.tar.gz'])
|
||||
camera = dict((n, d) for n, d, _ in parts(model_bytes)['data.tar.gz'])
|
||||
payload = 'usr/share/mission-core-node/insta360/payload.zip'
|
||||
with (zipfile.ZipFile(io.BytesIO(previous_camera[payload])) as before,
|
||||
zipfile.ZipFile(io.BytesIO(camera[payload])) as after):
|
||||
old_names, new_names = set(before.namelist()), set(after.namelist())
|
||||
permitted = {'python/missioncore_plugin_sdk/' + n for n in sources}
|
||||
if old_names - new_names or (new_names - old_names) - permitted:
|
||||
raise ValueError('Camera payload inventory changed')
|
||||
changed = {n for n in old_names & new_names if before.read(n) != after.read(n)}
|
||||
changed |= new_names - old_names
|
||||
expected = {'python/missioncore_plugin_sdk/' + n for n, d in sources.items()
|
||||
if 'python/missioncore_plugin_sdk/' + n not in old_names
|
||||
or before.read('python/missioncore_plugin_sdk/' + n) != d}
|
||||
if changed != expected:
|
||||
raise ValueError('Unreviewed camera runtime delta: ' + repr(changed))
|
||||
for name, data in sources.items():
|
||||
if after.read('python/missioncore_plugin_sdk/' + name) != data:
|
||||
raise ValueError('Camera and Node SDK differ')
|
||||
profile = {**prior, **{k: model[k] for k in ('version', 'revision', 'bytes', 'sha256')}}
|
||||
changes = {SDK + n: d for n, d in sources.items()}
|
||||
changes[MODEL + 'profile.json'] = (json.dumps(profile, indent=2) + '\n').encode()
|
||||
proof = dict(schema='missioncore.node.media-sdk-revision/v1', version=version,
|
||||
predecessor_sha256=base_sha, compiled_node_unchanged=binary is None,
|
||||
os_network_and_motor_payloads_unchanged=True,
|
||||
sdk={n: sha(d) for n, d in sources.items()}, model=profile,
|
||||
prepared_host_only=True, camera_qualification=check)
|
||||
if binary is not None:
|
||||
from repack_runtime import verify_embedded_ui
|
||||
executable = binary.read_bytes()
|
||||
if executable[:6] != b'\x7fELF\x02\x01' or executable[18:20] != b'\x3e\x00':
|
||||
raise ValueError('Expected Linux amd64 executable')
|
||||
verify_embedded_ui(executable)
|
||||
changes['usr/lib/mission-core-node/node-agent'] = executable
|
||||
proof['binary_sha256'] = sha(executable)
|
||||
proof['node_sources'] = {str(p.relative_to(REPO)): sha(p.read_bytes())
|
||||
for p in sorted((REPO / 'apps/node-agent/internal').rglob('*.go'))}
|
||||
changes[PROOF] = (json.dumps(proof, indent=2) + '\n').encode()
|
||||
controls = []
|
||||
for name, data, mode in archives['control.tar.gz']:
|
||||
if name == 'control':
|
||||
data, count = re.subn(rb'(?m)^Version: [^\n]+$', b'Version: ' + version.encode(), data)
|
||||
assert count == 1
|
||||
controls.append((name, data, mode))
|
||||
files = [(n, changes.get(n, d), m) for n, d, m in archives['data.tar.gz'] if n != old_model]
|
||||
files += [(n, d, 0o644) for n, d in changes.items() if n not in old]
|
||||
files.append((MODEL + model_name, model_bytes, 0o644))
|
||||
result = package(controls, files)
|
||||
actual = parts(result)
|
||||
if actual['control.tar.gz'] != controls or actual['data.tar.gz'] != sorted(files):
|
||||
raise ValueError('Packaged bytes differ from the admitted manifest')
|
||||
output.mkdir(mode=0o700)
|
||||
name = 'mission-core-node_' + version + '_amd64.deb'
|
||||
(output / name).write_bytes(result)
|
||||
artifacts = {name: {'bytes': len(result), 'sha256': sha(result)}}
|
||||
for dep, meta in evidence['artifacts'].items():
|
||||
if dep.startswith('mission-core-node_'):
|
||||
continue
|
||||
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
|
||||
data = store.read(dep)
|
||||
if sha(data) != meta['sha256']:
|
||||
raise ValueError('Predecessor dependency changed')
|
||||
(output / dep).write_bytes(data)
|
||||
artifacts[dep] = meta
|
||||
report = dict(schema=evidence['schema'], state='pending' if binary else 'complete',
|
||||
artifacts=artifacts,
|
||||
clean_image_qualified=False, packaging_revision=proof,
|
||||
predecessor_qualification=evidence)
|
||||
(output / 'qualification.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
return dict(directory=str(output), artifacts=artifacts)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--base', required=True, type=Path)
|
||||
parser.add_argument('--base-sha256', required=True)
|
||||
parser.add_argument('--model', required=True, type=Path)
|
||||
parser.add_argument('--version', required=True)
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
parser.add_argument('--binary', type=Path)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(build(args.base, args.base_sha256, args.model, args.version,
|
||||
args.output, args.binary)))
|
||||
Reference in New Issue
Block a user