compiler.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 './metrics'
  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. // set "compiling" to true (in the React component's state), and return if it was already true
  57. const wasCompiling = this.compilingRef.current
  58. this.setCompiling(true)
  59. if (wasCompiling) {
  60. if (options.isAutoCompileOnChange) {
  61. this.debouncedAutoCompile()
  62. }
  63. return
  64. }
  65. try {
  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.projectId}/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. // unset the error before it's set again later, so that components are recreated and events are tracked
  90. this.setError(undefined)
  91. data.options = options
  92. if (data.clsiServerId) {
  93. this.clsiServerId = data.clsiServerId
  94. }
  95. this.setData(data)
  96. } catch (error) {
  97. console.error(error)
  98. this.cleanupCompileResult()
  99. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  100. } finally {
  101. this.setCompiling(false)
  102. }
  103. }
  104. // parse the text of the current doc in the editor
  105. // if it contains "\documentclass" then use this as the root doc
  106. getRootDocOverrideId() {
  107. // only override when not in the root doc itself
  108. if (this.currentDoc.doc_id !== this.rootDocId) {
  109. const snapshot = this.currentDoc.getSnapshot()
  110. if (snapshot && isMainFile(snapshot)) {
  111. return this.currentDoc.doc_id
  112. }
  113. }
  114. return null
  115. }
  116. // build the query parameters added to post-compile requests
  117. buildPostCompileParams() {
  118. const params = new URLSearchParams()
  119. // the id of the CLSI server that processed the previous compile request
  120. if (this.clsiServerId) {
  121. params.set('clsiserverid', this.clsiServerId)
  122. }
  123. return params
  124. }
  125. // build the query parameters for the compile request
  126. buildCompileParams(options) {
  127. const params = new URLSearchParams()
  128. // note: no clsiserverid query param is set on "compile" requests,
  129. // as this is added in the backend by the web api
  130. // tell the server whether this is an automatic or manual compile request
  131. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  132. params.set('auto_compile', 'true')
  133. }
  134. // use the feature flag to enable PDF caching in a ServiceWorker
  135. if (getMeta('ol-enablePdfCaching')) {
  136. params.set('enable_pdf_caching', 'true')
  137. }
  138. // use the feature flag to enable "file line errors"
  139. if (searchParams.get('file_line_errors') === 'true') {
  140. params.file_line_errors = 'true'
  141. }
  142. return params
  143. }
  144. // send a request to stop the current compile
  145. stopCompile() {
  146. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  147. // and doesn't matter if it runs twice.
  148. const params = this.buildPostCompileParams()
  149. return postJSON(`/project/${this.projectId}/compile/stop?${params}`, {
  150. signal: this.signal,
  151. })
  152. .catch(error => {
  153. console.error(error)
  154. this.setError('error')
  155. })
  156. .finally(() => {
  157. this.setCompiling(false)
  158. })
  159. }
  160. // send a request to clear the cache
  161. clearCache() {
  162. const params = this.buildPostCompileParams()
  163. return deleteJSON(`/project/${this.projectId}/output?${params}`, {
  164. signal: this.signal,
  165. }).catch(error => {
  166. console.error(error)
  167. this.setError('clear-cache')
  168. })
  169. }
  170. }