share-js-doc.ts 14 KB

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