compiler.js 6.3 KB

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