websocket.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import {
  2. refreshServerConnectionLabel
  3. } from './marshaller.js'
  4. window.ws = null
  5. export function checkWebsocketConnection () {
  6. if (window.ws === null || window.ws.readyState === 3) {
  7. reconnectWebsocket()
  8. }
  9. }
  10. function reconnectWebsocket () {
  11. window.websocketAvailable = false
  12. const websocketConnectionUrl = new URL(window.location.toString())
  13. websocketConnectionUrl.hash = ''
  14. websocketConnectionUrl.pathname += 'websocket'
  15. if (window.location.protocol === 'https:') {
  16. websocketConnectionUrl.protocol = 'wss'
  17. } else {
  18. websocketConnectionUrl.protocol = 'ws'
  19. }
  20. window.websocketConnectionUrl = websocketConnectionUrl
  21. const ws = window.ws = new WebSocket(websocketConnectionUrl.toString())
  22. ws.addEventListener('open', websocketOnOpen)
  23. ws.addEventListener('message', websocketOnMessage)
  24. ws.addEventListener('error', websocketOnError)
  25. ws.addEventListener('close', websocketOnClose)
  26. }
  27. function websocketOnOpen (evt) {
  28. window.websocketAvailable = true
  29. window.ws.send('monitor')
  30. refreshServerConnectionLabel()
  31. window.refreshLoop()
  32. }
  33. function websocketOnMessage (msg) {
  34. // FIXME check msg status is OK
  35. const j = JSON.parse(msg.data)
  36. const e = new Event(j.type)
  37. e.payload = j.payload
  38. switch (j.type) {
  39. case 'EventOutputChunk':
  40. case 'EventConfigChanged':
  41. case 'EventExecutionFinished':
  42. case 'EventEntityChanged':
  43. window.dispatchEvent(e)
  44. break
  45. default:
  46. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + j.type, true)
  47. }
  48. }
  49. function websocketOnError (err) {
  50. window.websocketAvailable = false
  51. window.refreshLoop()
  52. console.log(err)
  53. window.showBigError('ws-connect-error', 'connecting to the websocket', 'Please see your browser console for debugging information.', true)
  54. refreshServerConnectionLabel()
  55. }
  56. function websocketOnClose () {
  57. window.websocketAvailable = false
  58. refreshServerConnectionLabel()
  59. }