connection-manager.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import {
  2. ConnectionError,
  3. ConnectionState,
  4. ExternalHeartbeat,
  5. SocketDebuggingInfo,
  6. } from './types/connection-state'
  7. import SocketIoShim from '../../../ide/connection/SocketIoShim'
  8. import getMeta from '../../../utils/meta'
  9. import { Socket } from '@/features/ide-react/connection/types/socket'
  10. import { debugConsole } from '@/utils/debugging'
  11. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  12. const ONE_HOUR_IN_MS = 1000 * 60 * 60
  13. const TWO_MINUTES_IN_MS = 2 * 60 * 1000
  14. const DISCONNECT_AFTER_MS = ONE_HOUR_IN_MS * 24
  15. const CONNECTION_ERROR_RECONNECT_DELAY = 1000
  16. const USER_ACTIVITY_RECONNECT_NOW_DELAY = 1000
  17. const USER_ACTIVITY_RECONNECT_DELAY = 5000
  18. const JOIN_PROJECT_RATE_LIMITED_DELAY = 15 * 1000
  19. const RECONNECT_GRACEFULLY_RETRY_INTERVAL_MS = 5000
  20. const MAX_RECONNECT_GRACEFULLY_INTERVAL_MS = 45 * 1000
  21. const MAX_RETRY_CONNECT = 5
  22. const externalSocketHeartbeat = isSplitTestEnabled('external-socket-heartbeat')
  23. const initialState: ConnectionState = {
  24. readyState: WebSocket.CLOSED,
  25. forceDisconnected: false,
  26. inactiveDisconnect: false,
  27. lastConnectionAttempt: 0,
  28. reconnectAt: null,
  29. forcedDisconnectDelay: 0,
  30. error: '',
  31. }
  32. export class StateChangeEvent extends CustomEvent<{
  33. state: ConnectionState
  34. previousState: ConnectionState
  35. }> {}
  36. export class ConnectionManager extends EventTarget {
  37. state: ConnectionState = initialState
  38. private connectionAttempt: number | null = null
  39. private gracefullyReconnectUntil = 0
  40. private lastUserActivity: number
  41. private protocolVersion = -1
  42. private readonly idleDisconnectInterval: number
  43. private reconnectCountdownInterval = 0
  44. readonly socket: Socket
  45. private userIsLeavingPage = false
  46. private externalHeartbeatInterval?: number
  47. private externalHeartbeat: ExternalHeartbeat = {
  48. currentStart: 0,
  49. lastSuccess: 0,
  50. lastLatency: 0,
  51. }
  52. constructor() {
  53. super()
  54. this.lastUserActivity = performance.now()
  55. this.idleDisconnectInterval = window.setInterval(() => {
  56. this.disconnectIfIdleSince(DISCONNECT_AFTER_MS)
  57. }, ONE_HOUR_IN_MS)
  58. window.addEventListener('online', () => this.onOnline())
  59. window.addEventListener('beforeunload', () => {
  60. this.userIsLeavingPage = true
  61. })
  62. const parsedURL = new URL(
  63. getMeta('ol-wsUrl') || '/socket.io',
  64. window.origin
  65. )
  66. const query = new URLSearchParams({
  67. projectId: getMeta('ol-project_id'),
  68. })
  69. if (externalSocketHeartbeat) {
  70. query.set('esh', '1')
  71. }
  72. const socket = SocketIoShim.connect(parsedURL.origin, {
  73. resource: parsedURL.pathname.slice(1),
  74. 'auto connect': false,
  75. 'connect timeout': 30 * 1000,
  76. 'force new connection': true,
  77. query: query.toString(),
  78. reconnect: false,
  79. }) as unknown as Socket
  80. this.socket = socket
  81. // bail out if socket.io failed to load (e.g. the real-time server is down)
  82. if (typeof window.io !== 'object') {
  83. this.switchToWsFallbackIfPossible()
  84. debugConsole.error(
  85. 'Socket.io javascript not loaded. Please check that the real-time service is running and accessible.'
  86. )
  87. this.changeState({
  88. ...this.state,
  89. error: 'io-not-loaded',
  90. })
  91. return
  92. }
  93. socket.on('connect', () => this.onConnect())
  94. socket.on('disconnect', () => this.onDisconnect())
  95. socket.on('error', () => this.onConnectError())
  96. socket.on('connect_failed', () => this.onConnectError())
  97. socket.on('joinProjectResponse', body => this.onJoinProjectResponse(body))
  98. socket.on('connectionRejected', err => this.onConnectionRejected(err))
  99. socket.on('reconnectGracefully', () => this.onReconnectGracefully())
  100. socket.on('forceDisconnect', (_, delay) => this.onForceDisconnect(delay))
  101. this.tryReconnect()
  102. }
  103. close(error: ConnectionError) {
  104. this.onForceDisconnect(0, error)
  105. }
  106. tryReconnectNow() {
  107. this.tryReconnectWithBackoff(USER_ACTIVITY_RECONNECT_NOW_DELAY)
  108. }
  109. // Called when document is clicked or the editor cursor changes
  110. registerUserActivity() {
  111. this.lastUserActivity = performance.now()
  112. this.userIsLeavingPage = false
  113. this.ensureIsConnected()
  114. }
  115. getSocketDebuggingInfo(): SocketDebuggingInfo {
  116. return {
  117. client_id: this.socket.socket?.sessionid,
  118. transport: this.socket.socket?.transport?.name,
  119. publicId: this.socket.publicId,
  120. lastUserActivity: this.lastUserActivity,
  121. connectionState: this.state,
  122. externalHeartbeat: this.externalHeartbeat,
  123. }
  124. }
  125. private changeState(state: ConnectionState) {
  126. const previousState = this.state
  127. this.state = state
  128. debugConsole.log('[ConnectionManager] changed state', {
  129. previousState,
  130. state,
  131. })
  132. this.dispatchEvent(
  133. new StateChangeEvent('statechange', { detail: { state, previousState } })
  134. )
  135. }
  136. private switchToWsFallbackIfPossible() {
  137. const search = new URLSearchParams(window.location.search)
  138. if (getMeta('ol-wsUrl') && search.get('ws') !== 'fallback') {
  139. // if we tried to boot from a custom real-time backend and failed,
  140. // try reloading and falling back to the siteUrl
  141. search.set('ws', 'fallback')
  142. window.location.search = search.toString()
  143. return true
  144. }
  145. return false
  146. }
  147. private onOnline() {
  148. if (!this.state.inactiveDisconnect) this.ensureIsConnected()
  149. }
  150. private onConnectionRejected(err: any) {
  151. switch (err?.message) {
  152. case 'retry': // pending real-time shutdown
  153. this.startAutoReconnectCountdown(0)
  154. break
  155. case 'rate-limit hit when joining project': // rate-limited
  156. this.changeState({
  157. ...this.state,
  158. error: 'rate-limited',
  159. })
  160. break
  161. case 'not authorized': // not logged in
  162. case 'invalid session': // expired session
  163. this.changeState({
  164. ...this.state,
  165. error: 'not-logged-in',
  166. forceDisconnected: true,
  167. })
  168. break
  169. case 'project not found': // project has been deleted
  170. this.changeState({
  171. ...this.state,
  172. error: 'project-deleted',
  173. forceDisconnected: true,
  174. })
  175. break
  176. default:
  177. this.changeState({
  178. ...this.state,
  179. error: 'unable-to-join',
  180. })
  181. break
  182. }
  183. }
  184. private onConnectError() {
  185. if (this.connectionAttempt === null) return // ignore errors once connected.
  186. if (this.connectionAttempt++ < MAX_RETRY_CONNECT) {
  187. setTimeout(
  188. () => {
  189. if (this.canReconnect()) this.socket.socket.connect()
  190. },
  191. // add jitter to spread reconnects
  192. this.connectionAttempt *
  193. (1 + Math.random()) *
  194. CONNECTION_ERROR_RECONNECT_DELAY
  195. )
  196. } else {
  197. if (!this.switchToWsFallbackIfPossible()) {
  198. this.disconnect()
  199. this.changeState({
  200. ...this.state,
  201. error: 'unable-to-connect',
  202. })
  203. }
  204. }
  205. }
  206. private onConnect() {
  207. if (externalSocketHeartbeat) {
  208. if (this.externalHeartbeatInterval) {
  209. window.clearInterval(this.externalHeartbeatInterval)
  210. }
  211. this.externalHeartbeatInterval = window.setInterval(
  212. () => this.sendExternalHeartbeat(),
  213. 15_000
  214. )
  215. }
  216. }
  217. private onDisconnect() {
  218. this.connectionAttempt = null
  219. if (this.externalHeartbeatInterval) {
  220. window.clearInterval(this.externalHeartbeatInterval)
  221. }
  222. this.externalHeartbeat.currentStart = 0
  223. this.changeState({
  224. ...this.state,
  225. readyState: WebSocket.CLOSED,
  226. })
  227. if (this.disconnectIfIdleSince(DISCONNECT_AFTER_MS)) return
  228. if (this.state.error === 'rate-limited') {
  229. this.tryReconnectWithBackoff(JOIN_PROJECT_RATE_LIMITED_DELAY)
  230. } else {
  231. this.startAutoReconnectCountdown(0)
  232. }
  233. }
  234. private onForceDisconnect(
  235. delay: number,
  236. error: ConnectionError = 'maintenance'
  237. ) {
  238. clearInterval(this.idleDisconnectInterval)
  239. clearTimeout(this.reconnectCountdownInterval)
  240. window.removeEventListener('online', this.onOnline)
  241. window.setTimeout(() => this.disconnect(), 1000 * delay)
  242. this.changeState({
  243. ...this.state,
  244. forceDisconnected: true,
  245. forcedDisconnectDelay: delay,
  246. error,
  247. })
  248. }
  249. private onJoinProjectResponse({
  250. protocolVersion,
  251. publicId,
  252. }: {
  253. protocolVersion: number
  254. publicId: string
  255. }) {
  256. if (
  257. this.protocolVersion !== -1 &&
  258. this.protocolVersion !== protocolVersion
  259. ) {
  260. this.onForceDisconnect(0, 'protocol-changed')
  261. return
  262. }
  263. this.protocolVersion = protocolVersion
  264. this.socket.publicId = publicId
  265. this.connectionAttempt = null
  266. this.changeState({
  267. ...this.state,
  268. readyState: WebSocket.OPEN,
  269. error: '',
  270. reconnectAt: null,
  271. })
  272. }
  273. private onReconnectGracefully() {
  274. // Disconnect idle users a little earlier than the 24h limit.
  275. if (this.disconnectIfIdleSince(DISCONNECT_AFTER_MS * 0.75)) return
  276. if (this.gracefullyReconnectUntil) return
  277. this.gracefullyReconnectUntil =
  278. performance.now() + MAX_RECONNECT_GRACEFULLY_INTERVAL_MS
  279. this.tryReconnectGracefully()
  280. }
  281. private canReconnect(): boolean {
  282. if (this.state.readyState === WebSocket.OPEN) return false // no need to reconnect
  283. if (this.state.forceDisconnected) return false // reconnecting blocked
  284. return true
  285. }
  286. private isReconnectingSoon(ms: number): boolean {
  287. if (!this.state.reconnectAt) return false
  288. return this.state.reconnectAt - performance.now() <= ms
  289. }
  290. private hasReconnectedRecently(ms: number): boolean {
  291. return performance.now() - this.state.lastConnectionAttempt < ms
  292. }
  293. private isUserInactiveSince(since: number): boolean {
  294. return performance.now() - this.lastUserActivity > since
  295. }
  296. private disconnectIfIdleSince(threshold: number): boolean {
  297. if (!this.isUserInactiveSince(threshold)) return false
  298. const previouslyClosed = this.state.readyState === WebSocket.CLOSED
  299. this.changeState({
  300. ...this.state,
  301. readyState: WebSocket.CLOSED,
  302. inactiveDisconnect: true,
  303. })
  304. if (!previouslyClosed) {
  305. this.socket.disconnect()
  306. }
  307. return true
  308. }
  309. disconnect() {
  310. this.changeState({
  311. ...this.state,
  312. readyState: WebSocket.CLOSED,
  313. })
  314. this.socket.disconnect()
  315. }
  316. private ensureIsConnected() {
  317. if (this.state.readyState === WebSocket.OPEN) return
  318. this.tryReconnectWithBackoff(
  319. this.state.error === 'rate-limited'
  320. ? JOIN_PROJECT_RATE_LIMITED_DELAY
  321. : USER_ACTIVITY_RECONNECT_DELAY
  322. )
  323. }
  324. private startAutoReconnectCountdown(backoff: number) {
  325. if (this.userIsLeavingPage) return
  326. if (!this.canReconnect()) return
  327. let countdown
  328. if (this.isUserInactiveSince(TWO_MINUTES_IN_MS)) {
  329. countdown = 60 + Math.floor(Math.random() * 2 * 60)
  330. } else {
  331. countdown = 3 + Math.floor(Math.random() * 7)
  332. }
  333. const ms = backoff + countdown * 1000
  334. if (this.isReconnectingSoon(ms)) return
  335. this.changeState({
  336. ...this.state,
  337. reconnectAt: performance.now() + ms,
  338. })
  339. clearTimeout(this.reconnectCountdownInterval)
  340. this.reconnectCountdownInterval = window.setTimeout(() => {
  341. if (this.isReconnectingSoon(0)) {
  342. this.tryReconnect()
  343. }
  344. }, ms)
  345. }
  346. private tryReconnect() {
  347. this.gracefullyReconnectUntil = 0
  348. this.changeState({
  349. ...this.state,
  350. reconnectAt: null,
  351. })
  352. if (!this.canReconnect()) return
  353. this.connectionAttempt = 0
  354. this.changeState({
  355. ...this.state,
  356. readyState: WebSocket.CONNECTING,
  357. error: '',
  358. inactiveDisconnect: false,
  359. lastConnectionAttempt: performance.now(),
  360. })
  361. this.addReconnectListeners()
  362. this.socket.socket.connect()
  363. }
  364. private addReconnectListeners() {
  365. const handleFailure = () => {
  366. removeSocketListeners()
  367. this.startAutoReconnectCountdown(0)
  368. }
  369. const handleSuccess = () => {
  370. removeSocketListeners()
  371. }
  372. const removeSocketListeners = () => {
  373. this.socket.removeListener('error', handleFailure)
  374. this.socket.removeListener('connect', handleSuccess)
  375. }
  376. this.socket.on('error', handleFailure)
  377. this.socket.on('connect', handleSuccess)
  378. }
  379. private tryReconnectGracefully() {
  380. if (
  381. this.state.readyState === WebSocket.CLOSED ||
  382. !this.gracefullyReconnectUntil
  383. )
  384. return
  385. if (
  386. this.gracefullyReconnectUntil < performance.now() ||
  387. this.isUserInactiveSince(RECONNECT_GRACEFULLY_RETRY_INTERVAL_MS)
  388. ) {
  389. this.disconnect()
  390. this.tryReconnect()
  391. } else {
  392. setTimeout(() => {
  393. this.tryReconnectGracefully()
  394. }, RECONNECT_GRACEFULLY_RETRY_INTERVAL_MS)
  395. }
  396. }
  397. private tryReconnectWithBackoff(backoff: number) {
  398. if (this.hasReconnectedRecently(backoff)) {
  399. this.startAutoReconnectCountdown(backoff)
  400. } else {
  401. this.tryReconnect()
  402. }
  403. }
  404. private sendExternalHeartbeat() {
  405. const t0 = performance.now()
  406. this.socket.emit('debug.getHostname', () => {
  407. if (this.externalHeartbeat.currentStart !== t0) {
  408. return
  409. }
  410. const t1 = performance.now()
  411. this.externalHeartbeat = {
  412. currentStart: 0,
  413. lastSuccess: t1,
  414. lastLatency: t1 - t0,
  415. }
  416. })
  417. this.externalHeartbeat.currentStart = t0
  418. }
  419. }