share-js-doc.ts 15 KB

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