compiler.js 6.8 KB

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