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