share-js-doc.ts 14 KB

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