compiler.js 6.3 KB

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