share-js-doc.ts 17 KB

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