document-container.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. hasBufferedOps() {
  159. return this.doc?.hasBufferedOps()
  160. }
  161. setTrackingChanges(track_changes: boolean) {
  162. if (this.doc) {
  163. this.doc.track_changes = track_changes
  164. }
  165. }
  166. getTrackingChanges() {
  167. return !!this.doc?.track_changes
  168. }
  169. setTrackChangesIdSeeds(id_seeds: TrackChangesIdSeeds) {
  170. if (this.doc) {
  171. this.doc.track_changes_id_seeds = id_seeds
  172. }
  173. }
  174. private onUpdateAppliedHandler = (update: any) => this.onUpdateApplied(update)
  175. private onErrorHandler = (error: Error, message: ErrorMetadata) => {
  176. // 'otUpdateError' are emitted per doc socket.io room, hence we can be
  177. // sure that message.doc_id exists.
  178. if (message.doc_id !== this.doc_id) {
  179. // This error is for another doc. Do not action it. We could open
  180. // a modal that has the wrong context on it.
  181. return
  182. }
  183. this.onError(error, message)
  184. }
  185. private onDisconnectHandler = () => this.onDisconnect()
  186. private bindToSocketEvents() {
  187. this.socket.on('otUpdateApplied', this.onUpdateAppliedHandler)
  188. this.socket.on('otUpdateError', this.onErrorHandler)
  189. return this.socket.on('disconnect', this.onDisconnectHandler)
  190. }
  191. private unBindFromSocketEvents() {
  192. this.socket.removeListener('otUpdateApplied', this.onUpdateAppliedHandler)
  193. this.socket.removeListener('otUpdateError', this.onErrorHandler)
  194. return this.socket.removeListener('disconnect', this.onDisconnectHandler)
  195. }
  196. private bindToEditorEvents() {
  197. this.ideEventEmitter.on('project:joined', this.onReconnect)
  198. }
  199. private unBindFromEditorEvents() {
  200. this.ideEventEmitter.off('project:joined', this.onReconnect)
  201. }
  202. leaveAndCleanUp(cb?: (error?: Error) => void) {
  203. return this.leave((error?: Error) => {
  204. this.cleanUp()
  205. if (cb) cb(error)
  206. })
  207. }
  208. leaveAndCleanUpPromise() {
  209. return new Promise<void>((resolve, reject) => {
  210. this.leaveAndCleanUp((error?: Error) => {
  211. if (error) {
  212. reject(error)
  213. } else {
  214. resolve()
  215. }
  216. })
  217. })
  218. }
  219. join(callback?: JoinCallback) {
  220. this.wantToBeJoined = true
  221. this.cancelLeave()
  222. if (this.connected) {
  223. this.joinDoc(callback)
  224. } else if (callback) {
  225. this.joinCallbacks.push(callback)
  226. }
  227. }
  228. leave(callback?: LeaveCallback) {
  229. this.flush() // force an immediate flush when leaving document
  230. this.wantToBeJoined = false
  231. this.cancelJoin()
  232. if (this.doc?.hasBufferedOps()) {
  233. debugConsole.log(
  234. '[leave] Doc has buffered ops, pushing callback for later'
  235. )
  236. if (callback) {
  237. this.leaveCallbacks.push(callback)
  238. }
  239. } else if (!this.connected) {
  240. debugConsole.log('[leave] Not connected, returning now')
  241. callback?.()
  242. } else {
  243. debugConsole.log('[leave] Leaving now')
  244. this.leaveDoc(callback)
  245. }
  246. }
  247. flush() {
  248. return this.doc?.flushPendingOps()
  249. }
  250. chaosMonkey(line = 0, char = 'a') {
  251. const orig = char
  252. let copy: string | null = null
  253. let pos = 0
  254. const timer = () => {
  255. if (copy == null || !copy.length) {
  256. copy = orig.slice() + ' ' + new Date() + '\n'
  257. line += Math.random() > 0.1 ? 1 : -2
  258. if (line < 0) {
  259. line = 0
  260. }
  261. pos = 0
  262. }
  263. char = copy[0]
  264. copy = copy.slice(1)
  265. if (this.cm6) {
  266. this.cm6.view.dispatch({
  267. changes: {
  268. from: Math.min(pos, this.cm6.view.state.doc.length),
  269. insert: char,
  270. },
  271. })
  272. }
  273. pos += 1
  274. this.chaosMonkeyTimer = window.setTimeout(
  275. timer,
  276. 100 + (Math.random() < 0.1 ? 1000 : 0)
  277. )
  278. }
  279. timer()
  280. }
  281. clearChaosMonkey() {
  282. const timer = this.chaosMonkeyTimer
  283. if (timer) {
  284. this.chaosMonkeyTimer = null
  285. window.clearTimeout(timer)
  286. }
  287. }
  288. pollSavedStatus() {
  289. // returns false if doc has ops waiting to be acknowledged or
  290. // sent that haven't changed since the last time we checked.
  291. // Otherwise returns true.
  292. let saved
  293. const inflightOp = this.getInflightOp()
  294. const pendingOp = this.getPendingOp()
  295. const recentAck = this.getRecentAck()
  296. const pendingOpSize = pendingOp ? getShareJsOpSize(pendingOp) : 0
  297. if (inflightOp == null && pendingOp == null) {
  298. // There's nothing going on, this is OK.
  299. saved = true
  300. debugConsole.log('[pollSavedStatus] no inflight or pending ops')
  301. } else if (inflightOp && inflightOp === this.oldInflightOp) {
  302. // The same inflight op has been sitting unacked since we
  303. // last checked, this is bad.
  304. saved = false
  305. debugConsole.log('[pollSavedStatus] inflight op is same as before')
  306. } else if (
  307. pendingOp != null &&
  308. recentAck &&
  309. pendingOpSize < MAX_PENDING_OP_SIZE
  310. ) {
  311. // There is an op waiting to go to server but it is small and
  312. // within the flushDelay, this is OK for now.
  313. saved = true
  314. debugConsole.log(
  315. '[pollSavedStatus] pending op (small with recent ack) assume ok',
  316. pendingOp,
  317. pendingOpSize
  318. )
  319. } else {
  320. // In any other situation, assume the document is unsaved.
  321. saved = false
  322. debugConsole.log(
  323. `[pollSavedStatus] assuming not saved (inflightOp?: ${
  324. inflightOp != null
  325. }, pendingOp?: ${pendingOp != null})`
  326. )
  327. }
  328. this.oldInflightOp = inflightOp
  329. return saved
  330. }
  331. private cancelLeave() {
  332. this.leaveCallbacks = []
  333. }
  334. private cancelJoin() {
  335. this.joinCallbacks = []
  336. }
  337. private onUpdateApplied(update: Update) {
  338. if (update?.doc === this.doc_id && this.doc != null) {
  339. // FIXME: change this back to processUpdateFromServer when redis fixed
  340. this.doc.processUpdateFromServerInOrder(update)
  341. if (!this.wantToBeJoined) {
  342. return this.leave()
  343. }
  344. }
  345. }
  346. private onDisconnect() {
  347. debugConsole.log('[onDisconnect] disconnecting')
  348. this.connected = false
  349. this.joined = false
  350. return this.doc != null
  351. ? this.doc.updateConnectionState('disconnected')
  352. : undefined
  353. }
  354. private onReconnect = () => {
  355. debugConsole.log('[onReconnect] reconnected (joined project)')
  356. this.connected = true
  357. if (this.wantToBeJoined || this.doc?.hasBufferedOps()) {
  358. debugConsole.log(
  359. `[onReconnect] Rejoining (wantToBeJoined: ${
  360. this.wantToBeJoined
  361. } OR hasBufferedOps: ${this.doc?.hasBufferedOps()})`
  362. )
  363. this.joinDoc((error?: Error) => {
  364. if (error) {
  365. this.onError(error)
  366. return
  367. }
  368. this.doc?.updateConnectionState('ok')
  369. this.doc?.flushPendingOps()
  370. this.callJoinCallbacks()
  371. })
  372. }
  373. }
  374. private callJoinCallbacks() {
  375. for (const callback of this.joinCallbacks) {
  376. callback()
  377. }
  378. this.joinCallbacks = []
  379. }
  380. private joinDoc(callback?: JoinCallback) {
  381. if (this.doc) {
  382. return this.socket.emit(
  383. 'joinDoc',
  384. this.doc_id,
  385. this.doc.getVersion(),
  386. { encodeRanges: true, age: this.doc.getTimeSinceLastServerActivity() },
  387. (error, docLines, version, updates, ranges) => {
  388. if (error) {
  389. callback?.(error)
  390. return
  391. }
  392. this.joined = true
  393. this.doc?.catchUp(updates)
  394. this.decodeRanges(ranges)
  395. this.catchUpRanges(ranges?.changes, ranges?.comments)
  396. callback?.()
  397. }
  398. )
  399. } else {
  400. this.socket.emit(
  401. 'joinDoc',
  402. this.doc_id,
  403. { encodeRanges: true },
  404. (error, docLines, version, updates, ranges) => {
  405. if (error) {
  406. callback?.(error)
  407. return
  408. }
  409. this.joined = true
  410. this.doc = new ShareJsDoc(
  411. this.doc_id,
  412. docLines,
  413. version,
  414. this.socket,
  415. this.globalEditorWatchdogManager,
  416. this.ideEventEmitter
  417. )
  418. this.decodeRanges(ranges)
  419. this.ranges = new RangesTracker(ranges?.changes, ranges?.comments)
  420. this.bindToShareJsDocEvents()
  421. callback?.()
  422. }
  423. )
  424. }
  425. }
  426. private decodeRanges(ranges: RangesTracker) {
  427. try {
  428. if (ranges.changes) {
  429. for (const change of ranges.changes) {
  430. if (isInsertOperation(change.op)) {
  431. change.op.i = decodeUtf8(change.op.i)
  432. }
  433. if (isDeleteOperation(change.op)) {
  434. change.op.d = decodeUtf8(change.op.d)
  435. }
  436. }
  437. }
  438. return (() => {
  439. if (!ranges.comments) {
  440. return []
  441. }
  442. return ranges.comments.map((comment: Change<CommentOperation>) =>
  443. comment.op.c != null
  444. ? (comment.op.c = decodeUtf8(comment.op.c))
  445. : undefined
  446. )
  447. })()
  448. } catch (err) {
  449. debugConsole.error(err)
  450. }
  451. }
  452. private leaveDoc(callback?: LeaveCallback) {
  453. debugConsole.log('[leaveDoc] Sending leaveDoc request')
  454. this.socket.emit('leaveDoc', this.doc_id, error => {
  455. if (error) {
  456. callback?.(error)
  457. return
  458. }
  459. this.joined = false
  460. for (const leaveCallback of this.leaveCallbacks) {
  461. debugConsole.log('[_leaveDoc] Calling buffered callback', leaveCallback)
  462. leaveCallback(error)
  463. }
  464. this.leaveCallbacks = []
  465. callback?.()
  466. })
  467. }
  468. cleanUp() {
  469. // if we arrive here from _onError the pending and inflight ops will have been cleared
  470. if (this.hasBufferedOps()) {
  471. debugConsole.log(
  472. `[cleanUp] Document (${this.doc_id}) has buffered ops, refusing to remove from openDocs`
  473. )
  474. return // return immediately, do not unbind from events
  475. }
  476. this.detachDoc(this.doc_id, this)
  477. this.unBindFromEditorEvents()
  478. this.unBindFromSocketEvents()
  479. }
  480. private bindToShareJsDocEvents() {
  481. if (!this.doc) {
  482. return
  483. }
  484. this.doc.on('error', (error: Error, meta: ErrorMetadata) =>
  485. this.onError(error, meta)
  486. )
  487. this.doc.on('externalUpdate', (update: Update) => {
  488. return this.trigger('externalUpdate', update)
  489. })
  490. this.doc.on('remoteop', (...ops: AnyOperation[]) => {
  491. return this.trigger('remoteop', ...ops)
  492. })
  493. this.doc.on('op:sent', (op: AnyOperation) => {
  494. return this.trigger('op:sent')
  495. })
  496. this.doc.on('op:acknowledged', (op: AnyOperation) => {
  497. this.ideEventEmitter.emit('ide:opAcknowledged', {
  498. doc_id: this.doc_id,
  499. op,
  500. })
  501. return this.trigger('op:acknowledged')
  502. })
  503. this.doc.on('op:timeout', (op: AnyOperation) => {
  504. this.trigger('op:timeout')
  505. return this.onError(new Error('op timed out'))
  506. })
  507. let docChangedTimeout: number | null = null
  508. this.doc.on(
  509. 'change',
  510. (ops: AnyOperation[], oldSnapshot: any, msg: Message) => {
  511. this.applyOpsToRanges(ops, msg)
  512. if (docChangedTimeout) {
  513. window.clearTimeout(docChangedTimeout)
  514. }
  515. docChangedTimeout = window.setTimeout(() => {
  516. window.dispatchEvent(
  517. new CustomEvent('doc:changed', { detail: { id: this.doc_id } })
  518. )
  519. this.ideEventEmitter.emit('doc:changed', { doc_id: this.doc_id })
  520. }, 50)
  521. }
  522. )
  523. this.doc.on('flipped_pending_to_inflight', () => {
  524. return this.trigger('flipped_pending_to_inflight')
  525. })
  526. let docSavedTimeout: number | null
  527. this.doc.on('saved', () => {
  528. if (docSavedTimeout) {
  529. window.clearTimeout(docSavedTimeout)
  530. }
  531. docSavedTimeout = window.setTimeout(() => {
  532. window.dispatchEvent(
  533. new CustomEvent('doc:saved', { detail: { id: this.doc_id } })
  534. )
  535. this.ideEventEmitter.emit('doc:saved', { doc_id: this.doc_id })
  536. }, 50)
  537. })
  538. }
  539. private onError(
  540. error: Error,
  541. meta: ErrorMetadata = {},
  542. editorContent?: string
  543. ) {
  544. meta.doc_id = this.doc_id
  545. debugConsole.log('ShareJS error', error, meta)
  546. if (error.message === 'no project_id found on client') {
  547. debugConsole.log('ignoring error, will wait to join project')
  548. return
  549. }
  550. if (this.doc) {
  551. this.doc.clearInflightAndPendingOps()
  552. }
  553. this.trigger('error', error, meta, editorContent)
  554. // The clean-up should run after the error is triggered because the error triggers a
  555. // disconnect. If we run the clean-up first, we remove our event handlers and miss
  556. // the disconnect event, which means we try to leaveDoc when the connection comes back.
  557. // This could interfere with the new connection of a new instance of this document.
  558. this.cleanUp()
  559. }
  560. private applyOpsToRanges(ops: AnyOperation[], msg?: Message) {
  561. let old_id_seed
  562. let track_changes_as = null
  563. const remote_op = msg != null
  564. if (remote_op && msg?.meta.tc) {
  565. old_id_seed = this.ranges!.getIdSeed()
  566. this.ranges!.setIdSeed(msg.meta.tc)
  567. track_changes_as = msg.meta.user_id
  568. } else if (!remote_op && this.track_changes_as != null) {
  569. track_changes_as = this.track_changes_as
  570. }
  571. this.ranges!.track_changes = track_changes_as != null
  572. for (const op of this.filterOps(ops)) {
  573. this.ranges!.applyOp(op, { user_id: track_changes_as })
  574. }
  575. if (old_id_seed != null) {
  576. this.ranges!.setIdSeed(old_id_seed)
  577. }
  578. if (remote_op) {
  579. // With remote ops, the editor hasn't been updated when we receive this
  580. // op, so defer updating track changes until it has
  581. return window.setTimeout(() => this.emit('ranges:dirty'))
  582. } else {
  583. return this.emit('ranges:dirty')
  584. }
  585. }
  586. private catchUpRanges(
  587. changes: Change<EditOperation>[],
  588. comments: Change<CommentOperation>[]
  589. ) {
  590. // We've just been given the current server's ranges, but need to apply any local ops we have.
  591. // Reset to the server state then apply our local ops again.
  592. if (changes == null) {
  593. changes = []
  594. }
  595. if (comments == null) {
  596. comments = []
  597. }
  598. this.emit('ranges:clear')
  599. this.ranges!.changes = changes
  600. this.ranges!.comments = comments
  601. this.ranges!.track_changes = this.doc?.track_changes ?? false
  602. for (const op of this.filterOps(this.doc?.getInflightOp() || [])) {
  603. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.inflight)
  604. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  605. }
  606. for (const op of this.filterOps(this.doc?.getPendingOp() || [])) {
  607. this.ranges!.setIdSeed(this.doc?.track_changes_id_seeds?.pending)
  608. this.ranges!.applyOp(op, { user_id: this.track_changes_as })
  609. }
  610. return this.emit('ranges:redraw')
  611. }
  612. private filterOps(ops: AnyOperation[]) {
  613. // Read-only token users can't see/edit comment, so we filter out comment
  614. // ops to avoid highlighting comment ranges.
  615. if (getMeta('ol-isRestrictedTokenMember')) {
  616. return ops.filter(op => !isCommentOperation(op))
  617. } else {
  618. return ops
  619. }
  620. }
  621. }