connection-manager.ts 11 KB

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