| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- // Deterministic browser-transport checks. No server, device or network is used.
- import assert from 'node:assert/strict';
- import {readFile} from 'node:fs/promises';
- import vm from 'node:vm';
- const source = await readFile(new URL('../src/stl_backend/web/transport.js', import.meta.url), 'utf8');
- function fixture() {
- const sockets = [], timers = new Map(), states = [];
- let nextTimer = 0, now = 0, token = '';
- class FakeSocket {
- static OPEN = 1;
- constructor(url) { this.url=url; this.readyState=0; this.sent=[]; sockets.push(this); }
- open() { this.readyState=1; this.onopen?.({}); }
- send(text) { assert.equal(this.readyState,1); this.sent.push(JSON.parse(text)); }
- answer(id,result) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:true,result})}); }
- fail(id,code,message) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:false,error:{code,message}})}); }
- close() { if(this.readyState===3)return; this.readyState=3; this.onclose?.({}); }
- }
- const window = new EventTarget();
- window.addEventListener('stl:transport-state', event=>states.push(event.detail.state));
- vm.runInNewContext(source, {
- window, location:{protocol:'https:',host:'bench.example:8443'}, WebSocket:FakeSocket,
- CustomEvent, sessionStorage:{getItem:()=>token},
- setTimeout:(fn,delay)=>{const id=++nextTimer;timers.set(id,{fn,when:now+delay});return id;},
- clearTimeout:id=>timers.delete(id),
- });
- const flush = async()=>{await Promise.resolve();await Promise.resolve();};
- async function tick(ms) {
- const until=now+ms;
- while(true) {
- const next=[...timers].filter(([,timer])=>timer.when<=until).sort((a,b)=>a[1].when-b[1].when)[0];
- if(!next)break;
- timers.delete(next[0]);now=next[1].when;next[1].fn();await flush();
- }
- now=until;await flush();
- }
- return {api:window.stlTransport,sockets,states,timers,flush,tick,setToken:value=>{token=value;}};
- }
- const f=fixture();
- f.setToken('test-token');
- const first=f.api.call('GetStationControl',{station_id:'S1'});
- const second=f.api.call('GetQueue',{station_id:'S1'});
- assert.equal(f.sockets.length,1,'Concurrent calls share one connection');
- const socket=f.sockets[0];
- assert.equal(socket.url,'wss://bench.example:8443/ws');
- assert.equal(socket.sent.length,0,'Requests wait for the open handshake');
- socket.open();await f.flush();
- assert.equal(socket.sent.length,2);
- const [one,two]=socket.sent;
- assert.notEqual(one.id,two.id);
- assert.equal(one.v,1);assert.equal(one.authorization,'Bearer test-token');
- assert.deepEqual(one.params,{station_id:'S1'});
- socket.answer(two.id,{items:[]});socket.answer(one.id,{station_id:'S1',dimms:[]});
- assert.equal((await first).station_id,'S1');assert.equal((await second).items.length,0);
- assert.equal(f.api.snapshot().pending,0,'Out-of-order results match their own request IDs');
- f.setToken('');
- const missing=f.api.call('UnknownMethod');await f.flush();
- const missingFrame=socket.sent.at(-1);
- assert.equal('authorization' in missingFrame,false,'Empty optional token is omitted');
- const missingCheck=assert.rejects(missing,error=>error.code==='UNIMPLEMENTED'&&error.message.includes('unknown method'));
- socket.fail(missingFrame.id,'UNIMPLEMENTED','unknown method');await missingCheck;
- assert.equal(f.api.snapshot().state,'open','Business error does not break the connection');
- const uncertain=f.api.call('EnqueueCommand',{command_id:'original-command',method:'StationPower'});await f.flush();
- const uncertainCheck=assert.rejects(uncertain,error=>error.code==='DISCONNECTED');
- socket.close();await uncertainCheck;
- assert.equal(f.api.snapshot().pending,0);
- await f.tick(2000);
- assert.equal(f.sockets.length,2,'Disconnect opens a fresh channel automatically');
- const restored=f.sockets[1];restored.open();await f.flush();
- assert.equal(restored.sent.length,0,'Uncertain write is not replayed after reconnect');
- assert.equal(f.api.snapshot().generation,2);
- const fresh=f.api.call('GetQueueItem',{command_id:'original-command'});await f.flush();
- restored.answer(restored.sent[0].id,{command_id:'original-command',state:'succeeded'});
- assert.equal((await fresh).state,'succeeded','The UI can recover the original durable queue result');
- const late=f.api.call('GetStationControl',{station_id:'S1'});await f.flush();
- const lateId=restored.sent.at(-1).id;
- const timeoutCheck=assert.rejects(late,error=>error.code==='REQUEST_TIMEOUT');
- await f.tick(20000);await timeoutCheck;
- assert.equal(f.api.snapshot().pending,0);
- restored.answer(lateId,{station_id:'S1'});
- assert.equal(f.api.snapshot().pending,0,'Late responses do not recreate timed-out requests');
- const sentBefore=restored.sent.length;
- await f.tick(10000);
- assert.equal(restored.sent.length,sentBefore,'Timeout does not resend a request');
- const manual=f.api.reconnect();
- assert.equal(f.sockets.length,3);f.sockets[2].open();await manual;
- assert.equal(f.sockets[2].sent.length,0,'Manual channel reconnect also sends no device operation');
- f.api.disconnect();await f.tick(10000);
- assert.equal(f.sockets.length,3,'Page shutdown stops reconnect attempts');
- assert.equal(f.timers.size,0);
- assert.ok(f.states.includes('open')&&f.states.includes('disconnected')&&f.states.includes('closed'));
- console.log('WEB_TRANSPORT_TEST_SUCCESS: multiplexing, optional token, structured errors, reconnect, no write replay, timeout and shutdown');
|