compiler.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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.stopOnFirstError = false
  41. this.debouncedAutoCompile = debounce(
  42. () => {
  43. this.compile({ isAutoCompileOnChange: true })
  44. },
  45. AUTO_COMPILE_DEBOUNCE,
  46. {
  47. maxWait: AUTO_COMPILE_MAX_WAIT,
  48. }
  49. )
  50. }
  51. // The main "compile" function.
  52. // Call this directly to run a compile now, otherwise call debouncedAutoCompile.
  53. async compile(options = {}) {
  54. if (!options) {
  55. options = {}
  56. }
  57. // set "compiling" to true (in the React component's state), and return if it was already true
  58. const wasCompiling = this.compilingRef.current
  59. this.setCompiling(true)
  60. if (wasCompiling) {
  61. if (options.isAutoCompileOnChange) {
  62. this.debouncedAutoCompile()
  63. }
  64. return
  65. }
  66. try {
  67. // reset values
  68. this.setChangedAt(0)
  69. this.validationIssues = undefined
  70. window.dispatchEvent(new CustomEvent('flush-changes')) // TODO: wait for this?
  71. const params = this.buildCompileParams(options)
  72. const t0 = performance.now()
  73. const body = {
  74. rootDoc_id: this.getRootDocOverrideId(),
  75. draft: this.draft,
  76. check: 'silent', // NOTE: 'error' and 'validate' are possible, but unused
  77. // use incremental compile for all users but revert to a full compile
  78. // if there was previously a server error
  79. incrementalCompilesEnabled: !this.error,
  80. }
  81. if (getMeta('ol-showStopOnFirstError')) {
  82. body.stopOnFirstError = this.stopOnFirstError
  83. }
  84. const data = await postJSON(
  85. `/project/${this.projectId}/compile?${params}`,
  86. { body, signal: this.signal }
  87. )
  88. const compileTimeClientE2E = performance.now() - t0
  89. const { firstRenderDone } = trackPdfDownload(data, compileTimeClientE2E)
  90. this.setFirstRenderDone(() => firstRenderDone)
  91. // unset the error before it's set again later, so that components are recreated and events are tracked
  92. this.setError(undefined)
  93. data.options = options
  94. if (data.clsiServerId) {
  95. this.clsiServerId = data.clsiServerId
  96. }
  97. this.setData(data)
  98. } catch (error) {
  99. console.error(error)
  100. this.cleanupCompileResult()
  101. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  102. } finally {
  103. this.setCompiling(false)
  104. }
  105. }
  106. // parse the text of the current doc in the editor
  107. // if it contains "\documentclass" then use this as the root doc
  108. getRootDocOverrideId() {
  109. // only override when not in the root doc itself
  110. if (this.currentDoc.doc_id !== this.rootDocId) {
  111. const snapshot = this.currentDoc.getSnapshot()
  112. if (snapshot && isMainFile(snapshot)) {
  113. return this.currentDoc.doc_id
  114. }
  115. }
  116. return null
  117. }
  118. // build the query parameters added to post-compile requests
  119. buildPostCompileParams() {
  120. const params = new URLSearchParams()
  121. // the id of the CLSI server that processed the previous compile request
  122. if (this.clsiServerId) {
  123. params.set('clsiserverid', this.clsiServerId)
  124. }
  125. return params
  126. }
  127. // build the query parameters for the compile request
  128. buildCompileParams(options) {
  129. const params = new URLSearchParams()
  130. // note: no clsiserverid query param is set on "compile" requests,
  131. // as this is added in the backend by the web api
  132. // tell the server whether this is an automatic or manual compile request
  133. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  134. params.set('auto_compile', 'true')
  135. }
  136. // use the feature flag to enable PDF caching in a ServiceWorker
  137. if (getMeta('ol-enablePdfCaching')) {
  138. params.set('enable_pdf_caching', 'true')
  139. }
  140. // use the feature flag to enable "file line errors"
  141. if (searchParams.get('file_line_errors') === 'true') {
  142. params.file_line_errors = 'true'
  143. }
  144. return params
  145. }
  146. // send a request to stop the current compile
  147. stopCompile() {
  148. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  149. // and doesn't matter if it runs twice.
  150. const params = this.buildPostCompileParams()
  151. return postJSON(`/project/${this.projectId}/compile/stop?${params}`, {
  152. signal: this.signal,
  153. })
  154. .catch(error => {
  155. console.error(error)
  156. this.setError('error')
  157. })
  158. .finally(() => {
  159. this.setCompiling(false)
  160. })
  161. }
  162. // send a request to clear the cache
  163. clearCache() {
  164. const params = this.buildPostCompileParams()
  165. return deleteJSON(`/project/${this.projectId}/output?${params}`, {
  166. signal: this.signal,
  167. }).catch(error => {
  168. console.error(error)
  169. this.setError('clear-cache')
  170. })
  171. }
  172. }