compiler.js 6.1 KB

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