websocket.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { buttonResults } from '../resources/vue/stores/buttonResults.js'
  2. import { rateLimits } from '../resources/vue/stores/rateLimits.js'
  3. export function initWebsocket () {
  4. window.addEventListener('EventOutputChunk', onOutputChunk)
  5. window.addEventListener('EventExecutionStarted', onExecutionChanged)
  6. window.addEventListener('EventExecutionFinished', onExecutionChanged)
  7. reconnectWebsocket()
  8. }
  9. window.websocketAvailable = false
  10. async function reconnectWebsocket () {
  11. if (window.websocketAvailable) {
  12. return
  13. }
  14. try {
  15. window.websocketAvailable = true
  16. for await (const e of window.client.eventStream()) {
  17. handleEvent(e)
  18. }
  19. } catch (err) {
  20. console.error('Websocket connection failed: ', err)
  21. }
  22. window.websocketAvailable = false
  23. console.log('Reconnecting websocket...')
  24. }
  25. function handleEvent (msg) {
  26. const typeName = msg.event.value.$typeName.replace('olivetin.api.v1.', '')
  27. const j = new Event(typeName)
  28. j.payload = msg.event.value
  29. switch (typeName) {
  30. case 'EventOutputChunk':
  31. case 'EventConfigChanged':
  32. case 'EventEntityChanged':
  33. window.dispatchEvent(j)
  34. break
  35. case 'EventExecutionFinished':
  36. case 'EventExecutionStarted':
  37. window.dispatchEvent(j)
  38. break
  39. default:
  40. console.warn('Unhandled websocket message type from server: ', typeName)
  41. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + typeName, true)
  42. }
  43. }
  44. function onOutputChunk (evt) {
  45. const chunk = evt.payload
  46. if (window.terminal) {
  47. if (chunk.executionTrackingId === window.terminal.executionTrackingId) {
  48. window.terminal.write(chunk.output)
  49. }
  50. }
  51. }
  52. function onExecutionChanged (evt) {
  53. buttonResults[evt.payload.logEntry.executionTrackingId] = evt.payload.logEntry
  54. const logEntry = evt.payload.logEntry
  55. // Update rate limit store from logEntry if rate limit expiry datetime is provided
  56. if (logEntry && logEntry.datetimeRateLimitExpires && logEntry.bindingId) {
  57. // Parse datetime string "2006-01-02 15:04:05" and convert to Unix timestamp
  58. const date = new Date(logEntry.datetimeRateLimitExpires.replace(' ', 'T') + 'Z')
  59. rateLimits[logEntry.bindingId] = date.getTime() / 1000
  60. } else if (logEntry && logEntry.bindingId) {
  61. // Clear rate limit if not set
  62. rateLimits[logEntry.bindingId] = 0
  63. }
  64. }