share-js-doc.ts 14 KB

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