compiler.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 2 second debounce to sending user changes to server if they aren't
  9. // collaborating with anyone. This needs to be higher than SINGLE_USER_FLUSH_DELAY, 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 = 2500
  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. if (options.isAutoCompileOnChange) {
  62. this.debouncedAutoCompile()
  63. }
  64. return
  65. }
  66. try {
  67. // log a sample of the compile requests
  68. sendMBSampled('editor-recompile-sampled', options)
  69. // reset values
  70. this.setChangedAt(0)
  71. this.validationIssues = undefined
  72. window.dispatchEvent(new CustomEvent('flush-changes')) // TODO: wait for this?
  73. const params = this.buildCompileParams(options)
  74. const t0 = performance.now()
  75. const data = await postJSON(
  76. `/project/${this.project._id}/compile?${params}`,
  77. {
  78. body: {
  79. rootDoc_id: this.getRootDocOverrideId(),
  80. draft: this.draft,
  81. check: 'silent', // NOTE: 'error' and 'validate' are possible, but unused
  82. // use incremental compile for all users but revert to a full compile
  83. // if there was previously a server error
  84. incrementalCompilesEnabled: !this.error,
  85. },
  86. signal: this.signal,
  87. }
  88. )
  89. const compileTimeClientE2E = performance.now() - t0
  90. const { firstRenderDone } = trackPdfDownload(data, compileTimeClientE2E)
  91. this.setFirstRenderDone(() => firstRenderDone)
  92. data.options = options
  93. if (data.clsiServerId) {
  94. this.clsiServerId = data.clsiServerId
  95. }
  96. this.setData(data)
  97. } catch (error) {
  98. console.error(error)
  99. this.cleanupCompileResult()
  100. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  101. } finally {
  102. this.setCompiling(false)
  103. }
  104. }
  105. // parse the text of the current doc in the editor
  106. // if it contains "\documentclass" then use this as the root doc
  107. getRootDocOverrideId() {
  108. // only override when not in the root doc itself
  109. if (this.currentDoc.doc_id !== this.project.rootDoc_id) {
  110. const snapshot = this.currentDoc.getSnapshot()
  111. if (snapshot && isMainFile(snapshot)) {
  112. return this.currentDoc.doc_id
  113. }
  114. }
  115. return null
  116. }
  117. // build the query parameters added to post-compile requests
  118. buildPostCompileParams() {
  119. const params = new URLSearchParams()
  120. // the id of the CLSI server that processed the previous compile request
  121. if (this.clsiServerId) {
  122. params.set('clsiserverid', this.clsiServerId)
  123. }
  124. return params
  125. }
  126. // build the query parameters for the compile request
  127. buildCompileParams(options) {
  128. const params = new URLSearchParams()
  129. // note: no clsiserverid query param is set on "compile" requests,
  130. // as this is added in the backend by the web api
  131. // tell the server whether this is an automatic or manual compile request
  132. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  133. params.set('auto_compile', 'true')
  134. }
  135. // use the feature flag to enable PDF caching in a ServiceWorker
  136. if (getMeta('ol-enablePdfCaching')) {
  137. params.set('enable_pdf_caching', 'true')
  138. }
  139. // use the feature flag to enable "file line errors"
  140. if (searchParams.get('file_line_errors') === 'true') {
  141. params.file_line_errors = 'true'
  142. }
  143. return params
  144. }
  145. // send a request to stop the current compile
  146. stopCompile() {
  147. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  148. // and doesn't matter if it runs twice.
  149. const params = this.buildPostCompileParams()
  150. return postJSON(`/project/${this.project._id}/compile/stop?${params}`, {
  151. signal: this.signal,
  152. })
  153. .catch(error => {
  154. console.error(error)
  155. this.setError('error')
  156. })
  157. .finally(() => {
  158. this.setCompiling(false)
  159. })
  160. }
  161. // send a request to clear the cache
  162. clearCache() {
  163. const params = this.buildPostCompileParams()
  164. return deleteJSON(`/project/${this.project._id}/output?${params}`, {
  165. signal: this.signal,
  166. }).catch(error => {
  167. console.error(error)
  168. this.setError('clear-cache')
  169. })
  170. }
  171. }