test_web_transport.mjs 5.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Deterministic browser-transport checks. No server, device or network is used.
  2. import assert from 'node:assert/strict';
  3. import {readFile} from 'node:fs/promises';
  4. import vm from 'node:vm';
  5. const source = await readFile(new URL('../src/stl_backend/web/transport.js', import.meta.url), 'utf8');
  6. function fixture() {
  7. const sockets = [], timers = new Map(), states = [];
  8. let nextTimer = 0, now = 0, token = '';
  9. class FakeSocket {
  10. static OPEN = 1;
  11. constructor(url) { this.url=url; this.readyState=0; this.sent=[]; sockets.push(this); }
  12. open() { this.readyState=1; this.onopen?.({}); }
  13. send(text) { assert.equal(this.readyState,1); this.sent.push(JSON.parse(text)); }
  14. answer(id,result) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:true,result})}); }
  15. fail(id,code,message) { this.onmessage?.({data:JSON.stringify({v:1,id,ok:false,error:{code,message}})}); }
  16. close() { if(this.readyState===3)return; this.readyState=3; this.onclose?.({}); }
  17. }
  18. const window = new EventTarget();
  19. window.addEventListener('stl:transport-state', event=>states.push(event.detail.state));
  20. vm.runInNewContext(source, {
  21. window, location:{protocol:'https:',host:'bench.example:8443'}, WebSocket:FakeSocket,
  22. CustomEvent, sessionStorage:{getItem:()=>token},
  23. setTimeout:(fn,delay)=>{const id=++nextTimer;timers.set(id,{fn,when:now+delay});return id;},
  24. clearTimeout:id=>timers.delete(id),
  25. });
  26. const flush = async()=>{await Promise.resolve();await Promise.resolve();};
  27. async function tick(ms) {
  28. const until=now+ms;
  29. while(true) {
  30. const next=[...timers].filter(([,timer])=>timer.when<=until).sort((a,b)=>a[1].when-b[1].when)[0];
  31. if(!next)break;
  32. timers.delete(next[0]);now=next[1].when;next[1].fn();await flush();
  33. }
  34. now=until;await flush();
  35. }
  36. return {api:window.stlTransport,sockets,states,timers,flush,tick,setToken:value=>{token=value;}};
  37. }
  38. const f=fixture();
  39. f.setToken('test-token');
  40. const first=f.api.call('GetStationControl',{station_id:'S1'});
  41. const second=f.api.call('GetQueue',{station_id:'S1'});
  42. assert.equal(f.sockets.length,1,'Concurrent calls share one connection');
  43. const socket=f.sockets[0];
  44. assert.equal(socket.url,'wss://bench.example:8443/ws');
  45. assert.equal(socket.sent.length,0,'Requests wait for the open handshake');
  46. socket.open();await f.flush();
  47. assert.equal(socket.sent.length,2);
  48. const [one,two]=socket.sent;
  49. assert.notEqual(one.id,two.id);
  50. assert.equal(one.v,1);assert.equal(one.authorization,'Bearer test-token');
  51. assert.deepEqual(one.params,{station_id:'S1'});
  52. socket.answer(two.id,{items:[]});socket.answer(one.id,{station_id:'S1',dimms:[]});
  53. assert.equal((await first).station_id,'S1');assert.equal((await second).items.length,0);
  54. assert.equal(f.api.snapshot().pending,0,'Out-of-order results match their own request IDs');
  55. f.setToken('');
  56. const missing=f.api.call('UnknownMethod');await f.flush();
  57. const missingFrame=socket.sent.at(-1);
  58. assert.equal('authorization' in missingFrame,false,'Empty optional token is omitted');
  59. const missingCheck=assert.rejects(missing,error=>error.code==='UNIMPLEMENTED'&&error.message.includes('unknown method'));
  60. socket.fail(missingFrame.id,'UNIMPLEMENTED','unknown method');await missingCheck;
  61. assert.equal(f.api.snapshot().state,'open','Business error does not break the connection');
  62. const uncertain=f.api.call('EnqueueCommand',{command_id:'original-command',method:'StationPower'});await f.flush();
  63. const uncertainCheck=assert.rejects(uncertain,error=>error.code==='DISCONNECTED');
  64. socket.close();await uncertainCheck;
  65. assert.equal(f.api.snapshot().pending,0);
  66. await f.tick(2000);
  67. assert.equal(f.sockets.length,2,'Disconnect opens a fresh channel automatically');
  68. const restored=f.sockets[1];restored.open();await f.flush();
  69. assert.equal(restored.sent.length,0,'Uncertain write is not replayed after reconnect');
  70. assert.equal(f.api.snapshot().generation,2);
  71. const fresh=f.api.call('GetQueueItem',{command_id:'original-command'});await f.flush();
  72. restored.answer(restored.sent[0].id,{command_id:'original-command',state:'succeeded'});
  73. assert.equal((await fresh).state,'succeeded','The UI can recover the original durable queue result');
  74. const late=f.api.call('GetStationControl',{station_id:'S1'});await f.flush();
  75. const lateId=restored.sent.at(-1).id;
  76. const timeoutCheck=assert.rejects(late,error=>error.code==='REQUEST_TIMEOUT');
  77. await f.tick(20000);await timeoutCheck;
  78. assert.equal(f.api.snapshot().pending,0);
  79. restored.answer(lateId,{station_id:'S1'});
  80. assert.equal(f.api.snapshot().pending,0,'Late responses do not recreate timed-out requests');
  81. const sentBefore=restored.sent.length;
  82. await f.tick(10000);
  83. assert.equal(restored.sent.length,sentBefore,'Timeout does not resend a request');
  84. const manual=f.api.reconnect();
  85. assert.equal(f.sockets.length,3);f.sockets[2].open();await manual;
  86. assert.equal(f.sockets[2].sent.length,0,'Manual channel reconnect also sends no device operation');
  87. f.api.disconnect();await f.tick(10000);
  88. assert.equal(f.sockets.length,3,'Page shutdown stops reconnect attempts');
  89. assert.equal(f.timers.size,0);
  90. assert.ok(f.states.includes('open')&&f.states.includes('disconnected')&&f.states.includes('closed'));
  91. console.log('WEB_TRANSPORT_TEST_SUCCESS: multiplexing, optional token, structured errors, reconnect, no write replay, timeout and shutdown');