compiler.js 6.7 KB

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