compiler.js 6.8 KB

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