ShareJsDoc.js 15 KB

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