compiler.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 { EDITOR_SESSION_ID, 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. editorId: EDITOR_SESSION_ID,
  97. }
  98. const data = await postJSON(
  99. `/project/${this.projectId}/compile?${params}`,
  100. { body, signal: this.signal }
  101. )
  102. const compileTimeClientE2E = Math.ceil(performance.now() - t0)
  103. const { deliveryLatencies, firstRenderDone } = trackPdfDownload(
  104. data,
  105. compileTimeClientE2E,
  106. t0
  107. )
  108. this.setDeliveryLatencies(() => deliveryLatencies)
  109. this.setFirstRenderDone(() => firstRenderDone)
  110. // unset the error before it's set again later, so that components are recreated and events are tracked
  111. this.setError(undefined)
  112. data.options = options
  113. data.rootDocId = rootDocId
  114. if (data.clsiServerId) {
  115. this.clsiServerId = data.clsiServerId
  116. }
  117. this.setData(data)
  118. } catch (error) {
  119. debugConsole.error(error)
  120. this.cleanupCompileResult()
  121. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  122. } finally {
  123. this.setCompiling(false)
  124. }
  125. }
  126. // parse the text of the current doc in the editor
  127. // if it contains "\documentclass" then use this as the root doc
  128. getRootDocOverrideId() {
  129. // only override when not in the root doc itself
  130. if (this.currentDoc && this.currentDoc.doc_id !== this.projectRootDocId) {
  131. const snapshot = this.currentDoc.getSnapshot()
  132. if (snapshot && isMainFile(snapshot)) {
  133. return this.currentDoc.doc_id
  134. }
  135. }
  136. return null
  137. }
  138. // build the query parameters added to post-compile requests
  139. buildPostCompileParams() {
  140. const params = new URLSearchParams()
  141. // the id of the CLSI server that processed the previous compile request
  142. if (this.clsiServerId) {
  143. params.set('clsiserverid', this.clsiServerId)
  144. }
  145. return params
  146. }
  147. // build the query parameters for the compile request
  148. buildCompileParams(options) {
  149. const params = new URLSearchParams()
  150. // note: no clsiserverid query param is set on "compile" requests,
  151. // as this is added in the backend by the web api
  152. // tell the server whether this is an automatic or manual compile request
  153. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  154. params.set('auto_compile', 'true')
  155. }
  156. // use the feature flag to enable PDF caching
  157. if (enablePdfCaching) {
  158. params.set('enable_pdf_caching', 'true')
  159. }
  160. // use the feature flag to enable "file line errors"
  161. if (searchParams.get('file_line_errors') === 'true') {
  162. params.file_line_errors = 'true'
  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. debugConsole.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. debugConsole.error(error)
  189. this.setError('clear-cache')
  190. })
  191. }
  192. setOption(option, value) {
  193. this.defaultOptions[option] = value
  194. }
  195. }