websocket.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { marshalLogsJsonToHtml } from './marshaller.js'
  2. window.ws = null
  3. export function checkWebsocketConnection () {
  4. if (window.ws === null || window.ws.readyState === 3) {
  5. reconnectWebsocket()
  6. }
  7. }
  8. function reconnectWebsocket () {
  9. window.websocketAvailable = false
  10. let proto = 'ws:'
  11. if (window.location.protocol === 'https:') {
  12. proto = 'wss:'
  13. }
  14. const websocketConnectionUrl = proto + window.location.host + '/websocket'
  15. const ws = window.ws = new WebSocket(websocketConnectionUrl)
  16. ws.addEventListener('open', websocketOnOpen)
  17. ws.addEventListener('message', websocketOnMessage)
  18. ws.addEventListener('error', websocketOnError)
  19. ws.addEventListener('close', websocketOnClose)
  20. }
  21. function websocketOnOpen (evt) {
  22. window.websocketAvailable = true
  23. window.ws.send('monitor')
  24. window.refreshLoop()
  25. }
  26. function websocketOnMessage (msg) {
  27. // FIXME check msg status is OK
  28. const j = JSON.parse(msg.data)
  29. switch (j.type) {
  30. case 'ExecutionFinished':
  31. updatePageAfterFinished(j.payload)
  32. break
  33. default:
  34. window.showBigError('Unknown message type from server: ' + j.type)
  35. }
  36. }
  37. function updatePageAfterFinished (logEntry) {
  38. document.querySelector('execution-button#execution-' + logEntry.uuid).onFinished(logEntry)
  39. marshalLogsJsonToHtml({
  40. logs: [logEntry]
  41. })
  42. // If the current execution dialog is open, update that too
  43. if (window.executionDialog != null && window.executionDialog.dlg.open && window.executionDialog.executionUuid === logEntry.uuid) {
  44. window.executionDialog.renderResult({
  45. logEntry: logEntry
  46. })
  47. }
  48. }
  49. function websocketOnError (err) {
  50. window.websocketAvailable = false
  51. window.refreshLoop()
  52. console.error(err)
  53. }
  54. function websocketOnClose () {
  55. window.websocketAvailable = false
  56. }