compiler.js 7.5 KB

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