ShareJsDoc.js 14 KB

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