share-js-doc.ts 14 KB

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