ShareJsDoc.js 14 KB

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