ShareJsDoc.js 15 KB

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