ConnectionManager.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Fix any style issues and re-enable lint.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS102: Remove unnecessary code created because of implicit returns
  6. * DS206: Consider reworking classes to avoid initClass
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  9. */
  10. /* global io */
  11. define([], function() {
  12. let ConnectionManager
  13. const ONEHOUR = 1000 * 60 * 60
  14. return (ConnectionManager = (function() {
  15. ConnectionManager = class ConnectionManager {
  16. static initClass() {
  17. this.prototype.disconnectAfterMs = ONEHOUR * 24
  18. this.prototype.lastUserAction = new Date()
  19. this.prototype.MIN_RETRY_INTERVAL = 1000 // ms, rate limit on reconnects for user clicking "try now"
  20. this.prototype.BACKGROUND_RETRY_INTERVAL = 5 * 1000
  21. this.prototype.JOIN_PROJECT_RETRY_INTERVAL = 5000
  22. this.prototype.JOIN_PROJECT_MAX_RETRY_INTERVAL = 60000
  23. this.prototype.RECONNECT_GRACEFULLY_RETRY_INTERVAL = 5000 // ms
  24. this.prototype.MAX_RECONNECT_GRACEFULLY_INTERVAL = 45 * 1000
  25. }
  26. constructor(ide, $scope) {
  27. this.ide = ide
  28. this.$scope = $scope
  29. this.wsUrl = ide.wsUrl || null // websocket url (if defined)
  30. if (typeof io === 'undefined' || io === null) {
  31. console.error(
  32. 'Socket.io javascript not loaded. Please check that the real-time service is running and accessible.'
  33. )
  34. this.ide.socket = { on() {} }
  35. this.$scope.$apply(() => {
  36. return (this.$scope.state.error =
  37. 'Could not connect to websocket server :(')
  38. })
  39. return
  40. }
  41. setInterval(() => {
  42. return this.disconnectIfInactive()
  43. }, ONEHOUR)
  44. // trigger a reconnect immediately if network comes back online
  45. window.addEventListener('online', () => {
  46. sl_console.log('[online] browser notified online')
  47. if (!this.connected) {
  48. return this.tryReconnectWithRateLimit({ force: true })
  49. }
  50. })
  51. this.userIsLeavingPage = false
  52. window.addEventListener('beforeunload', () => {
  53. this.userIsLeavingPage = true
  54. }) // Don't return true or it will show a pop up
  55. this.connected = false
  56. this.userIsInactive = false
  57. this.gracefullyReconnecting = false
  58. this.joinProjectRetryInterval = this.JOIN_PROJECT_RETRY_INTERVAL
  59. this.$scope.connection = {
  60. debug: sl_debugging,
  61. reconnecting: false,
  62. stillReconnecting: false,
  63. // If we need to force everyone to reload the editor
  64. forced_disconnect: false,
  65. inactive_disconnect: false,
  66. jobId: 0
  67. }
  68. this.$scope.tryReconnectNow = () => {
  69. // user manually requested reconnection via "Try now" button
  70. return this.tryReconnectWithRateLimit({ force: true })
  71. }
  72. this.$scope.$on('cursor:editor:update', () => {
  73. this.lastUserAction = new Date() // time of last edit
  74. if (!this.connected) {
  75. // user is editing, try to reconnect
  76. return this.tryReconnectWithRateLimit()
  77. }
  78. })
  79. document.querySelector('body').addEventListener('click', e => {
  80. if (!this.connected && e.target.id !== 'try-reconnect-now-button') {
  81. // user is editing, try to reconnect
  82. return this.tryReconnectWithRateLimit()
  83. }
  84. })
  85. // initial connection attempt
  86. this.updateConnectionManagerState('connecting')
  87. this.ide.socket = io.connect(
  88. this.wsUrl,
  89. {
  90. reconnect: false,
  91. 'connect timeout': 30 * 1000,
  92. 'force new connection': true
  93. }
  94. )
  95. // handle network-level websocket errors (e.g. failed dns lookups)
  96. let connectionErrorHandler = err => {
  97. this.updateConnectionManagerState('error')
  98. sl_console.log('socket.io error', err)
  99. if (this.wsUrl && !window.location.href.match(/ws=fallback/)) {
  100. // if we tried to load a custom websocket location and failed
  101. // try reloading and falling back to the siteUrl
  102. window.location = window.location.href + '?ws=fallback'
  103. } else {
  104. this.connected = false
  105. return this.$scope.$apply(() => {
  106. return (this.$scope.state.error =
  107. "Unable to connect, please view the <u><a href='/learn/Kb/Connection_problems'>connection problems guide</a></u> to fix the issue.")
  108. })
  109. }
  110. }
  111. this.ide.socket.on('error', connectionErrorHandler)
  112. // The "connect" event is the first event we get back. It only
  113. // indicates that the websocket is connected, we still need to
  114. // pass authentication to join a project.
  115. this.ide.socket.on('connect', () => {
  116. // state should be 'connecting'...
  117. // remove connection error handler when connected, avoid unwanted fallbacks
  118. this.ide.socket.removeListener('error', connectionErrorHandler)
  119. sl_console.log('[socket.io connect] Connected')
  120. this.updateConnectionManagerState('authenticating')
  121. })
  122. // The next event we should get is an authentication response
  123. // from the server, either "connectionAccepted" or
  124. // "connectionRejected".
  125. this.ide.socket.on('connectionAccepted', message => {
  126. // state should be 'authenticating'...
  127. sl_console.log('[socket.io connectionAccepted] allowed to connect')
  128. this.connected = true
  129. this.gracefullyReconnecting = false
  130. this.ide.pushEvent('connected')
  131. this.updateConnectionManagerState('joining')
  132. this.$scope.$apply(() => {
  133. if (this.$scope.state.loading) {
  134. return (this.$scope.state.load_progress = 70)
  135. }
  136. })
  137. // we have passed authentication so we can now join the project
  138. let connectionJobId = this.$scope.connection.jobId
  139. setTimeout(() => {
  140. this.joinProject(connectionJobId)
  141. }, 100)
  142. })
  143. this.ide.socket.on('connectionRejected', err => {
  144. // state should be 'authenticating'...
  145. sl_console.log(
  146. '[socket.io connectionRejected] session not valid or other connection error'
  147. )
  148. // real time sends a 'retry' message if the process was shutting down
  149. if (err && err.message === 'retry') {
  150. return this.tryReconnectWithRateLimit()
  151. }
  152. // we have failed authentication, usually due to an invalid session cookie
  153. return this.reportConnectionError(err)
  154. })
  155. // Alternatively the attempt to connect can fail completely, so
  156. // we never get into the "connect" state.
  157. this.ide.socket.on('connect_failed', () => {
  158. this.updateConnectionManagerState('error')
  159. this.connected = false
  160. return this.$scope.$apply(() => {
  161. return (this.$scope.state.error =
  162. "Unable to connect, please view the <u><a href='/learn/Kb/Connection_problems'>connection problems guide</a></u> to fix the issue.")
  163. })
  164. })
  165. // We can get a "disconnect" event at any point after the
  166. // "connect" event.
  167. this.ide.socket.on('disconnect', () => {
  168. sl_console.log('[socket.io disconnect] Disconnected')
  169. this.connected = false
  170. this.ide.pushEvent('disconnected')
  171. if (!this.$scope.connection.state.match(/^waiting/)) {
  172. if (
  173. !this.$scope.connection.forced_disconnect &&
  174. !this.userIsInactive
  175. ) {
  176. this.startAutoReconnectCountdown()
  177. } else {
  178. this.updateConnectionManagerState('inactive')
  179. }
  180. }
  181. })
  182. // Site administrators can send the forceDisconnect event to all users
  183. this.ide.socket.on('forceDisconnect', message => {
  184. this.updateConnectionManagerState('inactive')
  185. this.$scope.$apply(() => {
  186. this.$scope.permissions.write = false
  187. return (this.$scope.connection.forced_disconnect = true)
  188. })
  189. this.ide.socket.disconnect()
  190. this.ide.showGenericMessageModal(
  191. 'Please Refresh',
  192. `\
  193. We're performing maintenance on Overleaf and you need to refresh the editor.
  194. Sorry for any inconvenience.
  195. The editor will refresh in automatically in 10 seconds.\
  196. `
  197. )
  198. return setTimeout(() => location.reload(), 10 * 1000)
  199. })
  200. this.ide.socket.on('reconnectGracefully', () => {
  201. sl_console.log('Reconnect gracefully')
  202. this.reconnectGracefully()
  203. })
  204. }
  205. updateConnectionManagerState(state) {
  206. this.$scope.$apply(() => {
  207. this.$scope.connection.jobId += 1
  208. let jobId = this.$scope.connection.jobId
  209. sl_console.log(
  210. `[updateConnectionManagerState ${jobId}] from ${
  211. this.$scope.connection.state
  212. } to ${state}`
  213. )
  214. this.$scope.connection.state = state
  215. this.$scope.connection.reconnecting = false
  216. this.$scope.connection.stillReconnecting = false
  217. this.$scope.connection.inactive_disconnect = false
  218. this.$scope.connection.joining = false
  219. this.$scope.connection.reconnection_countdown = null
  220. if (state === 'connecting') {
  221. // initial connection
  222. } else if (state === 'reconnecting') {
  223. // reconnection after a connection has failed
  224. this.stopReconnectCountdownTimer()
  225. this.$scope.connection.reconnecting = true
  226. // if reconnecting takes more than 1s (it doesn't, usually) show the
  227. // 'reconnecting...' warning
  228. setTimeout(() => {
  229. if (
  230. this.$scope.connection.reconnecting &&
  231. this.$scope.connection.jobId === jobId
  232. ) {
  233. this.$scope.connection.stillReconnecting = true
  234. }
  235. }, 1000)
  236. } else if (state === 'reconnectFailed') {
  237. // reconnect attempt failed
  238. } else if (state === 'authenticating') {
  239. // socket connection has been established, trying to authenticate
  240. } else if (state === 'joining') {
  241. // authenticated, joining project
  242. this.$scope.connection.joining = true
  243. } else if (state === 'ready') {
  244. // project has been joined
  245. } else if (state === 'waitingCountdown') {
  246. // disconnected and waiting to reconnect via the countdown timer
  247. this.stopReconnectCountdownTimer()
  248. } else if (state === 'waitingGracefully') {
  249. // disconnected and waiting to reconnect gracefully
  250. this.stopReconnectCountdownTimer()
  251. } else if (state === 'inactive') {
  252. // disconnected and not trying to reconnect (inactive)
  253. } else if (state === 'error') {
  254. // something is wrong
  255. } else {
  256. sl_console.log(
  257. `[WARN] [updateConnectionManagerState ${jobId}] got unrecognised state ${state}`
  258. )
  259. }
  260. })
  261. }
  262. expectConnectionManagerState(state, jobId) {
  263. if (
  264. this.$scope.connection.state === state &&
  265. (!jobId || jobId === this.$scope.connection.jobId)
  266. ) {
  267. return true
  268. }
  269. sl_console.log(
  270. `[WARN] [state mismatch] expected state ${state}${
  271. jobId ? '/' + jobId : ''
  272. } when in ${this.$scope.connection.state}/${
  273. this.$scope.connection.jobId
  274. }`
  275. )
  276. return false
  277. }
  278. // Error reporting, which can reload the page if appropriate
  279. reportConnectionError(err) {
  280. sl_console.log('[socket.io] reporting connection error')
  281. this.updateConnectionManagerState('error')
  282. if (
  283. (err != null ? err.message : undefined) === 'not authorized' ||
  284. (err != null ? err.message : undefined) === 'invalid session'
  285. ) {
  286. return (window.location = `/login?redir=${encodeURI(
  287. window.location.pathname
  288. )}`)
  289. } else {
  290. this.ide.socket.disconnect()
  291. return this.ide.showGenericMessageModal(
  292. 'Something went wrong connecting',
  293. `\
  294. Something went wrong connecting to your project. Please refresh if this continues to happen.\
  295. `
  296. )
  297. }
  298. }
  299. joinProject(connectionId) {
  300. sl_console.log(`[joinProject ${connectionId}] joining...`)
  301. // Note: if the "joinProject" message doesn't reach the server
  302. // (e.g. if we are in a disconnected state at this point) the
  303. // callback will never be executed
  304. if (!this.expectConnectionManagerState('joining', connectionId)) {
  305. sl_console.log(
  306. `[joinProject ${connectionId}] aborting with stale connection`
  307. )
  308. return
  309. }
  310. const data = {
  311. project_id: this.ide.project_id
  312. }
  313. if (window.anonymousAccessToken) {
  314. data.anonymousAccessToken = window.anonymousAccessToken
  315. }
  316. this.ide.socket.emit(
  317. 'joinProject',
  318. data,
  319. (err, project, permissionsLevel, protocolVersion) => {
  320. if (err != null || project == null) {
  321. if (err.code === 'TooManyRequests') {
  322. sl_console.log(
  323. `[joinProject ${connectionId}] retrying: ${err.message}`
  324. )
  325. setTimeout(
  326. () => this.joinProject(connectionId),
  327. this.joinProjectRetryInterval
  328. )
  329. if (
  330. this.joinProjectRetryInterval <
  331. this.JOIN_PROJECT_MAX_RETRY_INTERVAL
  332. ) {
  333. this.joinProjectRetryInterval += this.JOIN_PROJECT_RETRY_INTERVAL
  334. }
  335. return
  336. } else {
  337. return this.reportConnectionError(err)
  338. }
  339. }
  340. this.joinProjectRetryInterval = this.JOIN_PROJECT_RETRY_INTERVAL
  341. if (
  342. this.$scope.protocolVersion != null &&
  343. this.$scope.protocolVersion !== protocolVersion
  344. ) {
  345. location.reload(true)
  346. }
  347. this.$scope.$apply(() => {
  348. this.updateConnectionManagerState('ready')
  349. this.$scope.protocolVersion = protocolVersion
  350. this.$scope.project = project
  351. this.$scope.permissionsLevel = permissionsLevel
  352. this.$scope.state.load_progress = 100
  353. this.$scope.state.loading = false
  354. this.$scope.$broadcast('project:joined')
  355. })
  356. }
  357. )
  358. }
  359. reconnectImmediately() {
  360. this.disconnect()
  361. return this.tryReconnect()
  362. }
  363. disconnect() {
  364. if (this.ide.socket.socket && !this.ide.socket.socket.connected) {
  365. sl_console.log(
  366. '[socket.io] skipping disconnect because socket.io has not connected'
  367. )
  368. return
  369. }
  370. sl_console.log('[socket.io] disconnecting client')
  371. return this.ide.socket.disconnect()
  372. }
  373. startAutoReconnectCountdown() {
  374. this.updateConnectionManagerState('waitingCountdown')
  375. let connectionId = this.$scope.connection.jobId
  376. let countdown
  377. sl_console.log('[ConnectionManager] starting autoreconnect countdown')
  378. const twoMinutes = 2 * 60 * 1000
  379. if (
  380. this.lastUserAction != null &&
  381. new Date() - this.lastUserAction > twoMinutes
  382. ) {
  383. // between 1 minute and 3 minutes
  384. countdown = 60 + Math.floor(Math.random() * 120)
  385. } else {
  386. countdown = 3 + Math.floor(Math.random() * 7)
  387. }
  388. if (this.userIsLeavingPage) {
  389. // user will have pressed refresh or back etc
  390. return
  391. }
  392. this.$scope.$apply(() => {
  393. this.$scope.connection.reconnecting = false
  394. this.$scope.connection.stillReconnecting = false
  395. this.$scope.connection.joining = false
  396. this.$scope.connection.reconnection_countdown = countdown
  397. })
  398. setTimeout(() => {
  399. if (!this.connected && !this.countdownTimeoutId) {
  400. this.countdownTimeoutId = setTimeout(
  401. () => this.decreaseCountdown(connectionId),
  402. 1000
  403. )
  404. }
  405. }, 200)
  406. }
  407. stopReconnectCountdownTimer() {
  408. // clear timeout and set to null so we know there is no countdown running
  409. if (this.countdownTimeoutId != null) {
  410. sl_console.log(
  411. '[ConnectionManager] cancelling existing reconnect timer'
  412. )
  413. clearTimeout(this.countdownTimeoutId)
  414. this.countdownTimeoutId = null
  415. }
  416. }
  417. decreaseCountdown(connectionId) {
  418. this.countdownTimeoutId = null
  419. if (this.$scope.connection.reconnection_countdown == null) {
  420. return
  421. }
  422. if (
  423. !this.expectConnectionManagerState('waitingCountdown', connectionId)
  424. ) {
  425. sl_console.log(
  426. `[ConnectionManager] Aborting stale countdown ${connectionId}`
  427. )
  428. return
  429. }
  430. sl_console.log(
  431. '[ConnectionManager] decreasing countdown',
  432. this.$scope.connection.reconnection_countdown
  433. )
  434. this.$scope.$apply(() => {
  435. this.$scope.connection.reconnection_countdown--
  436. })
  437. if (this.$scope.connection.reconnection_countdown <= 0) {
  438. this.$scope.connection.reconnecting = false
  439. this.$scope.$apply(() => {
  440. this.tryReconnect()
  441. })
  442. } else {
  443. this.countdownTimeoutId = setTimeout(
  444. () => this.decreaseCountdown(connectionId),
  445. 1000
  446. )
  447. }
  448. }
  449. tryReconnect() {
  450. sl_console.log('[ConnectionManager] tryReconnect')
  451. if (this.connected || this.$scope.connection.reconnecting) {
  452. return
  453. }
  454. this.updateConnectionManagerState('reconnecting')
  455. sl_console.log('[ConnectionManager] Starting new connection')
  456. const removeHandler = () => {
  457. this.ide.socket.removeListener('error', handleFailure)
  458. this.ide.socket.removeListener('connect', handleSuccess)
  459. }
  460. const handleFailure = () => {
  461. sl_console.log('[ConnectionManager] tryReconnect: failed')
  462. removeHandler()
  463. this.updateConnectionManagerState('reconnectFailed')
  464. this.tryReconnectWithRateLimit({ force: true })
  465. }
  466. const handleSuccess = () => {
  467. sl_console.log('[ConnectionManager] tryReconnect: success')
  468. removeHandler()
  469. }
  470. this.ide.socket.on('error', handleFailure)
  471. this.ide.socket.on('connect', handleSuccess)
  472. // use socket.io connect() here to make a single attempt, the
  473. // reconnect() method makes multiple attempts
  474. this.ide.socket.socket.connect()
  475. // record the time of the last attempt to connect
  476. this.lastConnectionAttempt = new Date()
  477. }
  478. tryReconnectWithRateLimit(options) {
  479. // bail out if the reconnect is already in progress
  480. if (this.$scope.connection.reconnecting || this.connected) {
  481. return
  482. }
  483. // bail out if we are going to reconnect soon anyway
  484. const reconnectingSoon =
  485. this.$scope.connection.reconnection_countdown != null &&
  486. this.$scope.connection.reconnection_countdown <= 5
  487. const clickedTryNow = options != null ? options.force : undefined // user requested reconnection
  488. if (reconnectingSoon && !clickedTryNow) {
  489. return
  490. }
  491. // bail out if we tried reconnecting recently
  492. const allowedInterval = clickedTryNow
  493. ? this.MIN_RETRY_INTERVAL
  494. : this.BACKGROUND_RETRY_INTERVAL
  495. if (
  496. this.lastConnectionAttempt != null &&
  497. new Date() - this.lastConnectionAttempt < allowedInterval
  498. ) {
  499. if (this.$scope.connection.state !== 'waitingCountdown') {
  500. this.startAutoReconnectCountdown()
  501. }
  502. return
  503. }
  504. this.tryReconnect()
  505. }
  506. disconnectIfInactive() {
  507. this.userIsInactive =
  508. new Date() - this.lastUserAction > this.disconnectAfterMs
  509. if (this.userIsInactive && this.connected) {
  510. this.disconnect()
  511. return this.$scope.$apply(() => {
  512. return (this.$scope.connection.inactive_disconnect = true)
  513. }) // 5 minutes
  514. }
  515. }
  516. reconnectGracefully(force) {
  517. if (this.reconnectGracefullyStarted == null) {
  518. this.reconnectGracefullyStarted = new Date()
  519. } else {
  520. if (!force) {
  521. sl_console.log(
  522. '[reconnectGracefully] reconnection is already in process, so skipping'
  523. )
  524. return
  525. }
  526. }
  527. const userIsInactive =
  528. new Date() - this.lastUserAction >
  529. this.RECONNECT_GRACEFULLY_RETRY_INTERVAL
  530. const maxIntervalReached =
  531. new Date() - this.reconnectGracefullyStarted >
  532. this.MAX_RECONNECT_GRACEFULLY_INTERVAL
  533. if (userIsInactive || maxIntervalReached) {
  534. sl_console.log(
  535. "[reconnectGracefully] User didn't do anything for last 5 seconds, reconnecting"
  536. )
  537. this._reconnectGracefullyNow()
  538. } else {
  539. sl_console.log(
  540. '[reconnectGracefully] User is working, will try again in 5 seconds'
  541. )
  542. this.updateConnectionManagerState('waitingGracefully')
  543. setTimeout(() => {
  544. this.reconnectGracefully(true)
  545. }, this.RECONNECT_GRACEFULLY_RETRY_INTERVAL)
  546. }
  547. }
  548. _reconnectGracefullyNow() {
  549. this.gracefullyReconnecting = true
  550. this.reconnectGracefullyStarted = null
  551. // Clear cookie so we don't go to the same backend server
  552. $.cookie('SERVERID', '', { expires: -1, path: '/' })
  553. return this.reconnectImmediately()
  554. }
  555. }
  556. ConnectionManager.initClass()
  557. return ConnectionManager
  558. })())
  559. })