share-js-doc.ts 14 KB

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