ConnectionManager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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.$scope.connection.reconnecting = true
  225. // if reconnecting takes more than 1s (it doesn't, usually) show the
  226. // 'reconnecting...' warning
  227. setTimeout(() => {
  228. if (
  229. this.$scope.connection.reconnecting &&
  230. this.$scope.connection.jobId === jobId
  231. ) {
  232. this.$scope.connection.stillReconnecting = true
  233. }
  234. }, 1000)
  235. } else if (state === 'authenticating') {
  236. // socket connection has been established, trying to authenticate
  237. } else if (state === 'joining') {
  238. // authenticated, joining project
  239. this.$scope.connection.joining = true
  240. } else if (state === 'ready') {
  241. // project has been joined
  242. } else if (state === 'waitingCountdown') {
  243. // disconnected and waiting to reconnect via the countdown timer
  244. this.cancelReconnect()
  245. } else if (state === 'waitingGracefully') {
  246. // disconnected and waiting to reconnect gracefully
  247. this.cancelReconnect()
  248. } else if (state === 'inactive') {
  249. // disconnected and not trying to reconnect (inactive)
  250. } else if (state === 'error') {
  251. // something is wrong
  252. } else {
  253. sl_console.log(
  254. `[WARN] [updateConnectionManagerState ${jobId}] got unrecognised state ${state}`
  255. )
  256. }
  257. })
  258. }
  259. expectConnectionManagerState(state, jobId) {
  260. if (
  261. this.$scope.connection.state === state &&
  262. (!jobId || jobId === this.$scope.connection.jobId)
  263. ) {
  264. return true
  265. }
  266. sl_console.log(
  267. `[WARN] [state mismatch] expected state ${state}${
  268. jobId ? '/' + jobId : ''
  269. } when in ${this.$scope.connection.state}/${
  270. this.$scope.connection.jobId
  271. }`
  272. )
  273. return false
  274. }
  275. // Error reporting, which can reload the page if appropriate
  276. reportConnectionError(err) {
  277. sl_console.log('[socket.io] reporting connection error')
  278. this.updateConnectionManagerState('error')
  279. if (
  280. (err != null ? err.message : undefined) === 'not authorized' ||
  281. (err != null ? err.message : undefined) === 'invalid session'
  282. ) {
  283. return (window.location = `/login?redir=${encodeURI(
  284. window.location.pathname
  285. )}`)
  286. } else {
  287. this.ide.socket.disconnect()
  288. return this.ide.showGenericMessageModal(
  289. 'Something went wrong connecting',
  290. `\
  291. Something went wrong connecting to your project. Please refresh if this continues to happen.\
  292. `
  293. )
  294. }
  295. }
  296. joinProject(connectionId) {
  297. sl_console.log(`[joinProject ${connectionId}] joining...`)
  298. // Note: if the "joinProject" message doesn't reach the server
  299. // (e.g. if we are in a disconnected state at this point) the
  300. // callback will never be executed
  301. if (!this.expectConnectionManagerState('joining', connectionId)) {
  302. sl_console.log(
  303. `[joinProject ${connectionId}] aborting with stale connection`
  304. )
  305. return
  306. }
  307. const data = {
  308. project_id: this.ide.project_id
  309. }
  310. if (window.anonymousAccessToken) {
  311. data.anonymousAccessToken = window.anonymousAccessToken
  312. }
  313. this.ide.socket.emit(
  314. 'joinProject',
  315. data,
  316. (err, project, permissionsLevel, protocolVersion) => {
  317. if (err != null || project == null) {
  318. if (err.code === 'TooManyRequests') {
  319. sl_console.log(
  320. `[joinProject ${connectionId}] retrying: ${err.message}`
  321. )
  322. setTimeout(
  323. () => this.joinProject(connectionId),
  324. this.joinProjectRetryInterval
  325. )
  326. if (
  327. this.joinProjectRetryInterval <
  328. this.JOIN_PROJECT_MAX_RETRY_INTERVAL
  329. ) {
  330. this.joinProjectRetryInterval += this.JOIN_PROJECT_RETRY_INTERVAL
  331. }
  332. return
  333. } else {
  334. return this.reportConnectionError(err)
  335. }
  336. }
  337. this.joinProjectRetryInterval = this.JOIN_PROJECT_RETRY_INTERVAL
  338. if (
  339. this.$scope.protocolVersion != null &&
  340. this.$scope.protocolVersion !== protocolVersion
  341. ) {
  342. location.reload(true)
  343. }
  344. this.$scope.$apply(() => {
  345. this.updateConnectionManagerState('ready')
  346. this.$scope.protocolVersion = protocolVersion
  347. this.$scope.project = project
  348. this.$scope.permissionsLevel = permissionsLevel
  349. this.$scope.state.load_progress = 100
  350. this.$scope.state.loading = false
  351. this.$scope.$broadcast('project:joined')
  352. })
  353. }
  354. )
  355. }
  356. reconnectImmediately() {
  357. this.disconnect()
  358. return this.tryReconnect()
  359. }
  360. disconnect() {
  361. if (this.ide.socket.socket && !this.ide.socket.socket.connected) {
  362. sl_console.log(
  363. '[socket.io] skipping disconnect because socket.io has not connected'
  364. )
  365. return
  366. }
  367. sl_console.log('[socket.io] disconnecting client')
  368. return this.ide.socket.disconnect()
  369. }
  370. startAutoReconnectCountdown() {
  371. this.updateConnectionManagerState('waitingCountdown')
  372. let connectionId = this.$scope.connection.jobId
  373. let countdown
  374. sl_console.log('[ConnectionManager] starting autoreconnect countdown')
  375. const twoMinutes = 2 * 60 * 1000
  376. if (
  377. this.lastUserAction != null &&
  378. new Date() - this.lastUserAction > twoMinutes
  379. ) {
  380. // between 1 minute and 3 minutes
  381. countdown = 60 + Math.floor(Math.random() * 120)
  382. } else {
  383. countdown = 3 + Math.floor(Math.random() * 7)
  384. }
  385. if (this.userIsLeavingPage) {
  386. // user will have pressed refresh or back etc
  387. return
  388. }
  389. this.$scope.$apply(() => {
  390. this.$scope.connection.reconnecting = false
  391. this.$scope.connection.stillReconnecting = false
  392. this.$scope.connection.joining = false
  393. this.$scope.connection.reconnection_countdown = countdown
  394. })
  395. setTimeout(() => {
  396. if (!this.connected) {
  397. this.countdownTimeoutId = setTimeout(
  398. () => this.decreaseCountdown(connectionId),
  399. 1000
  400. )
  401. }
  402. }, 200)
  403. }
  404. cancelReconnect() {
  405. this.disconnect()
  406. // clear timeout and set to null so we know there is no countdown running
  407. if (this.countdownTimeoutId != null) {
  408. sl_console.log(
  409. '[ConnectionManager] cancelling existing reconnect timer'
  410. )
  411. clearTimeout(this.countdownTimeoutId)
  412. this.countdownTimeoutId = null
  413. }
  414. }
  415. decreaseCountdown(connectionId) {
  416. this.countdownTimeoutId = null
  417. if (this.$scope.connection.reconnection_countdown == null) {
  418. return
  419. }
  420. if (
  421. !this.expectConnectionManagerState('waitingCountdown', connectionId)
  422. ) {
  423. sl_console.log(
  424. `[ConnectionManager] Aborting stale countdown ${connectionId}`
  425. )
  426. return
  427. }
  428. sl_console.log(
  429. '[ConnectionManager] decreasing countdown',
  430. this.$scope.connection.reconnection_countdown
  431. )
  432. this.$scope.$apply(() => {
  433. this.$scope.connection.reconnection_countdown--
  434. })
  435. if (this.$scope.connection.reconnection_countdown <= 0) {
  436. this.$scope.connection.reconnecting = false
  437. this.$scope.$apply(() => {
  438. this.tryReconnect()
  439. })
  440. } else {
  441. this.countdownTimeoutId = setTimeout(
  442. () => this.decreaseCountdown(connectionId),
  443. 1000
  444. )
  445. }
  446. }
  447. tryReconnect() {
  448. sl_console.log('[ConnectionManager] tryReconnect')
  449. if (this.connected || this.$scope.connection.reconnecting) {
  450. return
  451. }
  452. this.updateConnectionManagerState('reconnecting')
  453. sl_console.log('[ConnectionManager] Starting new connection')
  454. // use socket.io connect() here to make a single attempt, the
  455. // reconnect() method makes multiple attempts
  456. this.ide.socket.socket.connect()
  457. // record the time of the last attempt to connect
  458. this.lastConnectionAttempt = new Date()
  459. }
  460. tryReconnectWithRateLimit(options) {
  461. // bail out if the reconnect is already in progress
  462. if (this.$scope.connection.reconnecting || this.connected) {
  463. return
  464. }
  465. // bail out if we are going to reconnect soon anyway
  466. const reconnectingSoon =
  467. this.$scope.connection.reconnection_countdown != null &&
  468. this.$scope.connection.reconnection_countdown <= 5
  469. const clickedTryNow = options != null ? options.force : undefined // user requested reconnection
  470. if (reconnectingSoon && !clickedTryNow) {
  471. return
  472. }
  473. // bail out if we tried reconnecting recently
  474. const allowedInterval = clickedTryNow
  475. ? this.MIN_RETRY_INTERVAL
  476. : this.BACKGROUND_RETRY_INTERVAL
  477. if (
  478. this.lastConnectionAttempt != null &&
  479. new Date() - this.lastConnectionAttempt < allowedInterval
  480. ) {
  481. if (this.$scope.connection.state !== 'waitingCountdown') {
  482. this.startAutoReconnectCountdown()
  483. }
  484. return
  485. }
  486. this.tryReconnect()
  487. }
  488. disconnectIfInactive() {
  489. this.userIsInactive =
  490. new Date() - this.lastUserAction > this.disconnectAfterMs
  491. if (this.userIsInactive && this.connected) {
  492. this.disconnect()
  493. return this.$scope.$apply(() => {
  494. return (this.$scope.connection.inactive_disconnect = true)
  495. }) // 5 minutes
  496. }
  497. }
  498. reconnectGracefully(force) {
  499. if (this.reconnectGracefullyStarted == null) {
  500. this.reconnectGracefullyStarted = new Date()
  501. } else {
  502. if (!force) {
  503. sl_console.log(
  504. '[reconnectGracefully] reconnection is already in process, so skipping'
  505. )
  506. return
  507. }
  508. }
  509. const userIsInactive =
  510. new Date() - this.lastUserAction >
  511. this.RECONNECT_GRACEFULLY_RETRY_INTERVAL
  512. const maxIntervalReached =
  513. new Date() - this.reconnectGracefullyStarted >
  514. this.MAX_RECONNECT_GRACEFULLY_INTERVAL
  515. if (userIsInactive || maxIntervalReached) {
  516. sl_console.log(
  517. "[reconnectGracefully] User didn't do anything for last 5 seconds, reconnecting"
  518. )
  519. this._reconnectGracefullyNow()
  520. } else {
  521. sl_console.log(
  522. '[reconnectGracefully] User is working, will try again in 5 seconds'
  523. )
  524. this.updateConnectionManagerState('waitingGracefully')
  525. setTimeout(() => {
  526. this.reconnectGracefully(true)
  527. }, this.RECONNECT_GRACEFULLY_RETRY_INTERVAL)
  528. }
  529. }
  530. _reconnectGracefullyNow() {
  531. this.gracefullyReconnecting = true
  532. this.reconnectGracefullyStarted = null
  533. // Clear cookie so we don't go to the same backend server
  534. $.cookie('SERVERID', '', { expires: -1, path: '/' })
  535. return this.reconnectImmediately()
  536. }
  537. }
  538. ConnectionManager.initClass()
  539. return ConnectionManager
  540. })())
  541. })