compiler.js 6.8 KB

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