ShareJsDoc.js 15 KB

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