share-js-doc.ts 15 KB

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