document-container.ts 19 KB

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