compiler.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import { isMainFile } from './editor-files'
  2. import getMeta from '../../../utils/meta'
  3. import { sendMBSampled } from '../../../infrastructure/event-tracking'
  4. import { deleteJSON, postJSON } from '../../../infrastructure/fetch-json'
  5. import { debounce } from 'lodash'
  6. import { trackPdfDownload } from '../../../ide/pdf/controllers/PdfJsMetrics'
  7. const AUTO_COMPILE_MAX_WAIT = 5000
  8. // We add a 1 second debounce to sending user changes to server if they aren't
  9. // collaborating with anyone. This needs to be higher than that, and allow for
  10. // client to server latency, otherwise we compile before the op reaches the server
  11. // and then again on ack.
  12. const AUTO_COMPILE_DEBOUNCE = 2000
  13. const searchParams = new URLSearchParams(window.location.search)
  14. export default class DocumentCompiler {
  15. constructor({
  16. project,
  17. setChangedAt,
  18. setCompiling,
  19. setData,
  20. setFirstRenderDone,
  21. setError,
  22. cleanupCompileResult,
  23. signal,
  24. }) {
  25. this.project = project
  26. this.setChangedAt = setChangedAt
  27. this.setCompiling = setCompiling
  28. this.setData = setData
  29. this.setFirstRenderDone = setFirstRenderDone
  30. this.setError = setError
  31. this.cleanupCompileResult = cleanupCompileResult
  32. this.signal = signal
  33. this.clsiServerId = null
  34. this.currentDoc = null
  35. this.error = undefined
  36. this.timer = 0
  37. this.debouncedAutoCompile = debounce(
  38. () => {
  39. this.compile({ isAutoCompileOnChange: true })
  40. },
  41. AUTO_COMPILE_DEBOUNCE,
  42. {
  43. maxWait: AUTO_COMPILE_MAX_WAIT,
  44. }
  45. )
  46. }
  47. // The main "compile" function.
  48. // Call this directly to run a compile now, otherwise call debouncedAutoCompile.
  49. async compile(options = {}) {
  50. // only compile if the feature flag is enabled
  51. if (!window.showNewPdfPreview) {
  52. return
  53. }
  54. // set "compiling" to true (in the React component's state), and return if it was already true
  55. let wasCompiling
  56. this.setCompiling(oldValue => {
  57. wasCompiling = oldValue
  58. return true
  59. })
  60. if (wasCompiling) {
  61. return
  62. }
  63. try {
  64. // log a sample of the compile requests
  65. sendMBSampled('editor-recompile-sampled', options)
  66. // reset values
  67. this.setChangedAt(0)
  68. this.validationIssues = undefined
  69. window.dispatchEvent(new CustomEvent('flush-changes')) // TODO: wait for this?
  70. const params = this.buildCompileParams(options)
  71. const t0 = performance.now()
  72. const data = await postJSON(
  73. `/project/${this.project._id}/compile?${params}`,
  74. {
  75. body: {
  76. rootDoc_id: this.getRootDocOverrideId(),
  77. draft: this.draft,
  78. check: 'silent', // NOTE: 'error' and 'validate' are possible, but unused
  79. // use incremental compile for all users but revert to a full compile
  80. // if there was previously a server error
  81. incrementalCompilesEnabled: !this.error,
  82. },
  83. signal: this.signal,
  84. }
  85. )
  86. const compileTimeClientE2E = performance.now() - t0
  87. const { firstRenderDone } = trackPdfDownload(data, compileTimeClientE2E)
  88. this.setFirstRenderDone(() => firstRenderDone)
  89. data.options = options
  90. if (data.clsiServerId) {
  91. this.clsiServerId = data.clsiServerId
  92. }
  93. this.setData(data)
  94. } catch (error) {
  95. console.error(error)
  96. this.cleanupCompileResult()
  97. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  98. } finally {
  99. this.setCompiling(false)
  100. }
  101. }
  102. // parse the text of the current doc in the editor
  103. // if it contains "\documentclass" then use this as the root doc
  104. getRootDocOverrideId() {
  105. // only override when not in the root doc itself
  106. if (this.currentDoc.doc_id !== this.project.rootDoc_id) {
  107. const snapshot = this.currentDoc.getSnapshot()
  108. if (snapshot && isMainFile(snapshot)) {
  109. return this.currentDoc.doc_id
  110. }
  111. }
  112. return null
  113. }
  114. // build the query parameters added to post-compile requests
  115. buildPostCompileParams() {
  116. const params = new URLSearchParams()
  117. // the id of the CLSI server that processed the previous compile request
  118. if (this.clsiServerId) {
  119. params.set('clsiserverid', this.clsiServerId)
  120. }
  121. return params
  122. }
  123. // build the query parameters for the compile request
  124. buildCompileParams(options) {
  125. const params = new URLSearchParams()
  126. // note: no clsiserverid query param is set on "compile" requests,
  127. // as this is added in the backend by the web api
  128. // tell the server whether this is an automatic or manual compile request
  129. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  130. params.set('auto_compile', 'true')
  131. }
  132. // use the feature flag to enable PDF caching in a ServiceWorker
  133. if (getMeta('ol-enablePdfCaching')) {
  134. params.set('enable_pdf_caching', 'true')
  135. }
  136. // use the feature flag to enable "file line errors"
  137. if (searchParams.get('file_line_errors') === 'true') {
  138. params.file_line_errors = 'true'
  139. }
  140. return params
  141. }
  142. // send a request to stop the current compile
  143. stopCompile() {
  144. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  145. // and doesn't matter if it runs twice.
  146. const params = this.buildPostCompileParams()
  147. return postJSON(`/project/${this.project._id}/compile/stop?${params}`, {
  148. signal: this.signal,
  149. })
  150. .catch(error => {
  151. console.error(error)
  152. this.setError('error')
  153. })
  154. .finally(() => {
  155. this.setCompiling(false)
  156. })
  157. }
  158. // send a request to clear the cache
  159. clearCache() {
  160. const params = this.buildPostCompileParams()
  161. return deleteJSON(`/project/${this.project._id}/output?${params}`, {
  162. signal: this.signal,
  163. }).catch(error => {
  164. console.error(error)
  165. this.setError('clear-cache')
  166. })
  167. }
  168. }