compiler.js 6.3 KB

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