ConnectionManager.js 22 KB

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