ConnectionManager.js 23 KB

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