compiler.js 7.9 KB

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