compiler.js 6.4 KB

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