ShareJsDoc.js 14 KB

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