feat(k1): add USB networking, device management and acquisition recovery
This commit is contained in:
@@ -4,10 +4,11 @@ import {createElement} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
|
||||
let server,Detail,presentation,enrolledDevice;
|
||||
let server,Detail,presentation,enrolledDevice,ObservationAction;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
|
||||
({K1Detail:Detail}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Detail.tsx'));
|
||||
({K1ObservationAction:ObservationAction}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1ObservationAction.tsx'));
|
||||
presentation=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/presentation.ts');
|
||||
({enrolledDevice}=await server.ssrLoadModule('../../packages/sensor-ui/src/contracts.ts'));
|
||||
});
|
||||
@@ -88,3 +89,47 @@ test('completed scan with healthy control remains connected and permits a named
|
||||
assert.doesNotMatch(markup,/Проверить состояние K1|Подключить устройство|Устройство остановлено/);
|
||||
assert.equal(presentation.k1Status(stopped,false).tone,'neutral');
|
||||
});
|
||||
test('observation Play only opens configuration; active acquisition offers its existing controls',()=>{
|
||||
let opened=0;
|
||||
const action=ObservationAction({device,fresh:true,configure:()=>opened++});
|
||||
assert.equal(action.props.label,'Начать сканирование K1');assert.equal(action.props.children.props.name,'play');
|
||||
action.props.onClick();assert.equal(opened,1);
|
||||
assert.equal(ObservationAction({device,fresh:false,configure:()=>opened++}),null);
|
||||
const active={...device,snapshot:{...device.snapshot,acquisition:'streaming'}};
|
||||
let stopped=0;const stop=ObservationAction({device:{...active,control:{...active.control,can_stop:true}},fresh:true,stop:()=>stopped++});
|
||||
assert.equal(stop.props.label,'Остановить сканирование K1');stop.props.onClick();assert.equal(stopped,1);assert.equal(opened,1);
|
||||
});
|
||||
test('observation configuration preserves START fields and STOP without a duplicate media viewer',()=>{
|
||||
for(const acquisition of ['idle','starting','streaming','stopping']){
|
||||
const value={...device,snapshot:{...device.snapshot,acquisition}};
|
||||
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,backLabel:'Вернуться к наблюдению',transport:{},back:()=>{},refresh:async()=>{},failure:()=>{},createRerunHost:()=>assert.fail('must not allocate another viewer')}));
|
||||
assert.match(markup,/Вернуться к наблюдению/);assert.doesNotMatch(markup,/rerun-viewport__canvas|Открыть пространственную сцену/);
|
||||
if(acquisition==='idle')assert.match(markup,/Название проекта/);
|
||||
if(acquisition==='streaming')assert.match(markup,/Остановить устройство/);
|
||||
}
|
||||
});
|
||||
|
||||
test('observation gear contains only acquisition controls, including before START',()=>{
|
||||
for(const acquisition of ['idle','streaming']){
|
||||
const value={...device,snapshot:{...device.snapshot,acquisition}};
|
||||
const markup=renderToStaticMarkup(createElement(Detail,{device:value,enabled:true,previewEnabled:false,sceneProfile:{view:'plan',save:()=>{}},transport:{},back:()=>{},refresh:async()=>{},failure:()=>{}}));
|
||||
assert.doesNotMatch(markup,/Размер точки|Атрибут цвета|Палитра|rerun-viewport__canvas/);
|
||||
if(acquisition==='idle')assert.match(markup,/Название проекта/);
|
||||
else assert.match(markup,/Остановить устройство/);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('K1 storage shows used percentage and expires independently of a fresh inventory',()=>{
|
||||
const now=Date.now(),observed_at=new Date(now-1000).toISOString();
|
||||
const almostFull={...device,storage_status:{used_percent:98.99,observed_at}};
|
||||
assert.equal(presentation.k1StorageStatus(almostFull,true,now+18000).tone,'warning');
|
||||
const status=presentation.k1StorageStatus(almostFull,true,now);
|
||||
assert.equal(status.tone,'warning');assert.match(status.label,/занято 99 %.*мало свободного места/);
|
||||
assert.match(render(almostFull),/Хранилище K1: занято 99 %/);
|
||||
for(const [value,fresh,at] of [[almostFull,false,now],[{...almostFull,online:false},true,now],[almostFull,true,now+20000],[{...device,storage_status:null},true,now]]){
|
||||
const unavailable=presentation.k1StorageStatus(value,fresh,at);
|
||||
assert.equal(unavailable.tone,'neutral');assert.match(unavailable.label,/нет свежих данных/);assert.doesNotMatch(unavailable.label,/99/);
|
||||
}
|
||||
assert.equal(presentation.k1StorageStatus({...device,storage_status:{used_percent:0,observed_at}},true,now).tone,'neutral');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createElement} from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
|
||||
let server,Observation;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',plugins:[{
|
||||
name:'inline-observation-portals-for-ssr',enforce:'pre',
|
||||
transform(code,id){
|
||||
if(id.endsWith('/K1Observation.tsx')||id.endsWith('/ObservationHeader.tsx'))
|
||||
return code.replace("import {createPortal} from 'react-dom';","import {cloneElement as portalChild} from 'react'; const createPortal=(child: any,_target: unknown,key?: string)=>child&&key?portalChild(child,{key}):child;");
|
||||
},
|
||||
}]});
|
||||
({K1Observation:Observation}=await server.ssrLoadModule('@xgrids-k1/frontend/sensors/K1Observation.tsx'));
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
|
||||
const render=(acquisition,enabled)=>renderToStaticMarkup(createElement(Observation,{
|
||||
device:{id:'synthetic-k1',name:'K1',online:enabled,verified:enabled,
|
||||
control:{can_stop:true,acquisition_id:'same-acquisition'},
|
||||
snapshot:{acquisition,context:{session_id:'same-session'}}},
|
||||
transport:{},enabled,fresh:enabled,views:[{id:'points',target:{},statusTarget:{},actionsTarget:{}}],
|
||||
createRerunHost:()=>assert.fail('server rendering must not allocate a viewer'),
|
||||
}));
|
||||
test('an ongoing acquisition retains the spatial surface during a link gap while STOP is disabled',()=>{
|
||||
const online=render('streaming',true),offline=render('streaming',false);
|
||||
for(const markup of [online,offline]){
|
||||
assert.match(markup,/rerun-viewport__canvas/);
|
||||
assert.match(markup,/Окно накопления облака точек/);
|
||||
assert.match(markup,/Позиция воспроизведения/);
|
||||
assert.match(markup,/ЭФИР/);
|
||||
assert.doesNotMatch(markup,/буфер не включён/);
|
||||
assert.match(markup,/Следовать за K1/);
|
||||
assert.doesNotMatch(markup,/data-viewer-controls/);
|
||||
assert.match(markup,/data-pulse="true"/);
|
||||
}
|
||||
const stop=offline.match(/<button\b[^>]*aria-label="Остановить сканирование K1"[^>]*>/)?.[0];
|
||||
assert.ok(stop);assert.match(stop,/disabled=""/);
|
||||
assert.doesNotMatch(offline,/Инициировать запуск/);
|
||||
});
|
||||
test('completed or never-started acquisitions do not retain an active spatial surface',()=>{
|
||||
for(const acquisition of ['idle','failed'])
|
||||
assert.doesNotMatch(render(acquisition,false),/rerun-viewport__canvas/);
|
||||
});
|
||||
@@ -49,7 +49,7 @@ test('source age expires even when metadata repeats, old frames never look live'
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:250,points:3});
|
||||
assert.equal(gate.fresh,true);assert.equal(gate.points,3);
|
||||
now+=1800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
|
||||
now+=4800;gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:3});
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:2,age_ms:9000,points:3});
|
||||
assert.equal(gate.fresh,false);
|
||||
@@ -58,6 +58,19 @@ test('source age expires even when metadata repeats, old frames never look live'
|
||||
assert.throws(()=>gate.receive({type:'lidar-state',sequence:4,age_ms:-1,points:4}));
|
||||
});
|
||||
|
||||
test('budgeted cloud accepts a three-second delivery without making an old frame live forever',()=>{
|
||||
let now=10000;const gate=previewFreshness(()=>now);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:3000,points:394});
|
||||
assert.equal(gate.fresh,true);
|
||||
now+=1999;assert.equal(gate.fresh,true);
|
||||
gate.receive({type:'lidar-state',sequence:1,age_ms:0,points:394});
|
||||
now++;assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:2,age_ms:null,points:394});
|
||||
assert.equal(gate.fresh,false);
|
||||
gate.receive({type:'lidar-state',sequence:3,age_ms:5000,points:394});
|
||||
assert.equal(gate.fresh,false);
|
||||
});
|
||||
|
||||
test('onboard camera admits immediate sourceopen and ignores callbacks after close',()=>{
|
||||
const saved={media:globalThis.MediaSource,create:URL.createObjectURL,revoke:URL.revokeObjectURL};
|
||||
let source,buffer,appended=0,ready=0,failed=0;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {readdir,readFile} from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import ts from 'typescript';
|
||||
|
||||
test('K1 sensor surfaces cannot introduce browser-default explanatory paragraphs',async()=>{
|
||||
const root=new URL('../../../plugins/xgrids-k1/frontend/src/sensors/',import.meta.url);
|
||||
const files=(await readdir(root)).filter(name=>name.endsWith('.tsx'));
|
||||
for(const name of files){
|
||||
const text=await readFile(new URL(name,root),'utf8');
|
||||
const source=ts.createSourceFile(name,text,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
|
||||
function inspect(node){
|
||||
if((ts.isJsxOpeningElement(node)||ts.isJsxSelfClosingElement(node))&&node.tagName.getText(source)==='p'){
|
||||
assert.ok(node.attributes.properties.some(p=>ts.isJsxAttribute(p)&&p.name.text==='className'),`${name}: explanatory copy must use Description; only explicitly styled viewport/data paragraphs may remain`);
|
||||
}
|
||||
ts.forEachChild(node,inspect);
|
||||
}
|
||||
inspect(source);
|
||||
}
|
||||
});
|
||||
@@ -232,3 +232,74 @@ test('legacy resolution failure invalidates the form before a second stale submi
|
||||
assert.equal(api.enrollmentBluetoothFailure(state),true);
|
||||
assert.match(api.enrollmentNotice(state),/Найдите K1 ещё раз/);
|
||||
});
|
||||
|
||||
test('saved Bridge recovery needs no BLE candidate and dispatches exactly one existing Verify',async()=>{
|
||||
const before={...initial,selected_device_id:null,candidates:[],discovery_generation:0,mode_revision:3,
|
||||
reconnect_target:{device_id:'saved-k1',source:'durable-configured-state'},
|
||||
allowed_actions:['observe-configured-device-network'],acquisition_recovery:{state:'active'}};
|
||||
const commands=[];
|
||||
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,
|
||||
result:{...before,snapshot_revision:2,selected_device_id:'saved-k1',connected:true,
|
||||
device_session:{device_id:'saved-k1',device_session_id:'new-live-session'},
|
||||
command_result:{operation_id:command.operation_id,status:'succeeded',action:'verify'}}};}};
|
||||
const result=await api.enroll(transport,before,'verify',{device_id:before.reconnect_target.device_id,discovery_generation:0,mode_revision:3});
|
||||
assert.equal(api.enrollmentAllowed(before,'verify'),true);
|
||||
assert.equal(api.enrollmentAllowed(before,'connect'),false);
|
||||
assert.equal(commands.length,1);assert.equal(commands[0].action,'verify');
|
||||
assert.deepEqual(commands[0].parameters,{device_id:'saved-k1',discovery_generation:0,mode_revision:3});
|
||||
assert.equal(api.enrollmentProof(result,'saved-k1').session,'new-live-session');
|
||||
});
|
||||
|
||||
test('unreachable K1 reports power and network checks without claiming power-off or live scanning',()=>{
|
||||
const before={...initial,connected:false,acquisition_recovery:{state:'active'}};
|
||||
assert.match(api.enrollmentRecoveryNotice(before),/не подтверждена/);
|
||||
for(const code of ['connection-verify-device-not-rediscovered','connection-verify-mqtt-unreachable','connection-verify-status-read-timeout']){
|
||||
const value={...before,verification:{status:'failed',error_code:code}};
|
||||
const message=api.enrollmentRecoveryNotice(value);
|
||||
assert.match(message,/Проверьте питание/);assert.match(message,/сети/);
|
||||
assert.doesNotMatch(message,/K1 выключен|съёмка продолжается|съёмка завершена/);
|
||||
assert.equal(api.enrollmentRecoveryNotice(JSON.parse(JSON.stringify(value))),message);
|
||||
}
|
||||
assert.match(api.enrollmentRecoveryNotice({...before,connected:true,acquisition_recovery:{state:'ceased'}}),/Предыдущая съёмка завершена/);
|
||||
assert.match(api.enrollmentRecoveryNotice({...before,fresh:false}),/Нет свежих сведений с БК/);
|
||||
});
|
||||
|
||||
test('onboard reset uses the existing CAS outcome without automatic Scan, Verify or provisioning',async()=>{
|
||||
const before={...initial,can_reset:true,supported_actions:['reset'],mode_revision:4};const commands=[];
|
||||
assert.equal(api.enrollmentAllowed(before,'reset'),true);
|
||||
assert.equal(api.enrollmentAllowed({...before,supported_actions:undefined},'reset'),false);
|
||||
assert.equal(api.enrollmentAllowed({...before,can_reset:undefined},'reset'),false);
|
||||
const transport={submit:async command=>{commands.push(command);return {state:'complete',operation_id:command.operation_id,result:{...before,mode_revision:5,snapshot_revision:2,connected:false,command_result:{operation_id:command.operation_id,action:'reset',status:'succeeded'}}};}};
|
||||
const result=await api.enroll(transport,before,'reset',{mode_revision:4});
|
||||
assert.equal(result.mode_revision,5);assert.equal(commands.length,1);assert.equal(commands[0].action,'reset');
|
||||
assert.deepEqual(commands[0].parameters,{mode_revision:4});
|
||||
transport.submit=async command=>({state:'complete',operation_id:command.operation_id,result:before});
|
||||
await assert.rejects(api.enroll(transport,before,'reset',{mode_revision:4}),/не подтверждён/);
|
||||
});
|
||||
|
||||
test('terminal enrollment without a driver result releases the observer without waiting or replay',async()=>{
|
||||
for(const action of ['connect','verify']){
|
||||
for(const state of ['unknown','failed','rejected']){
|
||||
let posts=0,reads=0,pauses=0,clock=Date.now();
|
||||
const transport={
|
||||
submit:async command=>{posts++;return {operation_id:command.operation_id,state,error:'Действие K1 не подтверждено.'};},
|
||||
operation:async()=>{throw new Error('terminal delivery must not be polled again');},
|
||||
state:async()=>{reads++;return {...initial,connected:true};},
|
||||
};
|
||||
const parameters={device_id:'synthetic-ble',...(action==='connect'?{password:crypto.randomUUID()}: {})};
|
||||
await assert.rejects(api.enroll(transport,initial,action,parameters,{
|
||||
now:()=>clock,pause:async()=>{pauses++;clock+=100000;},
|
||||
}),/Действие K1 не подтверждено/);
|
||||
assert.deepEqual({posts,reads,pauses},{posts:1,reads:0,pauses:0});
|
||||
assert.equal('password' in parameters,false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown delivery with a correlated running result still observes the owned bootstrap',async()=>{
|
||||
const f=fixture(),submit=f.transport.submit;
|
||||
f.transport.submit=async command=>({...await submit(command),state:'unknown'});
|
||||
const result=await api.enroll(f.transport,initial,'connect',f.parameters,f.observer);
|
||||
assert.equal(result.connected,true);
|
||||
assert.deepEqual(f.counts(),{posts:1,reads:1});
|
||||
});
|
||||
|
||||
@@ -94,8 +94,15 @@ func (d *DeviceEnrollment) call(ctx context.Context, path string, command any) (
|
||||
return nil, errors.New("Служба K1 на БК недоступна.")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
limit := int64(65536)
|
||||
if c, ok := command.(SensorCommand); ok && path == "/sensor-operation" && c.Action == "details" && c.Parameters["preview_blueprint"] != nil {
|
||||
// Canonical Rerun profiles include binary schema data (about 100 KiB
|
||||
// as JSON). This bound is for read-only visualization replies only.
|
||||
limit = 1024 * 1024
|
||||
}
|
||||
data, readErr := io.ReadAll(io.LimitReader(response.Body, limit+1))
|
||||
var value map[string]any
|
||||
if json.NewDecoder(io.LimitReader(response.Body, 65536)).Decode(&value) != nil || response.StatusCode != 200 {
|
||||
if readErr != nil || int64(len(data)) > limit || json.Unmarshal(data, &value) != nil || response.StatusCode != 200 {
|
||||
return nil, errors.New("Действие K1 не подтверждено. Обновите состояние устройства.")
|
||||
}
|
||||
return value, nil
|
||||
@@ -108,6 +115,7 @@ func (d *DeviceEnrollment) Status() map[string]any {
|
||||
if e != nil {
|
||||
value = map[string]any{"available": false}
|
||||
}
|
||||
value["supported_actions"] = []string{"scan", "networks", "connect", "verify", "reset"}
|
||||
value["node_id"] = d.nodeID
|
||||
value["name"], _ = os.Hostname()
|
||||
value["fresh"] = true
|
||||
@@ -122,6 +130,12 @@ func (c EnrollmentCommand) valid(nodeID string) bool {
|
||||
keys := map[string]bool{}
|
||||
switch c.Action {
|
||||
case "scan", "networks":
|
||||
case "reset":
|
||||
keys = map[string]bool{"mode_revision": true}
|
||||
v, ok := c.Parameters["mode_revision"].(float64)
|
||||
if !ok || v < 0 || v != float64(int64(v)) {
|
||||
return false
|
||||
}
|
||||
case "connect", "verify":
|
||||
keys = map[string]bool{"device_id": true, "discovery_generation": true, "mode_revision": true}
|
||||
id, ok := c.Parameters["device_id"].(string)
|
||||
@@ -192,7 +206,7 @@ func (d *DeviceEnrollment) Submit(c EnrollmentCommand, remote bool) (*Enrollment
|
||||
}
|
||||
}
|
||||
for _, v := range d.operations {
|
||||
if v.State == "running" {
|
||||
if v.State == "running" && (c.Action != "reset" || v.Action == "reset") {
|
||||
d.mu.Unlock()
|
||||
return nil, errors.New("Дождитесь текущего действия K1.")
|
||||
}
|
||||
@@ -209,7 +223,7 @@ func (d *DeviceEnrollment) Submit(c EnrollmentCommand, remote bool) (*Enrollment
|
||||
return out, nil
|
||||
}
|
||||
for _, v := range d.operations {
|
||||
if v.State == "running" {
|
||||
if v.State == "running" && (c.Action != "reset" || v.Action == "reset") {
|
||||
d.mu.Unlock()
|
||||
return nil, errors.New("Дождитесь текущего действия K1.")
|
||||
}
|
||||
@@ -237,6 +251,11 @@ func (d *DeviceEnrollment) execute(c EnrollmentCommand) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
op := d.operations[c.ID]
|
||||
// A committed local reset supersedes observation of the earlier attempt.
|
||||
// Its late HTTP reply cannot restore that attempt in the host journal.
|
||||
if op.State != "running" {
|
||||
return
|
||||
}
|
||||
op.Updated = time.Now().Unix()
|
||||
op.State = "complete"
|
||||
op.Result = result
|
||||
@@ -244,6 +263,20 @@ func (d *DeviceEnrollment) execute(c EnrollmentCommand) {
|
||||
op.State = "unknown"
|
||||
op.Error = "Действие K1 не подтверждено. Обновите состояние; повторная команда автоматически не отправляется."
|
||||
}
|
||||
if e == nil && c.Action == "reset" && result != nil {
|
||||
proof, _ := result["command_result"].(map[string]any)
|
||||
revision, _ := result["mode_revision"].(float64)
|
||||
if proof["operation_id"] == c.ID && proof["status"] == "succeeded" && revision == c.Parameters["mode_revision"].(float64)+1 {
|
||||
for id, previous := range d.operations {
|
||||
if id != c.ID && previous.State == "running" && previous.RuntimeID == c.RuntimeID {
|
||||
previous.State = "unknown"
|
||||
previous.Error = "Локальная попытка подключения сброшена оператором. История команды сохранена."
|
||||
previous.Updated = time.Now().Unix()
|
||||
_ = savePrivateJSON(filepath.Join(d.root, id+".json"), previous)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := savePrivateJSON(filepath.Join(d.root, c.ID+".json"), op); e != nil {
|
||||
op.State = "unknown"
|
||||
op.Error = "Результат не сохранён. Обновите состояние K1."
|
||||
|
||||
@@ -2,6 +2,7 @@ package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -15,6 +16,39 @@ import (
|
||||
|
||||
type enrollmentHTTP func(*http.Request) (*http.Response, error)
|
||||
|
||||
func TestCanonicalK1BlueprintReplyHasBoundedMediaAllowance(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, action string
|
||||
blueprint bool
|
||||
size int
|
||||
accepted bool
|
||||
}{
|
||||
{"canonical profile", "details", true, 102460, true},
|
||||
{"ordinary details", "details", false, 102460, false},
|
||||
{"physical action", "start", true, 102460, false},
|
||||
{"oversized profile", "details", true, 1024*1024 + 1, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"result":{"rrd":"` + strings.Repeat("a", tc.size) + `"}}`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
command := SensorCommand{Action: tc.action, Parameters: map[string]any{}}
|
||||
if tc.blueprint {
|
||||
command.Parameters["preview_blueprint"] = map[string]any{}
|
||||
}
|
||||
_, err := d.call(context.Background(), "/sensor-operation", command)
|
||||
if (err == nil) != tc.accepted {
|
||||
t.Fatalf("accepted=%v, error=%v", tc.accepted, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (f enrollmentHTTP) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
func enrollmentRequest() EnrollmentCommand {
|
||||
@@ -109,3 +143,92 @@ func TestEnrollmentRejectsAnotherNodeExpiredAndHostMutation(t *testing.T) {
|
||||
t.Fatal("expired operation admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentResetAcceptsOnlyModeRevision(t *testing.T) {
|
||||
c := enrollmentRequest()
|
||||
c.Action = "reset"
|
||||
c.Parameters = map[string]any{"mode_revision": float64(7)}
|
||||
if !c.valid("node-test") {
|
||||
t.Fatal("canonical reset was refused")
|
||||
}
|
||||
for _, parameters := range []map[string]any{{}, {"mode_revision": true}, {"mode_revision": float64(-1)}, {"mode_revision": float64(1.5)}, {"mode_revision": float64(7), "device_id": "x"}} {
|
||||
c.Parameters = parameters
|
||||
if c.valid("node-test") {
|
||||
t.Fatal("invalid reset admitted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentResetSupersedesPendingObservationWithoutReplayingCommand(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release, replied := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"available":true,"runtime_id":"runtime-test"}`
|
||||
if r.Method == "POST" {
|
||||
var command EnrollmentCommand
|
||||
if err := json.NewDecoder(r.Body).Decode(&command); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if command.Action == "connect" {
|
||||
close(entered)
|
||||
<-release
|
||||
close(replied)
|
||||
body = `{"connected":true}`
|
||||
} else {
|
||||
raw, _ := json.Marshal(map[string]any{"mode_revision": float64(1), "command_result": map[string]any{"operation_id": command.ID, "action": "reset", "status": "succeeded"}})
|
||||
body = string(raw)
|
||||
}
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
old := enrollmentRequest()
|
||||
if _, err := d.Submit(old, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
ordinary := enrollmentRequest()
|
||||
ordinary.ID = "op_" + strings.Repeat("b", 32)
|
||||
if _, err := d.Submit(ordinary, true); err == nil {
|
||||
t.Fatal("ordinary action bypassed pending operation")
|
||||
}
|
||||
reset := enrollmentRequest()
|
||||
reset.ID = "op_" + strings.Repeat("c", 32)
|
||||
reset.Action = "reset"
|
||||
reset.Parameters = map[string]any{"mode_revision": float64(0)}
|
||||
if _, err := d.Submit(reset, true); err != nil {
|
||||
close(release)
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for d.Get(reset.ID).State == "running" && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if d.Get(reset.ID).State != "complete" || d.Get(old.ID).State != "unknown" {
|
||||
close(release)
|
||||
t.Fatal("reset did not supersede pending observation")
|
||||
}
|
||||
close(release)
|
||||
<-replied
|
||||
// execute's old reply must leave the reset-owned terminal journal untouched.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if d.Get(old.ID).State != "unknown" || d.Get(old.ID).Result != nil {
|
||||
t.Fatal("late reply restored old result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnrollmentPublishesHostResetSupport(t *testing.T) {
|
||||
d, err := OpenDeviceEnrollment(t.TempDir(), "node-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d.client = &http.Client{Transport: enrollmentHTTP(func(r *http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"available":true,"can_reset":true}`)), Header: make(http.Header)}, nil
|
||||
})}
|
||||
got := d.Status()["supported_actions"].([]string)
|
||||
if strings.Join(got, ",") != "scan,networks,connect,verify,reset" {
|
||||
t.Fatal("host capability does not describe admitted actions")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,8 @@ var sensorModels = []sensorModel{
|
||||
PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json",
|
||||
Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")},
|
||||
{ID: "xgrids.k1", Name: "XGRIDS K1", Prefix: "k1", Kind: "k1",
|
||||
Actions: actions("details", "rename", "verify", "start", "stop", "option", "offer", "close-peer")},
|
||||
ActionTimeouts: map[string]time.Duration{"management": 35 * time.Second},
|
||||
Actions: actions("details", "rename", "verify", "start", "stop", "option", "offer", "close-peer", "management")},
|
||||
{ID: "insta360.x4", Name: "Insta360 X4", Prefix: "instax4", Kind: "insta360.x4", Plugin: "missioncore.insta360", Version: "0.1.3",
|
||||
// 2e1a:0002 is shared with other Insta360 models. Require the exact
|
||||
// OS product descriptor as well; SDK identity is verified after prepare.
|
||||
|
||||
Reference in New Issue
Block a user