ShareJsDoc.coffee 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. define [
  2. "utils/EventEmitter"
  3. "libs/sharejs"
  4. ], (EventEmitter, ShareJs) ->
  5. SINGLE_USER_FLUSH_DELAY = 1000 #ms
  6. class ShareJsDoc extends EventEmitter
  7. constructor: (@doc_id, docLines, version, @socket) ->
  8. # Dencode any binary bits of data
  9. # See http://ecmanaut.blogspot.co.uk/2006/07/encoding-decoding-utf8-in-javascript.html
  10. @type = "text"
  11. docLines = (decodeURIComponent(escape(line)) for line in docLines)
  12. snapshot = docLines.join("\n")
  13. @track_changes = false
  14. @connection = {
  15. send: (update) =>
  16. @_startInflightOpTimeout(update)
  17. if window.disconnectOnUpdate? and Math.random() < window.disconnectOnUpdate
  18. sl_console.log "Disconnecting on update", update
  19. window._ide.socket.socket.disconnect()
  20. if window.dropUpdates? and Math.random() < window.dropUpdates
  21. sl_console.log "Simulating a lost update", update
  22. return
  23. if @track_changes
  24. update.meta ?= {}
  25. update.meta.tc = @track_changes_id_seeds.inflight
  26. # console.log ">> update", @doc_id, update
  27. @socket.emit "applyOtUpdate", @doc_id, update, (error) =>
  28. return @_handleError(error) if error?
  29. state: "ok"
  30. id: @socket.socket.sessionid
  31. }
  32. @_doc = new ShareJs.Doc @connection, @doc_id,
  33. type: @type
  34. @_doc.setFlushDelay(SINGLE_USER_FLUSH_DELAY)
  35. @_doc.on "change", (args...) =>
  36. @trigger "change", args...
  37. @_doc.on "acknowledge", () =>
  38. @lastAcked = new Date() # note time of last ack from server for an op we sent
  39. @trigger "acknowledge"
  40. @_doc.on "remoteop", (args...) =>
  41. # As soon as we're working with a collaborator, start sending
  42. # ops as quickly as possible for low latency.
  43. @_doc.setFlushDelay(0)
  44. @trigger "remoteop", args...
  45. @_doc.on "flipped_pending_to_inflight", () =>
  46. @trigger "flipped_pending_to_inflight"
  47. @_doc.on "error", (e) =>
  48. @_handleError(e)
  49. @_bindToDocChanges(@_doc)
  50. @processUpdateFromServer
  51. open: true
  52. v: version
  53. snapshot: snapshot
  54. submitOp: (args...) -> @_doc.submitOp(args...)
  55. processUpdateFromServer: (message) ->
  56. try
  57. @_doc._onMessage message
  58. catch error
  59. # Version mismatches are thrown as errors
  60. console.log error
  61. @_handleError(error)
  62. if message?.meta?.type == "external"
  63. @trigger "externalUpdate", message
  64. catchUp: (updates) ->
  65. for update, i in updates
  66. update.v = @_doc.version
  67. update.doc = @doc_id
  68. @processUpdateFromServer(update)
  69. getSnapshot: () -> @_doc.snapshot
  70. getVersion: () -> @_doc.version
  71. getType: () -> @type
  72. clearInflightAndPendingOps: () ->
  73. @_doc.inflightOp = null
  74. @_doc.inflightCallbacks = []
  75. @_doc.pendingOp = null
  76. @_doc.pendingCallbacks = []
  77. flushPendingOps: () ->
  78. # This will flush any ops that are pending.
  79. # If there is an inflight op it will do nothing.
  80. @_doc.flush()
  81. updateConnectionState: (state) ->
  82. sl_console.log "[updateConnectionState] Setting state to #{state}"
  83. @connection.state = state
  84. @connection.id = @socket.socket.sessionid
  85. @_doc.autoOpen = false
  86. @_doc._connectionStateChanged(state)
  87. @lastAcked = null # reset the last ack time when connection changes
  88. hasBufferedOps: () ->
  89. @_doc.inflightOp? or @_doc.pendingOp?
  90. getInflightOp: () -> @_doc.inflightOp
  91. getPendingOp: () -> @_doc.pendingOp
  92. getRecentAck: () ->
  93. # check if we have received an ack recently (within the flush delay)
  94. @lastAcked? and new Date() - @lastAcked < @_doc._flushDelay
  95. getOpSize: (op) ->
  96. # compute size of an op from its components
  97. # (total number of characters inserted and deleted)
  98. size = 0
  99. for component in op or []
  100. if component?.i?
  101. size += component.i.length
  102. if component?.d?
  103. size += component.d.length
  104. return size
  105. attachToAce: (ace) -> @_doc.attach_ace(ace, false, window.maxDocLength)
  106. detachFromAce: () -> @_doc.detach_ace?()
  107. INFLIGHT_OP_TIMEOUT: 5000 # Retry sending ops after 5 seconds without an ack
  108. WAIT_FOR_CONNECTION_TIMEOUT: 500 # If we're waiting for the project to join, try again in 0.5 seconds
  109. _startInflightOpTimeout: (update) ->
  110. @_startFatalTimeoutTimer(update)
  111. retryOp = () =>
  112. # Only send the update again if inflightOp is still populated
  113. # This can be cleared when hard reloading the document in which
  114. # case we don't want to keep trying to send it.
  115. sl_console.log "[inflightOpTimeout] Trying op again"
  116. if @_doc.inflightOp?
  117. # When there is a socket.io disconnect, @_doc.inflightSubmittedIds
  118. # is updated with the socket.io client id of the current op in flight
  119. # (meta.source of the op).
  120. # @connection.id is the client id of the current socket.io session.
  121. # So we need both depending on whether the op was submitted before
  122. # one or more disconnects, or if it was submitted during the current session.
  123. update.dupIfSource = [@connection.id, @_doc.inflightSubmittedIds...]
  124. # We must be joined to a project for applyOtUpdate to work on the real-time
  125. # service, so don't send an op if we're not. Connection state is set to 'ok'
  126. # when we've joined the project
  127. if @connection.state != "ok"
  128. sl_console.log "[inflightOpTimeout] Not connected, retrying in 0.5s"
  129. timer = setTimeout retryOp, @WAIT_FOR_CONNECTION_TIMEOUT
  130. else
  131. sl_console.log "[inflightOpTimeout] Sending"
  132. @connection.send(update)
  133. timer = setTimeout retryOp, @INFLIGHT_OP_TIMEOUT
  134. @_doc.inflightCallbacks.push () =>
  135. @_clearFatalTimeoutTimer()
  136. clearTimeout timer
  137. FATAL_OP_TIMEOUT: 30000 # 30 seconds
  138. _startFatalTimeoutTimer: (update) ->
  139. # If an op doesn't get acked within FATAL_OP_TIMEOUT, something has
  140. # gone unrecoverably wrong (the op will have been retried multiple times)
  141. return if @_timeoutTimer?
  142. @_timeoutTimer = setTimeout () =>
  143. @_clearFatalTimeoutTimer()
  144. @trigger "op:timeout", update
  145. , @FATAL_OP_TIMEOUT
  146. _clearFatalTimeoutTimer: () ->
  147. return if !@_timeoutTimer?
  148. clearTimeout @_timeoutTimer
  149. @_timeoutTimer = null
  150. _handleError: (error, meta = {}) ->
  151. @trigger "error", error, meta
  152. _bindToDocChanges: (doc) ->
  153. submitOp = doc.submitOp
  154. doc.submitOp = (args...) =>
  155. @trigger "op:sent", args...
  156. doc.pendingCallbacks.push () =>
  157. @trigger "op:acknowledged", args...
  158. submitOp.apply(doc, args)
  159. flush = doc.flush
  160. doc.flush = (args...) =>
  161. @trigger "flush", doc.inflightOp, doc.pendingOp, doc.version
  162. flush.apply(doc, args)