document-container.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /* eslint-disable camelcase */
  2. // Migrated from services/web/frontend/js/ide/editor/Document.js
  3. import RangesTracker from '@overleaf/ranges-tracker'
  4. import { ShareJsDoc } from './share-js-doc'
  5. import { debugConsole } from '@/utils/debugging'
  6. import { Socket } from '@/features/ide-react/connection/types/socket'
  7. import { IdeEventEmitter } from '@/features/ide-react/create-ide-event-emitter'
  8. import { EditorFacade } from '@/features/source-editor/extensions/realtime'
  9. import EditorWatchdogManager from '@/features/ide-react/connection/editor-watchdog-manager'
  10. import EventEmitter from '@/utils/EventEmitter'
  11. import {
  12. AnyOperation,
  13. Change,
  14. CommentOperation,
  15. EditOperation,
  16. } from '../../../../../types/change'
  17. import {
  18. isCommentOperation,
  19. isDeleteOperation,
  20. isEditOperation,
  21. isInsertOperation,
  22. } from '@/utils/operations'
  23. import { decodeUtf8 } from '@/utils/decode-utf8'
  24. import {
  25. ShareJsOperation,
  26. TrackChangesIdSeeds,
  27. } from '@/features/ide-react/editor/types/document'
  28. import { ThreadId } from '../../../../../types/review-panel/review-panel'
  29. import getMeta from '@/utils/meta'
  30. const MAX_PENDING_OP_SIZE = 64
  31. type JoinCallback = (error?: Error) => void
  32. type LeaveCallback = JoinCallback
  33. type Update =
  34. | {
  35. v: number
  36. doc: string
  37. }
  38. | {
  39. v: number
  40. doc: string
  41. op: AnyOperation[]
  42. meta: {
  43. type?: string
  44. source: string
  45. user_id: string
  46. ts: number
  47. }
  48. hash?: string
  49. lastV?: number
  50. }
  51. type Message = {
  52. meta: {
  53. tc: string
  54. user_id: string
  55. }
  56. }
  57. type ErrorMetadata = Record<string, any>
  58. function getOpSize(op: AnyOperation) {
  59. if (isInsertOperation(op)) {
  60. return op.i.length
  61. }
  62. if (isDeleteOperation(op)) {
  63. return op.d.length
  64. }
  65. return 0
  66. }
  67. function getShareJsOpSize(shareJsOp: ShareJsOperation) {
  68. return shareJsOp.reduce((total, op) => total + getOpSize(op), 0)
  69. }
  70. // TODO: define these in RangesTracker
  71. type _RangesTracker = Omit<RangesTracker, 'changes' | 'comments'> & {
  72. changes: Change<EditOperation>[]
  73. comments: Change<CommentOperation>[]
  74. track_changes?: boolean
  75. }
  76. export type RangesTrackerWithResolvedThreadIds = _RangesTracker & {
  77. resolvedThreadIds: Record<ThreadId, boolean>
  78. }
  79. export class DocumentContainer extends EventEmitter {
  80. private connected: boolean
  81. private wantToBeJoined = false
  82. private chaosMonkeyTimer: number | null = null
  83. public track_changes_as: string | null = null
  84. private joinCallbacks: JoinCallback[] = []
  85. private leaveCallbacks: LeaveCallback[] = []
  86. doc?: ShareJsDoc
  87. cm6?: EditorFacade
  88. oldInflightOp?: ShareJsOperation
  89. ranges?: _RangesTracker | RangesTrackerWithResolvedThreadIds
  90. joined = false
  91. // This is set and read in useCodeMirrorScope
  92. docName = ''
  93. constructor(
  94. readonly doc_id: string,
  95. readonly socket: Socket,
  96. private readonly globalEditorWatchdogManager: EditorWatchdogManager,
  97. private readonly ideEventEmitter: IdeEventEmitter,
  98. private readonly detachDoc: (docId: string, doc: DocumentContainer) => void
  99. ) {
  100. super()
  101. this.connected = this.socket.socket.connected
  102. this.bindToEditorEvents()
  103. this.bindToSocketEvents()
  104. }
  105. attachToCM6(cm6: EditorFacade) {
  106. this.cm6 = cm6
  107. if (this.doc) {
  108. this.doc.attachToCM6(this.cm6)
  109. }
  110. this.cm6.on('change', this.checkConsistency)
  111. }
  112. detachFromCM6() {
  113. if (this.doc) {
  114. this.doc.detachFromCM6()
  115. }
  116. if (this.cm6) {
  117. this.cm6.off('change', this.checkConsistency)
  118. }
  119. delete this.cm6
  120. this.clearChaosMonkey()
  121. if (this.doc) {
  122. this.ideEventEmitter.emit('document:closed', this.doc)
  123. }
  124. }
  125. submitOp(...ops: AnyOperation[]) {
  126. this.doc?.submitOp(ops)
  127. }
  128. private checkConsistency = (editor: EditorFacade) => {
  129. // We've been seeing a lot of errors when I think there shouldn't be
  130. // any, which may be related to this check happening before the change is
  131. // applied. If we use a timeout, hopefully we can reduce this.
  132. window.setTimeout(() => {
  133. const editorValue = editor?.getValue()
  134. const sharejsValue = this.doc?.getSnapshot()
  135. if (editorValue !== sharejsValue) {
  136. return this.onError(
  137. new Error('Editor text does not match server text'),
  138. {},
  139. editorValue
  140. )
  141. }
  142. }, 0)
  143. }
  144. getSnapshot() {
  145. return this.doc?.getSnapshot()
  146. }
  147. getType() {
  148. return this.doc?.getType()
  149. }
  150. getInflightOp(): ShareJsOperation | undefined {
  151. return this.doc?.getInflightOp()
  152. }
  153. getPendingOp(): ShareJsOperation | undefined {
  154. return this.doc?.getPendingOp()
  155. }
  156. getRecentAck() {
  157. return this.doc?.getRecentAck()
  158. }
  159. getInflightOpCreatedAt() {
  160. return this.doc?.getInflightOpCreatedAt()
  161. }
  162. getPendingOpCreatedAt() {
  163. return this.doc?.getPendingOpCreatedAt()
  164. }
  165. hasBufferedOps() {
  166. return this.doc?.hasBufferedOps()
  167. }
  168. setTrackingChanges(track_changes: boolean) {
  169. if (this.doc) {
  170. this.doc.track_changes = track_changes
  171. }
  172. }
  173. getTrackingChanges() {
  174. return !!this.doc?.track_changes
  175. }
  176. setTrackChangesIdSeeds(id_seeds: TrackChangesIdSeeds) {
  177. if (this.doc) {
  178. this.doc.track_changes_id_seeds = id_seeds
  179. }
  180. }
  181. private onUpdateAppliedHandler = (update: any) => this.onUpdateApplied(update)
  182. private onErrorHandler = (error: Error, message: ErrorMetadata) => {
  183. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  184. // sure that message.doc_id exists.
  185. if (message.doc_id !== this.doc_id) {
  186. // This error is for another doc. Do not action it. We could open
  187. // a modal that has the wrong context on it.
  188. return
  189. }
  190. this.onError(error, message)
  191. }
  192. private onDisconnectHandler = () => this.onDisconnect()
  193. private bindToSocketEvents() {
  194. this.socket.on('otUpdateApplied', this.onUpdateAppliedHandler)
  195. this.socket.on('otUpdateError', this.onErrorHandler)
  196. return this.socket.on('disconnect', this.onDisconnectHandler)
  197. }
  198. private unBindFromSocketEvents() {
  199. this.socket.removeListener('otUpdateApplied', this.onUpdateAppliedHandler)
  200. this.socket.removeListener('otUpdateError', this.onErrorHandler)
  201. return this.socket.removeListener('disconnect', this.onDisconnectHandler)
  202. }
  203. private bindToEditorEvents() {
  204. this.ideEventEmitter.on('project:joined', this.onReconnect)
  205. }
  206. private unBindFromEditorEvents() {
  207. this.ideEventEmitter.off('project:joined', this.onReconnect)
  208. }
  209. leaveAndCleanUp(cb?: (error?: Error) => void) {
  210. return this.leave((error?: Error) => {
  211. this.cleanUp()
  212. if (cb) cb(error)
  213. })
  214. }
  215. leaveAndCleanUpPromise() {
  216. return new Promise<void>((resolve, reject) => {
  217. this.leaveAndCleanUp((error?: Error) => {
  218. if (error) {
  219. reject(error)
  220. } else {
  221. resolve()
  222. }
  223. })
  224. })
  225. }
  226. join(callback?: JoinCallback) {
  227. this.wantToBeJoined = true
  228. this.cancelLeave()
  229. if (this.connected) {
  230. this.joinDoc(callback)
  231. } else if (callback) {
  232. this.joinCallbacks.push(callback)
  233. }
  234. }
  235. leave(callback?: LeaveCallback) {
  236. this.flush() // force an immediate flush when leaving document
  237. this.wantToBeJoined = false
  238. this.cancelJoin()
  239. if (this.doc?.hasBufferedOps()) {
  240. debugConsole.log(
  241. '[leave] Doc has buffered ops, pushing callback for later'
  242. )
  243. if (callback) {
  244. this.leaveCallbacks.push(callback)
  245. }
  246. } else if (!this.connected) {
  247. debugConsole.log('[leave] Not connected, returning now')
  248. callback?.()
  249. } else {
  250. debugConsole.log('[leave] Leaving now')
  251. this.leaveDoc(callback)
  252. }
  253. }
  254. flush() {
  255. return this.doc?.flushPendingOps()
  256. }
  257. chaosMonkey(line = 0, char = 'a') {
  258. const orig = char
  259. let copy: string | null = null
  260. let pos = 0
  261. const timer = () => {
  262. if (copy == null || !copy.length) {
  263. copy = orig.slice() + ' ' + new Date() + '\n'
  264. line += Math.random() > 0.1 ? 1 : -2
  265. if (line < 0) {
  266. line = 0
  267. }
  268. pos = 0
  269. }
  270. char = copy[0]
  271. copy = copy.slice(1)
  272. if (this.cm6) {
  273. this.cm6.view.dispatch({
  274. changes: {
  275. from: Math.min(pos, this.cm6.view.state.doc.length),
  276. insert: char,
  277. },
  278. })
  279. }
  280. pos += 1
  281. this.chaosMonkeyTimer = window.setTimeout(
  282. timer,
  283. 100 + (Math.random() < 0.1 ? 1000 : 0)
  284. )
  285. }
  286. timer()
  287. }
  288. clearChaosMonkey() {
  289. const timer = this.chaosMonkeyTimer
  290. if (timer) {
  291. this.chaosMonkeyTimer = null
  292. window.clearTimeout(timer)
  293. }
  294. }
  295. pollSavedStatus() {
  296. // returns false if doc has ops waiting to be acknowledged or
  297. // sent that haven't changed since the last time we checked.
  298. // Otherwise returns true.
  299. let saved
  300. const inflightOp = this.getInflightOp()
  301. const pendingOp = this.getPendingOp()
  302. const recentAck = this.getRecentAck()
  303. const pendingOpSize = pendingOp ? getShareJsOpSize(pendingOp) : 0
  304. if (inflightOp == null && pendingOp == null) {
  305. // There's nothing going on, this is OK.
  306. saved = true
  307. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  308. } else if (inflightOp && inflightOp === this.oldInflightOp) {
  309. // The same inflight op has been sitting unacked since we
  310. // last checked, this is bad.
  311. saved = false
  312. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  313. } else if (
  314. pendingOp != null &&
  315. recentAck &&
  316. pendingOpSize < MAX_PENDING_OP_SIZE
  317. ) {
  318. // There is an op waiting to go to server but it is small and
  319. // within the recent ack limit, this is OK for now.
  320. saved = true
  321. debugConsole.log(
  322. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  323. pendingOp,
  324. pendingOpSize
  325. )
  326. } else {
  327. // In any other situation, assume the document is unsaved.
  328. saved = false
  329. debugConsole.log(
  330. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  331. inflightOp != null
  332. }, pendingOp?: ${pendingOp != null})`
  333. )
  334. }
  335. this.oldInflightOp = inflightOp
  336. return saved
  337. }
  338. private cancelLeave() {
  339. this.leaveCallbacks = []
  340. }
  341. private cancelJoin() {
  342. this.joinCallbacks = []
  343. }
  344. private onUpdateApplied(update: Update) {
  345. if (update?.doc === this.doc_id && this.doc != null) {
  346. // FIXME: change this back to processUpdateFromServer when redis fixed
  347. this.doc.processUpdateFromServerInOrder(update)
  348. if (!this.wantToBeJoined) {
  349. return this.leave()
  350. }
  351. }
  352. }
  353. private onDisconnect() {
  354. debugConsole.log('[onDisconnect] disconnecting')
  355. this.connected = false
  356. this.joined = false
  357. return this.doc != null
  358. ? this.doc.updateConnectionState('disconnected')
  359. : undefined
  360. }
  361. private onReconnect = () => {
  362. debugConsole.log('[onReconnect] reconnected (joined project)')
  363. this.connected = true
  364. if (this.wantToBeJoined || this.doc?.hasBufferedOps()) {
  365. debugConsole.log(
  366. `[onReconnect] Rejoining (wantToBeJoined: ${
  367. this.wantToBeJoined
  368. } OR hasBufferedOps: ${this.doc?.hasBufferedOps()})`
  369. )
  370. this.joinDoc((error?: Error) => {
  371. if (error) {
  372. this.onError(error)
  373. return
  374. }
  375. this.doc?.updateConnectionState('ok')
  376. this.doc?.flushPendingOps()
  377. this.callJoinCallbacks()
  378. })
  379. }
  380. }
  381. private callJoinCallbacks() {
  382. for (const callback of this.joinCallbacks) {
  383. callback()
  384. }
  385. this.joinCallbacks = []
  386. }
  387. private joinDoc(callback?: JoinCallback) {
  388. if (this.doc) {
  389. return this.socket.emit(
  390. 'joinDoc',
  391. this.doc_id,
  392. this.doc.getVersion(),
  393. { encodeRanges: true, age: this.doc.getTimeSinceLastServerActivity() },
  394. (error, docLines, version, updates, ranges) => {
  395. if (error) {
  396. callback?.(error)
  397. return
  398. }
  399. this.joined = true
  400. this.doc?.catchUp(updates)
  401. this.decodeRanges(ranges)
  402. this.catchUpRanges(ranges?.changes, ranges?.comments)
  403. callback?.()
  404. }
  405. )
  406. } else {
  407. this.socket.emit(
  408. 'joinDoc',
  409. this.doc_id,
  410. { encodeRanges: true },
  411. (error, docLines, version, updates, ranges) => {
  412. if (error) {
  413. callback?.(error)
  414. return
  415. }
  416. this.joined = true
  417. this.doc = new ShareJsDoc(
  418. this.doc_id,
  419. docLines,
  420. version,
  421. this.socket,
  422. this.globalEditorWatchdogManager,
  423. this.ideEventEmitter
  424. )
  425. this.decodeRanges(ranges)
  426. this.ranges = new RangesTracker(ranges?.changes, ranges?.comments)
  427. this.bindToShareJsDocEvents()
  428. callback?.()
  429. }
  430. )
  431. }
  432. }
  433. private decodeRanges(ranges: RangesTracker) {
  434. try {
  435. if (ranges.changes) {
  436. for (const change of ranges.changes) {
  437. if (isInsertOperation(change.op)) {
  438. change.op.i = decodeUtf8(change.op.i)
  439. }
  440. if (isDeleteOperation(change.op)) {
  441. change.op.d = decodeUtf8(change.op.d)
  442. }
  443. }
  444. }
  445. return (() => {
  446. if (!ranges.comments) {
  447. return []
  448. }
  449. return ranges.comments.map((comment: Change<CommentOperation>) =>
  450. comment.op.c != null
  451. ? (comment.op.c = decodeUtf8(comment.op.c))
  452. : undefined
  453. )
  454. })()
  455. } catch (err) {
  456. debugConsole.error(err)
  457. }
  458. }
  459. private leaveDoc(callback?: LeaveCallback) {
  460. debugConsole.log('[leaveDoc] Sending leaveDoc request')
  461. this.socket.emit('leaveDoc', this.doc_id, error => {
  462. if (error) {
  463. callback?.(error)
  464. return
  465. }
  466. this.joined = false
  467. for (const leaveCallback of this.leaveCallbacks) {
  468. debugConsole.log('[_leaveDoc] Calling buffered callback', leaveCallback)
  469. leaveCallback(error)
  470. }
  471. this.leaveCallbacks = []
  472. callback?.()
  473. })
  474. }
  475. cleanUp() {
  476. // if we arrive here from _onError the pending and inflight ops will have been cleared
  477. if (this.hasBufferedOps()) {
  478. debugConsole.log(
  479. `[cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  480. )
  481. return // return immediately, do not unbind from events
  482. }
  483. this.detachDoc(this.doc_id, this)
  484. this.unBindFromEditorEvents()
  485. this.unBindFromSocketEvents()
  486. }
  487. private bindToShareJsDocEvents() {
  488. if (!this.doc) {
  489. return
  490. }
  491. this.doc.on('error', (error: Error, meta: ErrorMetadata) =>
  492. this.onError(error, meta)
  493. )
  494. this.doc.on('externalUpdate', (update: Update) => {
  495. return this.trigger('externalUpdate', update)
  496. })
  497. this.doc.on('remoteop', (...ops: AnyOperation[]) => {
  498. return this.trigger('remoteop', ...ops)
  499. })
  500. this.doc.on('op:sent', (op: AnyOperation) => {
  501. return this.trigger('op:sent')
  502. })
  503. this.doc.on('op:acknowledged', (op: AnyOperation) => {
  504. this.ideEventEmitter.emit('ide:opAcknowledged', {
  505. doc_id: this.doc_id,
  506. op,
  507. })
  508. return this.trigger('op:acknowledged')
  509. })
  510. this.doc.on('op:timeout', (op: AnyOperation) => {
  511. this.trigger('op:timeout')
  512. return this.onError(new Error('op timed out'))
  513. })
  514. let docChangedTimeout: number | null = null
  515. this.doc.on(
  516. 'change',
  517. (ops: AnyOperation[], oldSnapshot: any, msg: Message) => {
  518. this.applyOpsToRanges(ops, msg)
  519. if (docChangedTimeout) {
  520. window.clearTimeout(docChangedTimeout)
  521. }
  522. docChangedTimeout = window.setTimeout(() => {
  523. if (ops.some(isEditOperation)) {
  524. window.dispatchEvent(
  525. new CustomEvent('doc:changed', { detail: { id: this.doc_id } })
  526. )
  527. this.ideEventEmitter.emit('doc:changed', {
  528. doc_id: this.doc_id,
  529. })
  530. }
  531. }, 50)
  532. }
  533. )
  534. this.doc.on('flipped_pending_to_inflight', () => {
  535. return this.trigger('flipped_pending_to_inflight')
  536. })
  537. let docSavedTimeout: number | null
  538. this.doc.on('saved', () => {
  539. if (docSavedTimeout) {
  540. window.clearTimeout(docSavedTimeout)
  541. }
  542. docSavedTimeout = window.setTimeout(() => {
  543. window.dispatchEvent(
  544. new CustomEvent('doc:saved', { detail: { id: this.doc_id } })
  545. )
  546. this.ideEventEmitter.emit('doc:saved', { doc_id: this.doc_id })
  547. }, 50)
  548. })
  549. }
  550. private onError(
  551. error: Error,
  552. meta: ErrorMetadata = {},
  553. editorContent?: string
  554. ) {
  555. meta.doc_id = this.doc_id
  556. debugConsole.log('ShareJS error', error, meta)
  557. if (error.message === 'no project_id found on client') {
  558. debugConsole.log('ignoring error, will wait to join project')
  559. return
  560. }
  561. if (this.doc) {
  562. this.doc.clearInflightAndPendingOps()
  563. }
  564. this.trigger('error', error, meta, editorContent)
  565. // The clean-up should run after the error is triggered because the error triggers a
  566. // disconnect. If we run the clean-up first, we remove our event handlers and miss
  567. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  568. // This could interfere with the new connection of a new instance of this document.
  569. this.cleanUp()
  570. }
  571. private applyOpsToRanges(ops: AnyOperation[], msg?: Message) {
  572. let old_id_seed
  573. let track_changes_as = null
  574. const remote_op = msg != null
  575. if (remote_op && msg?.meta.tc) {
  576. old_id_seed = this.ranges!.getIdSeed()
  577. this.ranges!.setIdSeed(msg.meta.tc)
  578. track_changes_as = msg.meta.user_id
  579. } else if (!remote_op && this.track_changes_as != null) {
  580. track_changes_as = this.track_changes_as
  581. }
  582. this.ranges!.track_changes = track_changes_as != null
  583. for (const op of this.filterOps(ops)) {
  584. this.ranges!.applyOp(op, { user_id: track_changes_as })
  585. }
  586. if (old_id_seed != null) {
  587. this.ranges!.setIdSeed(old_id_seed)
  588. }
  589. if (remote_op) {
  590. // With remote ops, the editor hasn't been updated when we receive this
  591. // op, so defer updating track changes until it has
  592. return window.setTimeout(() => this.emit('ranges:dirty'))
  593. } else {
  594. return this.emit('ranges:dirty')
  595. }
  596. }
  597. private catchUpRanges(
  598. changes: Change<EditOperation>[],
  599. comments: Change<CommentOperation>[]
  600. ) {
  601. // We've just been given the current server's ranges, but need to apply any local ops we have.
  602. // Reset to the server state then apply our local ops again.
  603. if (changes == null) {
  604. changes = []
  605. }
  606. if (comments == null) {
  607. comments = []
  608. }
  609. this.emit('ranges:clear')
  610. this.ranges!.changes = changes
  611. this.ranges!.comments = comments
  612. this.ranges!.track_changes = this.doc?.track_changes ?? false
  613. for (const op of this.filterOps(this.doc?.getInflightOp() || [])) {
  614. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.inflight)
  615. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  616. }
  617. for (const op of this.filterOps(this.doc?.getPendingOp() || [])) {
  618. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.pending)
  619. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  620. }
  621. return this.emit('ranges:redraw')
  622. }
  623. private filterOps(ops: AnyOperation[]) {
  624. // Read-only token users can't see/edit comment, so we filter out comment
  625. // ops to avoid highlighting comment ranges.
  626. if (getMeta('ol-isRestrictedTokenMember')) {
  627. return ops.filter(op => !isCommentOperation(op))
  628. } else {
  629. return ops
  630. }
  631. }
  632. }