share-js-doc.ts 14 KB

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