connection-manager.ts 9.7 KB

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