ShareJsDoc.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /* eslint-disable
  2. camelcase,
  3. max-len,
  4. no-unused-vars,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS001: Remove Babel/TypeScript constructor workaround
  11. * DS101: Remove unnecessary use of Array.from
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS103: Rewrite code to no longer use __guard__
  14. * DS205: Consider reworking code to avoid use of IIFEs
  15. * DS206: Consider reworking classes to avoid initClass
  16. * DS207: Consider shorter variations of null checks
  17. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  18. */
  19. import EventEmitter from '../../utils/EventEmitter'
  20. import ShareJs from '../../vendor/libs/sharejs'
  21. import EditorWatchdogManager from '../connection/EditorWatchdogManager'
  22. import { debugConsole } from '@/utils/debugging'
  23. import { recordDocumentFirstChangeEvent } from '@/features/event-tracking/document-first-change-event'
  24. let ShareJsDoc
  25. const SINGLE_USER_FLUSH_DELAY = 2000 // ms
  26. const MULTI_USER_FLUSH_DELAY = 500 // ms
  27. export default ShareJsDoc = (function () {
  28. ShareJsDoc = class ShareJsDoc extends EventEmitter {
  29. static initClass() {
  30. this.prototype.INFLIGHT_OP_TIMEOUT = 5000 // Retry sending ops after 5 seconds without an ack
  31. this.prototype.WAIT_FOR_CONNECTION_TIMEOUT = 500
  32. this.prototype.FATAL_OP_TIMEOUT = 30000
  33. }
  34. constructor(
  35. doc_id,
  36. docLines,
  37. version,
  38. socket,
  39. globalEditorWatchdogManager
  40. ) {
  41. super()
  42. // Dencode any binary bits of data
  43. // See http://ecmanaut.blogspot.co.uk/2006/07/encoding-decoding-utf8-in-javascript.html
  44. this.doc_id = doc_id
  45. this.socket = socket
  46. this.type = 'text'
  47. docLines = Array.from(docLines).map(line =>
  48. decodeURIComponent(escape(line))
  49. )
  50. const snapshot = docLines.join('\n')
  51. this.track_changes = false
  52. this.connection = {
  53. send: update => {
  54. this._startInflightOpTimeout(update)
  55. if (
  56. window.disconnectOnUpdate != null &&
  57. Math.random() < window.disconnectOnUpdate
  58. ) {
  59. debugConsole.log('Disconnecting on update', update)
  60. window._ide.socket.socket.disconnect()
  61. }
  62. if (
  63. window.dropUpdates != null &&
  64. Math.random() < window.dropUpdates
  65. ) {
  66. debugConsole.log('Simulating a lost update', update)
  67. return
  68. }
  69. if (this.track_changes) {
  70. if (update.meta == null) {
  71. update.meta = {}
  72. }
  73. update.meta.tc = this.track_changes_id_seeds.inflight
  74. }
  75. return this.socket.emit(
  76. 'applyOtUpdate',
  77. this.doc_id,
  78. update,
  79. error => {
  80. if (error != null) {
  81. return this._handleError(error)
  82. }
  83. }
  84. )
  85. },
  86. state: 'ok',
  87. id: this.socket.publicId,
  88. }
  89. this._doc = new ShareJs.Doc(this.connection, this.doc_id, {
  90. type: this.type,
  91. })
  92. this._doc.setFlushDelay(SINGLE_USER_FLUSH_DELAY)
  93. this._doc.on('change', (...args) => {
  94. return this.trigger('change', ...Array.from(args))
  95. })
  96. this.EditorWatchdogManager = new EditorWatchdogManager({
  97. parent: globalEditorWatchdogManager,
  98. })
  99. this._doc.on('acknowledge', () => {
  100. this.lastAcked = new Date() // note time of last ack from server for an op we sent
  101. this.EditorWatchdogManager.onAck() // keep track of last ack globally
  102. return this.trigger('acknowledge')
  103. })
  104. this._doc.on('remoteop', (...args) => {
  105. // As soon as we're working with a collaborator, start sending
  106. // ops more frequently for low latency.
  107. this._doc.setFlushDelay(MULTI_USER_FLUSH_DELAY)
  108. return this.trigger('remoteop', ...Array.from(args))
  109. })
  110. this._doc.on('flipped_pending_to_inflight', () => {
  111. return this.trigger('flipped_pending_to_inflight')
  112. })
  113. this._doc.on('saved', () => {
  114. return this.trigger('saved')
  115. })
  116. this._doc.on('error', e => {
  117. return this._handleError(e)
  118. })
  119. this._bindToDocChanges(this._doc)
  120. this.processUpdateFromServer({
  121. open: true,
  122. v: version,
  123. snapshot,
  124. })
  125. this._removeCarriageReturnCharFromShareJsDoc()
  126. }
  127. _removeCarriageReturnCharFromShareJsDoc() {
  128. const doc = this._doc
  129. if (doc.snapshot.indexOf('\r') === -1) {
  130. return
  131. }
  132. window._ide.pushEvent('remove-carriage-return-char', {
  133. doc_id: this.doc_id,
  134. })
  135. let nextPos
  136. while ((nextPos = doc.snapshot.indexOf('\r')) !== -1) {
  137. debugConsole.log('[ShareJsDoc] remove-carriage-return-char', nextPos)
  138. doc.del(nextPos, 1)
  139. }
  140. }
  141. submitOp(...args) {
  142. return this._doc.submitOp(...Array.from(args || []))
  143. }
  144. // The following code puts out of order messages into a queue
  145. // so that they can be processed in order. This is a workaround
  146. // for messages being delayed by redis cluster.
  147. // FIXME: REMOVE THIS WHEN REDIS PUBSUB IS SENDING MESSAGES IN ORDER
  148. _isAheadOfExpectedVersion(message) {
  149. return this._doc.version > 0 && message.v > this._doc.version
  150. }
  151. _pushOntoQueue(message) {
  152. debugConsole.log(`[processUpdate] push onto queue ${message.v}`)
  153. // set a timer so that we never leave messages in the queue indefinitely
  154. if (!this.queuedMessageTimer) {
  155. this.queuedMessageTimer = setTimeout(() => {
  156. debugConsole.log(
  157. `[processUpdate] queue timeout fired for ${message.v}`
  158. )
  159. // force the message to be processed after the timeout,
  160. // it will cause an error if the missing update has not arrived
  161. this.processUpdateFromServer(message)
  162. }, this.INFLIGHT_OP_TIMEOUT)
  163. }
  164. this.queuedMessages.push(message)
  165. // keep the queue in order, lowest version first
  166. this.queuedMessages.sort(function (a, b) {
  167. return a.v - b.v
  168. })
  169. }
  170. _clearQueue() {
  171. this.queuedMessages = []
  172. }
  173. _processQueue() {
  174. if (this.queuedMessages.length > 0) {
  175. const nextAvailableVersion = this.queuedMessages[0].v
  176. if (nextAvailableVersion > this._doc.version) {
  177. // there are updates we still can't apply yet
  178. } else {
  179. // there's a version we can accept on the queue, apply it
  180. debugConsole.log(
  181. `[processUpdate] taken from queue ${nextAvailableVersion}`
  182. )
  183. this.processUpdateFromServerInOrder(this.queuedMessages.shift())
  184. // clear the pending timer if the queue has now been cleared
  185. if (this.queuedMessages.length === 0 && this.queuedMessageTimer) {
  186. debugConsole.log('[processUpdate] queue is empty, cleared timeout')
  187. clearTimeout(this.queuedMessageTimer)
  188. this.queuedMessageTimer = null
  189. }
  190. }
  191. }
  192. }
  193. // FIXME: This is the new method which reorders incoming updates if needed
  194. // called from Document.js
  195. processUpdateFromServerInOrder(message) {
  196. // Create an array to hold queued messages
  197. if (!this.queuedMessages) {
  198. this.queuedMessages = []
  199. }
  200. // Is this update ahead of the next expected update?
  201. // If so, put it on a queue to be handled later.
  202. if (this._isAheadOfExpectedVersion(message)) {
  203. this._pushOntoQueue(message)
  204. return // defer processing this update for now
  205. }
  206. const error = this.processUpdateFromServer(message)
  207. if (
  208. error instanceof Error &&
  209. error.message === 'Invalid version from server'
  210. ) {
  211. // if there was an error, abandon the queued updates ahead of this one
  212. this._clearQueue()
  213. return
  214. }
  215. // Do we have any messages queued up?
  216. // find the next message if available
  217. this._processQueue()
  218. }
  219. // FIXME: This is the original method. Switch back to this when redis
  220. // issues are resolved.
  221. processUpdateFromServer(message) {
  222. try {
  223. this._doc._onMessage(message)
  224. } catch (error) {
  225. // Version mismatches are thrown as errors
  226. debugConsole.error(error)
  227. this._handleError(error)
  228. return error // return the error for queue handling
  229. }
  230. if (
  231. __guard__(message != null ? message.meta : undefined, x => x.type) ===
  232. 'external'
  233. ) {
  234. return this.trigger('externalUpdate', message)
  235. }
  236. }
  237. catchUp(updates) {
  238. return (() => {
  239. const result = []
  240. for (let i = 0; i < updates.length; i++) {
  241. const update = updates[i]
  242. update.v = this._doc.version
  243. update.doc = this.doc_id
  244. result.push(this.processUpdateFromServer(update))
  245. }
  246. return result
  247. })()
  248. }
  249. getSnapshot() {
  250. return this._doc.snapshot
  251. }
  252. getVersion() {
  253. return this._doc.version
  254. }
  255. getType() {
  256. return this.type
  257. }
  258. clearInflightAndPendingOps() {
  259. this._clearFatalTimeoutTimer()
  260. this._doc.inflightOp = null
  261. this._doc.inflightCallbacks = []
  262. this._doc.pendingOp = null
  263. return (this._doc.pendingCallbacks = [])
  264. }
  265. flushPendingOps() {
  266. // This will flush any ops that are pending.
  267. // If there is an inflight op it will do nothing.
  268. return this._doc.flush()
  269. }
  270. updateConnectionState(state) {
  271. debugConsole.log(`[updateConnectionState] Setting state to ${state}`)
  272. this.connection.state = state
  273. this.connection.id = this.socket.publicId
  274. this._doc.autoOpen = false
  275. this._doc._connectionStateChanged(state)
  276. return (this.lastAcked = null) // reset the last ack time when connection changes
  277. }
  278. hasBufferedOps() {
  279. return this._doc.inflightOp != null || this._doc.pendingOp != null
  280. }
  281. getInflightOp() {
  282. return this._doc.inflightOp
  283. }
  284. getPendingOp() {
  285. return this._doc.pendingOp
  286. }
  287. getRecentAck() {
  288. // check if we have received an ack recently (within a factor of two of the single user flush delay)
  289. return (
  290. this.lastAcked != null &&
  291. new Date() - this.lastAcked < 2 * SINGLE_USER_FLUSH_DELAY
  292. )
  293. }
  294. getOpSize(op) {
  295. // compute size of an op from its components
  296. // (total number of characters inserted and deleted)
  297. let size = 0
  298. for (const component of Array.from(op || [])) {
  299. if ((component != null ? component.i : undefined) != null) {
  300. size += component.i.length
  301. }
  302. if ((component != null ? component.d : undefined) != null) {
  303. size += component.d.length
  304. }
  305. }
  306. return size
  307. }
  308. _attachEditorWatchdogManager(editorName, editor) {
  309. // end-to-end check for edits -> acks, for this very ShareJsdoc
  310. // This will catch a broken connection and missing UX-blocker for the
  311. // user, allowing them to keep editing.
  312. this._detachEditorWatchdogManager =
  313. this.EditorWatchdogManager.attachToEditor(editorName, editor)
  314. }
  315. _attachToEditor(editorName, editor, attachToShareJs) {
  316. this._attachEditorWatchdogManager(editorName, editor)
  317. attachToShareJs()
  318. }
  319. _maybeDetachEditorWatchdogManager() {
  320. // a failed attach attempt may lead to a missing cleanup handler
  321. if (this._detachEditorWatchdogManager) {
  322. this._detachEditorWatchdogManager()
  323. delete this._detachEditorWatchdogManager
  324. }
  325. }
  326. attachToCM6(cm6) {
  327. this._attachToEditor('CM6', cm6, () => {
  328. cm6.attachShareJs(this._doc, window.maxDocLength)
  329. })
  330. }
  331. detachFromCM6() {
  332. this._maybeDetachEditorWatchdogManager()
  333. if (this._doc.detach_cm6) {
  334. this._doc.detach_cm6()
  335. }
  336. }
  337. _startInflightOpTimeout(update) {
  338. this._startFatalTimeoutTimer(update)
  339. const retryOp = () => {
  340. // Only send the update again if inflightOp is still populated
  341. // This can be cleared when hard reloading the document in which
  342. // case we don't want to keep trying to send it.
  343. debugConsole.log('[inflightOpTimeout] Trying op again')
  344. if (this._doc.inflightOp != null) {
  345. // When there is a socket.io disconnect, @_doc.inflightSubmittedIds
  346. // is updated with the socket.io client id of the current op in flight
  347. // (meta.source of the op).
  348. // @connection.id is the client id of the current socket.io session.
  349. // So we need both depending on whether the op was submitted before
  350. // one or more disconnects, or if it was submitted during the current session.
  351. update.dupIfSource = [
  352. this.connection.id,
  353. ...Array.from(this._doc.inflightSubmittedIds),
  354. ]
  355. // We must be joined to a project for applyOtUpdate to work on the real-time
  356. // service, so don't send an op if we're not. Connection state is set to 'ok'
  357. // when we've joined the project
  358. if (this.connection.state !== 'ok') {
  359. let timer
  360. debugConsole.log(
  361. '[inflightOpTimeout] Not connected, retrying in 0.5s'
  362. )
  363. return (timer = setTimeout(
  364. retryOp,
  365. this.WAIT_FOR_CONNECTION_TIMEOUT
  366. ))
  367. } else {
  368. debugConsole.log('[inflightOpTimeout] Sending')
  369. return this.connection.send(update)
  370. }
  371. }
  372. }
  373. const timer = setTimeout(retryOp, this.INFLIGHT_OP_TIMEOUT)
  374. return this._doc.inflightCallbacks.push(() => {
  375. this._clearFatalTimeoutTimer()
  376. return clearTimeout(timer)
  377. }) // 30 seconds
  378. }
  379. _startFatalTimeoutTimer(update) {
  380. // If an op doesn't get acked within FATAL_OP_TIMEOUT, something has
  381. // gone unrecoverably wrong (the op will have been retried multiple times)
  382. if (this._timeoutTimer != null) {
  383. return
  384. }
  385. return (this._timeoutTimer = setTimeout(() => {
  386. this._clearFatalTimeoutTimer()
  387. return this.trigger('op:timeout', update)
  388. }, this.FATAL_OP_TIMEOUT))
  389. }
  390. _clearFatalTimeoutTimer() {
  391. if (this._timeoutTimer == null) {
  392. return
  393. }
  394. clearTimeout(this._timeoutTimer)
  395. return (this._timeoutTimer = null)
  396. }
  397. _handleError(error, meta) {
  398. if (meta == null) {
  399. meta = {}
  400. }
  401. return this.trigger('error', error, meta)
  402. }
  403. _bindToDocChanges(doc) {
  404. const { submitOp } = doc
  405. doc.submitOp = (...args) => {
  406. recordDocumentFirstChangeEvent()
  407. this.trigger('op:sent', ...Array.from(args))
  408. doc.pendingCallbacks.push(() => {
  409. return this.trigger('op:acknowledged', ...Array.from(args))
  410. })
  411. return submitOp.apply(doc, args)
  412. }
  413. const { flush } = doc
  414. return (doc.flush = (...args) => {
  415. this.trigger('flush', doc.inflightOp, doc.pendingOp, doc.version)
  416. return flush.apply(doc, args)
  417. })
  418. }
  419. }
  420. ShareJsDoc.initClass()
  421. return ShareJsDoc
  422. })()
  423. function __guard__(value, transform) {
  424. return typeof value !== 'undefined' && value !== null
  425. ? transform(value)
  426. : undefined
  427. }