Document.coffee 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. define [
  2. "utils/EventEmitter"
  3. "ide/editor/ShareJsDoc"
  4. ], (EventEmitter, ShareJsDoc) ->
  5. class Document extends EventEmitter
  6. @getDocument: (ide, doc_id) ->
  7. @openDocs ||= {}
  8. if !@openDocs[doc_id]?
  9. sl_console.log "[getDocument] Creating new document instance for #{doc_id}"
  10. @openDocs[doc_id] = new Document(ide, doc_id)
  11. else
  12. sl_console.log "[getDocument] Returning existing document instance for #{doc_id}"
  13. return @openDocs[doc_id]
  14. @hasUnsavedChanges: () ->
  15. for doc_id, doc of (@openDocs or {})
  16. return true if doc.hasBufferedOps()
  17. return false
  18. @flushAll: () ->
  19. for doc_id, doc of @openDocs
  20. doc.flush()
  21. constructor: (@ide, @doc_id) ->
  22. @connected = @ide.socket.socket.connected
  23. @joined = false
  24. @wantToBeJoined = false
  25. @_checkConsistency = _.bind(@_checkConsistency, @)
  26. @inconsistentCount = 0
  27. @_bindToEditorEvents()
  28. @_bindToSocketEvents()
  29. attachToAce: (@ace) ->
  30. @doc?.attachToAce(@ace)
  31. editorDoc = @ace.getSession().getDocument()
  32. editorDoc.on "change", @_checkConsistency
  33. detachFromAce: () ->
  34. @doc?.detachFromAce()
  35. editorDoc = @ace?.getSession().getDocument()
  36. editorDoc?.off "change", @_checkConsistency
  37. @ide.$scope.$emit 'document:closed', @doc
  38. _checkConsistency: () ->
  39. # We've been seeing a lot of errors when I think there shouldn't be
  40. # any, which may be related to this check happening before the change is
  41. # applied. If we use a timeout, hopefully we can reduce this.
  42. setTimeout () =>
  43. editorValue = @ace?.getValue()
  44. sharejsValue = @doc?.getSnapshot()
  45. if editorValue != sharejsValue
  46. @inconsistentCount++
  47. else
  48. @inconsistentCount = 0
  49. if @inconsistentCount >= 3
  50. @_onError new Error("Editor text does not match server text")
  51. , 0
  52. getSnapshot: () ->
  53. @doc?.getSnapshot()
  54. getType: () ->
  55. @doc?.getType()
  56. getInflightOp: () ->
  57. @doc?.getInflightOp()
  58. getPendingOp: () ->
  59. @doc?.getPendingOp()
  60. hasBufferedOps: () ->
  61. @doc?.hasBufferedOps()
  62. _bindToSocketEvents: () ->
  63. @_onUpdateAppliedHandler = (update) => @_onUpdateApplied(update)
  64. @ide.socket.on "otUpdateApplied", @_onUpdateAppliedHandler
  65. @_onErrorHandler = (error, update) => @_onError(error, update)
  66. @ide.socket.on "otUpdateError", @_onErrorHandler
  67. @_onDisconnectHandler = (error) => @_onDisconnect(error)
  68. @ide.socket.on "disconnect", @_onDisconnectHandler
  69. _bindToEditorEvents: () ->
  70. onReconnectHandler = (update) =>
  71. @_onReconnect(update)
  72. @_unsubscribeReconnectHandler = @ide.$scope.$on "project:joined", onReconnectHandler
  73. _unBindFromEditorEvents: () ->
  74. @_unsubscribeReconnectHandler()
  75. _unBindFromSocketEvents: () ->
  76. @ide.socket.removeListener "otUpdateApplied", @_onUpdateAppliedHandler
  77. @ide.socket.removeListener "otUpdateError", @_onErrorHandler
  78. @ide.socket.removeListener "disconnect", @_onDisconnectHandler
  79. leaveAndCleanUp: () ->
  80. @leave (error) =>
  81. @_cleanUp()
  82. join: (callback = (error) ->) ->
  83. @wantToBeJoined = true
  84. @_cancelLeave()
  85. if @connected
  86. return @_joinDoc callback
  87. else
  88. @_joinCallbacks ||= []
  89. @_joinCallbacks.push callback
  90. leave: (callback = (error) ->) ->
  91. @wantToBeJoined = false
  92. @_cancelJoin()
  93. if (@doc? and @doc.hasBufferedOps())
  94. sl_console.log "[leave] Doc has buffered ops, pushing callback for later"
  95. @_leaveCallbacks ||= []
  96. @_leaveCallbacks.push callback
  97. else if !@connected
  98. sl_console.log "[leave] Not connected, returning now"
  99. callback()
  100. else
  101. sl_console.log "[leave] Leaving now"
  102. @_leaveDoc(callback)
  103. flush: () ->
  104. @doc?.flushPendingOps()
  105. chaosMonkey: (line = 0, char = "a") ->
  106. orig = char
  107. copy = null
  108. pos = 0
  109. timer = () =>
  110. unless copy? and copy.length
  111. copy = orig.slice() + ' ' + new Date() + '\n'
  112. line += if Math.random() > 0.1 then 1 else -2
  113. line = 0 if line < 0
  114. pos = 0
  115. char = copy[0]
  116. copy = copy.slice(1)
  117. @ace.session.insert({row: line, column: pos}, char)
  118. pos += 1
  119. @_cm = setTimeout timer, 100 + if Math.random() < 0.1 then 1000 else 0
  120. @_cm = timer()
  121. clearChaosMonkey: () ->
  122. clearTimeout @_cm
  123. pollSavedStatus: () ->
  124. # returns false if doc has ops waiting to be acknowledged or
  125. # sent that haven't changed since the last time we checked.
  126. # Otherwise returns true.
  127. inflightOp = @getInflightOp()
  128. pendingOp = @getPendingOp()
  129. if !inflightOp? and !pendingOp?
  130. # there's nothing going on
  131. saved = true
  132. sl_console.log "[pollSavedStatus] no inflight or pending ops"
  133. else if inflightOp? and inflightOp == @oldInflightOp
  134. # The same inflight op has been sitting unacked since we
  135. # last checked.
  136. saved = false
  137. sl_console.log "[pollSavedStatus] inflight op is same as before"
  138. else
  139. saved = true
  140. sl_console.log "[pollSavedStatus] assuming saved (inflightOp?: #{inflightOp?}, pendingOp?: #{pendingOp?})"
  141. @oldInflightOp = inflightOp
  142. return saved
  143. _cancelLeave: () ->
  144. if @_leaveCallbacks?
  145. delete @_leaveCallbacks
  146. _cancelJoin: () ->
  147. if @_joinCallbacks?
  148. delete @_joinCallbacks
  149. _onUpdateApplied: (update) ->
  150. @ide.pushEvent "received-update",
  151. doc_id: @doc_id
  152. remote_doc_id: update?.doc
  153. wantToBeJoined: @wantToBeJoined
  154. update: update
  155. if window.disconnectOnAck? and Math.random() < window.disconnectOnAck
  156. sl_console.log "Disconnecting on ack", update
  157. window._ide.socket.socket.disconnect()
  158. # Pretend we never received the ack
  159. return
  160. if window.dropAcks? and Math.random() < window.dropAcks
  161. if !update.op? # Only drop our own acks, not collaborator updates
  162. sl_console.log "Simulating a lost ack", update
  163. return
  164. if update?.doc == @doc_id and @doc?
  165. @doc.processUpdateFromServer update
  166. if !@wantToBeJoined
  167. @leave()
  168. _onDisconnect: () ->
  169. sl_console.log '[onDisconnect] disconnecting'
  170. @connected = false
  171. @joined = false
  172. @doc?.updateConnectionState "disconnected"
  173. _onReconnect: () ->
  174. sl_console.log "[onReconnect] reconnected (joined project)"
  175. @ide.pushEvent "reconnected:afterJoinProject"
  176. @connected = true
  177. if @wantToBeJoined or @doc?.hasBufferedOps()
  178. sl_console.log "[onReconnect] Rejoining (wantToBeJoined: #{@wantToBeJoined} OR hasBufferedOps: #{@doc?.hasBufferedOps()})"
  179. @_joinDoc (error) =>
  180. return @_onError(error) if error?
  181. @doc.updateConnectionState "ok"
  182. @doc.flushPendingOps()
  183. @_callJoinCallbacks()
  184. _callJoinCallbacks: () ->
  185. for callback in @_joinCallbacks or []
  186. callback()
  187. delete @_joinCallbacks
  188. _joinDoc: (callback = (error) ->) ->
  189. if @doc?
  190. @ide.socket.emit 'joinDoc', @doc_id, @doc.getVersion(), (error, docLines, version, updates) =>
  191. return callback(error) if error?
  192. @joined = true
  193. @doc.catchUp( updates )
  194. callback()
  195. else
  196. @ide.socket.emit 'joinDoc', @doc_id, (error, docLines, version) =>
  197. return callback(error) if error?
  198. @joined = true
  199. @doc = new ShareJsDoc @doc_id, docLines, version, @ide.socket
  200. @_bindToShareJsDocEvents()
  201. callback()
  202. _leaveDoc: (callback = (error) ->) ->
  203. sl_console.log '[_leaveDoc] Sending leaveDoc request'
  204. @ide.socket.emit 'leaveDoc', @doc_id, (error) =>
  205. return callback(error) if error?
  206. @joined = false
  207. for callback in @_leaveCallbacks or []
  208. sl_console.log '[_leaveDoc] Calling buffered callback', callback
  209. callback(error)
  210. delete @_leaveCallbacks
  211. callback(error)
  212. _cleanUp: () ->
  213. if Document.openDocs[@doc_id] == @
  214. sl_console.log "[_cleanUp] Removing self (#{@doc_id}) from in openDocs"
  215. delete Document.openDocs[@doc_id]
  216. else
  217. # It's possible that this instance has error, and the doc has been reloaded.
  218. # This creates a new instance in Document.openDoc with the same id. We shouldn't
  219. # clear it because it's not this instance.
  220. sl_console.log "[_cleanUp] New instance of (#{@doc_id}) created. Not removing"
  221. @_unBindFromEditorEvents()
  222. @_unBindFromSocketEvents()
  223. _bindToShareJsDocEvents: () ->
  224. @doc.on "error", (error, meta) => @_onError error, meta
  225. @doc.on "externalUpdate", (update) =>
  226. @ide.pushEvent "externalUpdate",
  227. doc_id: @doc_id
  228. @trigger "externalUpdate", update
  229. @doc.on "remoteop", () =>
  230. @ide.pushEvent "remoteop",
  231. doc_id: @doc_id
  232. @trigger "remoteop"
  233. @doc.on "op:sent", (op) =>
  234. @ide.pushEvent "op:sent",
  235. doc_id: @doc_id
  236. op: op
  237. @trigger "op:sent"
  238. @doc.on "op:acknowledged", (op) =>
  239. @ide.pushEvent "op:acknowledged",
  240. doc_id: @doc_id
  241. op: op
  242. @trigger "op:acknowledged"
  243. @doc.on "op:timeout", (op) =>
  244. @ide.pushEvent "op:timeout",
  245. doc_id: @doc_id
  246. op: op
  247. @trigger "op:timeout"
  248. @_onError new Error("op timed out"), {op: op}
  249. @doc.on "flush", (inflightOp, pendingOp, version) =>
  250. @ide.pushEvent "flush",
  251. doc_id: @doc_id,
  252. inflightOp: inflightOp,
  253. pendingOp: pendingOp
  254. v: version
  255. _onError: (error, meta = {}) ->
  256. meta.doc_id = @doc_id
  257. console.error "ShareJS error", error, meta
  258. ga?('send', 'event', 'error', "shareJsError", "#{error.message} - #{@ide.socket.socket.transport.name}" )
  259. @doc?.clearInflightAndPendingOps()
  260. @trigger "error", error, meta
  261. # The clean up should run after the error is triggered because the error triggers a
  262. # disconnect. If we run the clean up first, we remove our event handlers and miss
  263. # the disconnect event, which means we try to leaveDoc when the connection comes back.
  264. # This could intefere with the new connection of a new instance of this document.
  265. @_cleanUp()