share-js-doc.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /* eslint-disable camelcase */
  2. // Migrated from services/web/frontend/js/ide/editor/ShareJsDoc.js
  3. import EventEmitter from '../../../utils/EventEmitter'
  4. import { Doc } from '@/vendor/libs/sharejs'
  5. import { Socket } from '@/features/ide-react/connection/types/socket'
  6. import { debugConsole } from '@/utils/debugging'
  7. import { decodeUtf8 } from '@/utils/decode-utf8'
  8. import { IdeEventEmitter } from '@/features/ide-react/create-ide-event-emitter'
  9. import EditorWatchdogManager from '@/features/ide-react/connection/editor-watchdog-manager'
  10. import {
  11. Message,
  12. ShareJsConnectionState,
  13. ShareJsOperation,
  14. TrackChangesIdSeeds,
  15. } from '@/features/ide-react/editor/types/document'
  16. import { EditorFacade } from '@/features/source-editor/extensions/realtime'
  17. import { recordDocumentFirstChangeEvent } from '@/features/event-tracking/document-first-change-event'
  18. import getMeta from '@/utils/meta'
  19. // All times below are in milliseconds
  20. const SINGLE_USER_FLUSH_DELAY = 2000
  21. const MULTI_USER_FLUSH_DELAY = 500
  22. const INFLIGHT_OP_TIMEOUT = 5000 // Retry sending ops after 5 seconds without an ack
  23. const WAIT_FOR_CONNECTION_TIMEOUT = 500
  24. const FATAL_OP_TIMEOUT = 30000
  25. type Update = Record<string, any>
  26. type Connection = {
  27. send: (update: Update) => void
  28. state: ShareJsConnectionState
  29. id: string
  30. }
  31. export class ShareJsDoc extends EventEmitter {
  32. type: string
  33. track_changes = false
  34. track_changes_id_seeds: TrackChangesIdSeeds | null = null
  35. connection: Connection
  36. // @ts-ignore
  37. _doc: Doc
  38. private editorWatchdogManager: EditorWatchdogManager
  39. private lastAcked: Date | null = null
  40. private queuedMessageTimer: number | null = null
  41. private queuedMessages: Message[] = []
  42. private detachEditorWatchdogManager: (() => void) | null = null
  43. private _timeoutTimer: number | null = null
  44. constructor(
  45. readonly doc_id: string,
  46. docLines: string[],
  47. version: number,
  48. readonly socket: Socket,
  49. private readonly globalEditorWatchdogManager: EditorWatchdogManager,
  50. private readonly eventEmitter: IdeEventEmitter
  51. ) {
  52. super()
  53. this.type = 'text'
  54. // Decode any binary bits of data
  55. const snapshot = docLines.map(line => decodeUtf8(line)).join('\n')
  56. this.connection = {
  57. send: (update: Update) => {
  58. this.startInflightOpTimeout(update)
  59. if (this.track_changes && this.track_changes_id_seeds) {
  60. if (update.meta == null) {
  61. update.meta = {}
  62. }
  63. update.meta.tc = this.track_changes_id_seeds.inflight
  64. }
  65. return this.socket.emit(
  66. 'applyOtUpdate',
  67. this.doc_id,
  68. update,
  69. (error: Error) => {
  70. if (error != null) {
  71. this.handleError(error)
  72. }
  73. }
  74. )
  75. },
  76. state: 'ok',
  77. id: this.socket.publicId,
  78. }
  79. this._doc = new Doc(this.connection, this.doc_id, {
  80. type: this.type,
  81. })
  82. this._doc.setFlushDelay(SINGLE_USER_FLUSH_DELAY)
  83. this._doc.on('change', (...args: any[]) => {
  84. return this.trigger('change', ...args)
  85. })
  86. this.editorWatchdogManager = new EditorWatchdogManager({
  87. parent: globalEditorWatchdogManager,
  88. })
  89. this._doc.on('acknowledge', () => {
  90. this.lastAcked = new Date() // note time of last ack from server for an op we sent
  91. this.editorWatchdogManager.onAck() // keep track of last ack globally
  92. return this.trigger('acknowledge')
  93. })
  94. this._doc.on('remoteop', (...args: any[]) => {
  95. // As soon as we're working with a collaborator, start sending
  96. // ops more frequently for low latency.
  97. this._doc.setFlushDelay(MULTI_USER_FLUSH_DELAY)
  98. return this.trigger('remoteop', ...args)
  99. })
  100. this._doc.on('flipped_pending_to_inflight', () => {
  101. return this.trigger('flipped_pending_to_inflight')
  102. })
  103. this._doc.on('saved', () => {
  104. return this.trigger('saved')
  105. })
  106. this._doc.on('error', (e: Error) => {
  107. return this.handleError(e)
  108. })
  109. this.bindToDocChanges(this._doc)
  110. this.processUpdateFromServer({
  111. open: true,
  112. v: version,
  113. snapshot,
  114. })
  115. this.removeCarriageReturnCharFromShareJsDoc()
  116. }
  117. private removeCarriageReturnCharFromShareJsDoc() {
  118. const doc = this._doc
  119. if (doc.snapshot.indexOf('\r') === -1) {
  120. return
  121. }
  122. let nextPos
  123. while ((nextPos = doc.snapshot.indexOf('\r')) !== -1) {
  124. debugConsole.log('[ShareJsDoc] remove-carriage-return-char', nextPos)
  125. doc.del(nextPos, 1)
  126. }
  127. }
  128. submitOp(op: ShareJsOperation) {
  129. this._doc.submitOp(op)
  130. }
  131. // The following code puts out of order messages into a queue
  132. // so that they can be processed in order. This is a workaround
  133. // for messages being delayed by redis cluster.
  134. // FIXME: REMOVE THIS WHEN REDIS PUBSUB IS SENDING MESSAGES IN ORDER
  135. private isAheadOfExpectedVersion(message: Message) {
  136. return this._doc.version > 0 && message.v > this._doc.version
  137. }
  138. private pushOntoQueue(message: Message) {
  139. debugConsole.log(`[processUpdate] push onto queue ${message.v}`)
  140. // set a timer so that we never leave messages in the queue indefinitely
  141. if (!this.queuedMessageTimer) {
  142. this.queuedMessageTimer = window.setTimeout(() => {
  143. debugConsole.log(`[processUpdate] queue timeout fired for ${message.v}`)
  144. // force the message to be processed after the timeout,
  145. // it will cause an error if the missing update has not arrived
  146. this.processUpdateFromServer(message)
  147. }, INFLIGHT_OP_TIMEOUT)
  148. }
  149. this.queuedMessages.push(message)
  150. // keep the queue in order, lowest version first
  151. this.queuedMessages.sort(function (a, b) {
  152. return a.v - b.v
  153. })
  154. }
  155. private clearQueue() {
  156. this.queuedMessages = []
  157. }
  158. private processQueue() {
  159. if (this.queuedMessages.length > 0) {
  160. const nextAvailableVersion = this.queuedMessages[0].v
  161. if (nextAvailableVersion > this._doc.version) {
  162. // there are updates we still can't apply yet
  163. } else {
  164. // there's a version we can accept on the queue, apply it
  165. debugConsole.log(
  166. `[processUpdate] taken from queue ${nextAvailableVersion}`
  167. )
  168. const message = this.queuedMessages.shift()
  169. if (message) {
  170. this.processUpdateFromServerInOrder(message)
  171. }
  172. // clear the pending timer if the queue has now been cleared
  173. if (this.queuedMessages.length === 0 && this.queuedMessageTimer) {
  174. debugConsole.log('[processUpdate] queue is empty, cleared timeout')
  175. window.clearTimeout(this.queuedMessageTimer)
  176. this.queuedMessageTimer = null
  177. }
  178. }
  179. }
  180. }
  181. // FIXME: This is the new method which reorders incoming updates if needed
  182. // called from document.ts
  183. processUpdateFromServerInOrder(message: Message) {
  184. // Is this update ahead of the next expected update?
  185. // If so, put it on a queue to be handled later.
  186. if (this.isAheadOfExpectedVersion(message)) {
  187. this.pushOntoQueue(message)
  188. return // defer processing this update for now
  189. }
  190. const error = this.processUpdateFromServer(message)
  191. if (
  192. error instanceof Error &&
  193. error.message === 'Invalid version from server'
  194. ) {
  195. // if there was an error, abandon the queued updates ahead of this one
  196. this.clearQueue()
  197. return
  198. }
  199. // Do we have any messages queued up?
  200. // find the next message if available
  201. this.processQueue()
  202. }
  203. // FIXME: This is the original method. Switch back to this when redis
  204. // issues are resolved.
  205. processUpdateFromServer(message: Message) {
  206. try {
  207. this._doc._onMessage(message)
  208. } catch (error) {
  209. // Version mismatches are thrown as errors
  210. debugConsole.log(error)
  211. this.handleError(error)
  212. return error // return the error for queue handling
  213. }
  214. if (message.meta?.type === 'external') {
  215. return this.trigger('externalUpdate', message)
  216. }
  217. }
  218. catchUp(updates: Message[]) {
  219. return updates.map(update => {
  220. update.v = this._doc.version
  221. update.doc = this.doc_id
  222. return this.processUpdateFromServer(update)
  223. })
  224. }
  225. getSnapshot() {
  226. return this._doc.snapshot as string | undefined
  227. }
  228. getVersion() {
  229. return this._doc.version
  230. }
  231. getTimeSinceLastServerActivity() {
  232. return Math.floor(performance.now() - this._doc.lastServerActivity)
  233. }
  234. getType() {
  235. return this.type
  236. }
  237. clearInflightAndPendingOps() {
  238. this.clearFatalTimeoutTimer()
  239. this._doc.inflightOp = null
  240. this._doc.inflightCallbacks = []
  241. this._doc.pendingOp = null
  242. return (this._doc.pendingCallbacks = [])
  243. }
  244. flushPendingOps() {
  245. // This will flush any ops that are pending.
  246. // If there is an inflight op it will do nothing.
  247. return this._doc.flush()
  248. }
  249. updateConnectionState(state: ShareJsConnectionState) {
  250. debugConsole.log(`[updateConnectionState] Setting state to ${state}`)
  251. this.connection.state = state
  252. this.connection.id = this.socket.publicId
  253. this._doc.autoOpen = false
  254. this._doc._connectionStateChanged(state)
  255. return (this.lastAcked = null) // reset the last ack time when connection changes
  256. }
  257. hasBufferedOps() {
  258. return this._doc.inflightOp != null || this._doc.pendingOp != null
  259. }
  260. getInflightOp() {
  261. return this._doc.inflightOp
  262. }
  263. getPendingOp() {
  264. return this._doc.pendingOp
  265. }
  266. getRecentAck() {
  267. // check if we have received an ack recently (within a factor of two of the single user flush delay)
  268. return (
  269. this.lastAcked !== null &&
  270. Date.now() - this.lastAcked.getTime() < 2 * SINGLE_USER_FLUSH_DELAY
  271. )
  272. }
  273. private attachEditorWatchdogManager(editor: EditorFacade) {
  274. // end-to-end check for edits -> acks, for this very ShareJsdoc
  275. // This will catch a broken connection and missing UX-blocker for the
  276. // user, allowing them to keep editing.
  277. this.detachEditorWatchdogManager =
  278. this.editorWatchdogManager.attachToEditor(editor)
  279. }
  280. private attachToEditor(editor: EditorFacade, attachToShareJs: () => void) {
  281. this.attachEditorWatchdogManager(editor)
  282. attachToShareJs()
  283. }
  284. private maybeDetachEditorWatchdogManager() {
  285. // a failed attach attempt may lead to a missing cleanup handler
  286. if (this.detachEditorWatchdogManager) {
  287. this.detachEditorWatchdogManager()
  288. this.detachEditorWatchdogManager = null
  289. }
  290. }
  291. attachToCM6(cm6: EditorFacade) {
  292. this.attachToEditor(cm6, () => {
  293. cm6.attachShareJs(this._doc, getMeta('ol-maxDocLength'))
  294. })
  295. }
  296. detachFromCM6() {
  297. this.maybeDetachEditorWatchdogManager()
  298. if (this._doc.detach_cm6) {
  299. this._doc.detach_cm6()
  300. }
  301. }
  302. private startInflightOpTimeout(update: Update) {
  303. this.startFatalTimeoutTimer(update)
  304. const retryOp = () => {
  305. // Only send the update again if inflightOp is still populated
  306. // This can be cleared when hard reloading the document in which
  307. // case we don't want to keep trying to send it.
  308. debugConsole.log('[inflightOpTimeout] Trying op again')
  309. if (this._doc.inflightOp != null) {
  310. // When there is a socket.io disconnect, @_doc.inflightSubmittedIds
  311. // is updated with the socket.io client id of the current op in flight
  312. // (meta.source of the op).
  313. // @connection.id is the client id of the current socket.io session.
  314. // So we need both depending on whether the op was submitted before
  315. // one or more disconnects, or if it was submitted during the current session.
  316. update.dupIfSource = [
  317. this.connection.id,
  318. ...Array.from(this._doc.inflightSubmittedIds),
  319. ]
  320. // We must be joined to a project for applyOtUpdate to work on the real-time
  321. // service, so don't send an op if we're not. Connection state is set to 'ok'
  322. // when we've joined the project
  323. if (this.connection.state !== 'ok') {
  324. debugConsole.log(
  325. '[inflightOpTimeout] Not connected, retrying in 0.5s'
  326. )
  327. window.setTimeout(retryOp, WAIT_FOR_CONNECTION_TIMEOUT)
  328. } else {
  329. debugConsole.log('[inflightOpTimeout] Sending')
  330. return this.connection.send(update)
  331. }
  332. }
  333. }
  334. const timer = window.setTimeout(retryOp, INFLIGHT_OP_TIMEOUT)
  335. return this._doc.inflightCallbacks.push(() => {
  336. this.clearFatalTimeoutTimer()
  337. window.clearTimeout(timer)
  338. }) // 30 seconds
  339. }
  340. private startFatalTimeoutTimer(update: Update) {
  341. // If an op doesn't get acked within FATAL_OP_TIMEOUT, something has
  342. // gone unrecoverably wrong (the op will have been retried multiple times)
  343. if (this._timeoutTimer != null) {
  344. return
  345. }
  346. return (this._timeoutTimer = window.setTimeout(() => {
  347. this.clearFatalTimeoutTimer()
  348. return this.trigger('op:timeout', update)
  349. }, FATAL_OP_TIMEOUT))
  350. }
  351. private clearFatalTimeoutTimer() {
  352. if (this._timeoutTimer == null) {
  353. return
  354. }
  355. clearTimeout(this._timeoutTimer)
  356. return (this._timeoutTimer = null)
  357. }
  358. private handleError(error: unknown, meta = {}) {
  359. return this.trigger('error', error, meta)
  360. }
  361. // @ts-ignore
  362. private bindToDocChanges(doc: Doc) {
  363. const { submitOp } = doc
  364. doc.submitOp = (op: ShareJsOperation, callback?: () => void) => {
  365. recordDocumentFirstChangeEvent()
  366. this.trigger('op:sent', op)
  367. doc.pendingCallbacks.push(() => {
  368. return this.trigger('op:acknowledged', op)
  369. })
  370. return submitOp.call(doc, op, callback)
  371. }
  372. const { flush } = doc
  373. doc.flush = () => {
  374. this.trigger('flush', doc.inflightOp, doc.pendingOp, doc.version)
  375. return flush.call(doc)
  376. }
  377. }
  378. }