document-container.ts 19 KB

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