websocket.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { buttonResults } from '../resources/vue/stores/buttonResults.js'
  2. import { rateLimits } from '../resources/vue/stores/rateLimits.js'
  3. import { connectionState } from '../resources/vue/stores/connectionState.js'
  4. import {
  5. applyExecutionFinishedBindingState,
  6. applyExecutionStartedBindingState
  7. } from '../resources/vue/stores/bindingExecutionState.js'
  8. import { cloneLogEntry } from '../resources/vue/utils/executionLogEvents.js'
  9. const RECONNECT_DELAYS_MS = [200, 1000, 2000, 4000, 8000, 16000, 32000]
  10. const BANNER_DELAY_MS = 2000
  11. let reconnectAttempt = 0
  12. let reconnectTimer = null
  13. let listenersInitialized = false
  14. let eventStreamGeneration = 0
  15. let eventStreamAbortController = null
  16. function shouldConnectEventStream () {
  17. return window.initResponse && !window.initResponse.loginRequired
  18. }
  19. export function stopEventStream () {
  20. eventStreamGeneration++
  21. if (eventStreamAbortController != null) {
  22. eventStreamAbortController.abort()
  23. eventStreamAbortController = null
  24. }
  25. if (reconnectTimer != null) {
  26. clearTimeout(reconnectTimer)
  27. reconnectTimer = null
  28. }
  29. reconnectAttempt = 0
  30. connectionState.connected = false
  31. connectionState.reconnecting = false
  32. connectionState.scheduledReconnectDelayMs = 0
  33. connectionState.nextReconnectAt = null
  34. connectionState.showDisconnectedBanner = false
  35. window.websocketAvailable = false
  36. }
  37. export function connectEventStreamIfNeeded () {
  38. if (!shouldConnectEventStream()) {
  39. stopEventStream()
  40. return
  41. }
  42. if (connectionState.connected || reconnectTimer != null) {
  43. return
  44. }
  45. reconnectWebsocket()
  46. }
  47. export function initWebsocket () {
  48. if (!listenersInitialized) {
  49. window.addEventListener('EventOutputChunk', onOutputChunk)
  50. window.addEventListener('EventExecutionStarted', onExecutionStarted)
  51. window.addEventListener('EventExecutionFinished', onExecutionFinished)
  52. window.addEventListener('pagehide', stopEventStream)
  53. listenersInitialized = true
  54. }
  55. connectEventStreamIfNeeded()
  56. }
  57. window.websocketAvailable = false
  58. export function requestReconnectNow () {
  59. if (!shouldConnectEventStream()) {
  60. return
  61. }
  62. if (connectionState.connected) {
  63. return
  64. }
  65. if (reconnectTimer != null) {
  66. clearTimeout(reconnectTimer)
  67. reconnectTimer = null
  68. }
  69. reconnectAttempt = 0
  70. scheduleReconnect(RECONNECT_DELAYS_MS[0])
  71. }
  72. function scheduleReconnect (delayMs) {
  73. if (reconnectTimer != null) {
  74. clearTimeout(reconnectTimer)
  75. reconnectTimer = null
  76. }
  77. connectionState.scheduledReconnectDelayMs = delayMs
  78. connectionState.nextReconnectAt = delayMs > 0 ? Date.now() + delayMs : null
  79. updateBannerVisibility()
  80. reconnectTimer = setTimeout(() => {
  81. reconnectTimer = null
  82. reconnectWebsocket()
  83. }, delayMs)
  84. }
  85. function updateBannerVisibility () {
  86. if (connectionState.connected) {
  87. connectionState.showDisconnectedBanner = false
  88. return
  89. }
  90. connectionState.showDisconnectedBanner = connectionState.scheduledReconnectDelayMs >= BANNER_DELAY_MS
  91. }
  92. async function reconnectWebsocket () {
  93. if (!shouldConnectEventStream()) {
  94. return
  95. }
  96. if (connectionState.connected) {
  97. return
  98. }
  99. const streamGeneration = ++eventStreamGeneration
  100. if (eventStreamAbortController != null) {
  101. eventStreamAbortController.abort()
  102. }
  103. eventStreamAbortController = new AbortController()
  104. connectionState.reconnecting = true
  105. connectionState.connected = false
  106. if (connectionState.disconnectedAt == null) {
  107. connectionState.disconnectedAt = Date.now()
  108. }
  109. connectionState.nextReconnectAt = null
  110. connectionState.scheduledReconnectDelayMs = 0
  111. try {
  112. window.websocketAvailable = true
  113. const stream = window.client.eventStream({}, { signal: eventStreamAbortController.signal })
  114. connectionState.connected = true
  115. connectionState.reconnecting = false
  116. connectionState.disconnectedAt = null
  117. connectionState.nextReconnectAt = null
  118. connectionState.scheduledReconnectDelayMs = 0
  119. connectionState.showDisconnectedBanner = false
  120. for await (const e of stream) {
  121. if (streamGeneration !== eventStreamGeneration) {
  122. return
  123. }
  124. if (reconnectAttempt !== 0) {
  125. reconnectAttempt = 0
  126. }
  127. handleEvent(e)
  128. }
  129. } catch (err) {
  130. if (streamGeneration !== eventStreamGeneration) {
  131. return
  132. }
  133. console.error('Websocket connection failed: ', err)
  134. }
  135. if (streamGeneration !== eventStreamGeneration) {
  136. return
  137. }
  138. window.websocketAvailable = false
  139. connectionState.connected = false
  140. connectionState.reconnecting = false
  141. connectionState.disconnectedAt = connectionState.disconnectedAt ?? Date.now()
  142. const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]
  143. reconnectAttempt++
  144. console.log('Reconnecting websocket in ' + delay + 'ms...')
  145. if (!shouldConnectEventStream()) {
  146. return
  147. }
  148. scheduleReconnect(delay)
  149. }
  150. async function refreshInitAfterConfigChange () {
  151. if (!window.client) {
  152. return
  153. }
  154. try {
  155. window.initResponse = await window.client.init({})
  156. if (typeof window.updateHeaderFromInit === 'function') {
  157. window.updateHeaderFromInit()
  158. }
  159. } catch (err) {
  160. console.error('Failed to refresh config from server after EventConfigChanged:', err)
  161. }
  162. }
  163. async function handleConfigChangedEvent (j) {
  164. await refreshInitAfterConfigChange()
  165. window.dispatchEvent(j)
  166. }
  167. const eventCaseToTypeName = {
  168. entityChanged: 'EventEntityChanged',
  169. configChanged: 'EventConfigChanged',
  170. executionFinished: 'EventExecutionFinished',
  171. executionStarted: 'EventExecutionStarted',
  172. outputChunk: 'EventOutputChunk',
  173. heartbeat: 'EventHeartbeat'
  174. }
  175. function handleEvent (msg) {
  176. const eventCase = msg?.event?.case
  177. const eventValue = msg?.event?.value
  178. const typeName = eventCaseToTypeName[eventCase]
  179. if (!typeName || !eventValue) {
  180. console.warn('Skipping websocket event with no payload:', msg)
  181. return
  182. }
  183. const j = new Event(typeName)
  184. j.payload = eventValue
  185. switch (typeName) {
  186. case 'EventConfigChanged':
  187. handleConfigChangedEvent(j).catch((err) => {
  188. console.error('EventConfigChanged handler failed:', err)
  189. })
  190. break
  191. case 'EventHeartbeat':
  192. break
  193. case 'EventOutputChunk':
  194. case 'EventEntityChanged':
  195. window.dispatchEvent(j)
  196. break
  197. case 'EventExecutionFinished':
  198. case 'EventExecutionStarted':
  199. window.dispatchEvent(j)
  200. break
  201. default:
  202. console.warn('Unhandled websocket message type from server: ', typeName)
  203. window.showBigError('ws-unhandled-message', 'handling websocket message', 'Unhandled websocket message type from server: ' + typeName, true)
  204. }
  205. }
  206. function onOutputChunk (evt) {
  207. const chunk = evt.payload
  208. if (window.terminal) {
  209. if (chunk.executionTrackingId === window.terminal.executionTrackingId) {
  210. window.terminal.write(chunk.output)
  211. }
  212. }
  213. }
  214. export function applyExecutionLogEntry (logEntry) {
  215. const entry = cloneLogEntry(logEntry)
  216. if (!entry?.executionTrackingId) {
  217. return
  218. }
  219. buttonResults[entry.executionTrackingId] = entry
  220. if (entry.datetimeRateLimitExpires && entry.bindingId) {
  221. const date = new Date(entry.datetimeRateLimitExpires.replace(' ', 'T') + 'Z')
  222. rateLimits[entry.bindingId] = date.getTime() / 1000
  223. } else if (entry.bindingId) {
  224. rateLimits[entry.bindingId] = 0
  225. }
  226. }
  227. function onExecutionStarted (evt) {
  228. applyExecutionLogEntry(evt.payload.logEntry)
  229. applyExecutionStartedBindingState(evt.payload.logEntry)
  230. }
  231. function onExecutionFinished (evt) {
  232. applyExecutionLogEntry(evt.payload.logEntry)
  233. applyExecutionFinishedBindingState(evt.payload.logEntry)
  234. }