compiler.js 6.8 KB

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