EditorWatchdogManager.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. EditorWatchdogManager is used for end-to-end checks of edits.
  3. The editor UI is backed by Ace and CodeMirrors, which in turn are connected
  4. to ShareJs documents in the frontend.
  5. Edits propagate from the editor to ShareJs and are send through socket.io
  6. and real-time to document-updater.
  7. In document-updater edits are integrated into the document history and
  8. a confirmation/rejection is sent back to the frontend.
  9. Along the way things can get lost.
  10. We have certain safe-guards in place, but are still getting occasional
  11. reports of lost edits.
  12. EditorWatchdogManager is implementing the basis for end-to-end checks on
  13. two levels:
  14. - local/ShareJsDoc: edits that pass-by a ShareJs document shall get
  15. acknowledged eventually.
  16. - global: any edits made in the editor shall get acknowledged eventually,
  17. independent for which ShareJs document (potentially none) sees it.
  18. How does this work?
  19. ===================
  20. The global check is using a global EditorWatchdogManager that is available
  21. via the angular factory 'ide'.
  22. Local/ShareJsDoc level checks will connect to the global instance.
  23. Each EditorWatchdogManager keeps track of the oldest un-acknowledged edit.
  24. When ever a ShareJs document receives an acknowledgement event, a local
  25. EditorWatchdogManager will see it and also notify the global instance about
  26. it.
  27. The next edit cycle will clear the oldest un-acknowledged timestamp in case
  28. a new ack has arrived, otherwise it will bark loud! via the timeout handler.
  29. Scenarios
  30. =========
  31. - User opens the CodeMirror editor
  32. - attach global check to new CM instance
  33. - detach Ace from the local EditorWatchdogManager
  34. - when the frontend attaches the CM instance to ShareJs, we also
  35. attach it to the local EditorWatchdogManager
  36. - the internal attach process writes the document content to the editor,
  37. which in turn emits 'change' events. These event need to be excluded
  38. from the watchdog. EditorWatchdogManager.ignoreEditsFor takes care
  39. of that.
  40. - User opens the Ace editor (again)
  41. - (attach global check to the Ace editor, only one copy of Ace is around)
  42. - detach local EditorWatchdogManager from CM
  43. - likewise with CM, attach Ace to the local EditorWatchdogManager
  44. - User makes an edit
  45. - the editor will emit a 'change' event
  46. - the global EditorWatchdogManager will process it first
  47. - the local EditorWatchdogManager will process it next
  48. - Document-updater confirms an edit
  49. - the local EditorWatchdogManager will process it first, it passes it on to
  50. - the global EditorWatchdogManager will process it next
  51. Time
  52. ====
  53. The delay between edits and acks is measured using a monotonic clock:
  54. `performance.now()`.
  55. It is agnostic to system clock changes in either direction and timezone
  56. changes do not affect it as well.
  57. Roughly speaking, it is initialized with `0` when the `window` context is
  58. created, before our JS app boots.
  59. As per canIUse.com and MDN `performance.now()` is available to all supported
  60. Browsers, including IE11.
  61. See also: https://caniuse.com/?search=performance.now
  62. See also: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
  63. */
  64. // TIMEOUT specifies the timeout for edits into a single ShareJsDoc.
  65. const TIMEOUT = 60 * 1000
  66. // GLOBAL_TIMEOUT specifies the timeout for edits into any ShareJSDoc.
  67. const GLOBAL_TIMEOUT = TIMEOUT
  68. // REPORT_EVERY specifies how often we send events/report errors.
  69. const REPORT_EVERY = 60 * 1000
  70. const SCOPE_LOCAL = 'ShareJsDoc'
  71. const SCOPE_GLOBAL = 'global'
  72. class Reporter {
  73. constructor(onTimeoutHandler) {
  74. this._onTimeoutHandler = onTimeoutHandler
  75. this._lastReport = undefined
  76. this._queue = []
  77. }
  78. _getMetaPreferLocal() {
  79. for (const meta of this._queue) {
  80. if (meta.scope === SCOPE_LOCAL) {
  81. return meta
  82. }
  83. }
  84. return this._queue.pop()
  85. }
  86. onTimeout(meta) {
  87. // Collect all 'meta's for this update.
  88. // global arrive before local ones, but we are eager to report local ones.
  89. this._queue.push(meta)
  90. setTimeout(() => {
  91. // Another handler processed the 'meta' entry already
  92. if (!this._queue.length) return
  93. const maybeLocalMeta = this._getMetaPreferLocal()
  94. // Discard other, newly arrived 'meta's
  95. this._queue.length = 0
  96. const now = Date.now()
  97. // Do not flood the server with losing-edits events
  98. const reportedRecently = now - this._lastReport < REPORT_EVERY
  99. if (!reportedRecently) {
  100. this._lastReport = now
  101. this._onTimeoutHandler(maybeLocalMeta)
  102. }
  103. })
  104. }
  105. }
  106. export default class EditorWatchdogManager {
  107. constructor({ parent, onTimeoutHandler }) {
  108. this.scope = parent ? SCOPE_LOCAL : SCOPE_GLOBAL
  109. this.timeout = parent ? TIMEOUT : GLOBAL_TIMEOUT
  110. this.parent = parent
  111. if (parent) {
  112. this.reporter = parent.reporter
  113. } else {
  114. this.reporter = new Reporter(onTimeoutHandler)
  115. }
  116. this.lastAck = null
  117. this.lastUnackedEdit = null
  118. }
  119. onAck() {
  120. this.lastAck = performance.now()
  121. // bubble up to globalEditorWatchdogManager
  122. if (this.parent) this.parent.onAck()
  123. }
  124. onEdit() {
  125. // Use timestamps to track the high-water mark of unacked edits
  126. const now = performance.now()
  127. // Discard the last unacked edit if there are now newer acks
  128. if (this.lastAck > this.lastUnackedEdit) {
  129. this.lastUnackedEdit = null
  130. }
  131. // Start tracking for this keypress if we aren't already tracking an
  132. // unacked edit
  133. if (!this.lastUnackedEdit) {
  134. this.lastUnackedEdit = now
  135. }
  136. // Report an error if the last tracked edit hasn't been cleared by an
  137. // ack from the server after a long time
  138. const delay = now - this.lastUnackedEdit
  139. if (delay > this.timeout) {
  140. const timeOrigin = Date.now() - now
  141. const scope = this.scope
  142. const lastAck = new Date(this.lastAck ? timeOrigin + this.lastAck : 0)
  143. const lastUnackedEdit = new Date(timeOrigin + this.lastUnackedEdit)
  144. const meta = { scope, delay, lastAck, lastUnackedEdit }
  145. this._log('timedOut', meta)
  146. this.reporter.onTimeout(meta)
  147. }
  148. }
  149. attachToEditor(editorName, editor) {
  150. let onChange
  151. if (editorName === 'CM6') {
  152. // Code Mirror 6
  153. this._log('attach to editor', editorName)
  154. onChange = (_editor, changeDescription) => {
  155. if (changeDescription.origin === 'remote') return
  156. if (!(changeDescription.removed || changeDescription.inserted)) return
  157. this.onEdit()
  158. }
  159. editor.on('change', onChange)
  160. const detachFromEditor = () => {
  161. this._log('detach from editor', editorName)
  162. editor.off('change', onChange)
  163. }
  164. return detachFromEditor
  165. }
  166. if (editorName === 'CM') {
  167. // CM is passing the CM instance as first parameter, then the change.
  168. onChange = (editor, change) => {
  169. // Ignore remote changes.
  170. if (change.origin === 'remote') return
  171. // sharejs only looks at DEL or INSERT change events.
  172. // NOTE: Keep in sync with sharejs.
  173. if (!(change.removed || change.text)) return
  174. this.onEdit()
  175. }
  176. } else {
  177. // ACE is passing the change object as first parameter.
  178. onChange = change => {
  179. // Ignore remote changes.
  180. if (change.origin === 'remote') return
  181. // sharejs only looks at DEL or INSERT change events.
  182. // NOTE: Keep in sync with sharejs.
  183. if (!(change.action === 'remove' || change.action === 'insert')) return
  184. this.onEdit()
  185. }
  186. }
  187. this._log('attach to editor', editorName)
  188. editor.on('change', onChange)
  189. const detachFromEditor = () => {
  190. this._log('detach from editor', editorName)
  191. editor.off('change', onChange)
  192. }
  193. return detachFromEditor
  194. }
  195. _log() {
  196. sl_console.log(`[EditorWatchdogManager] ${this.scope}:`, ...arguments)
  197. }
  198. }