compiler.js 5.9 KB

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