compiler.js 5.9 KB

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