compiler.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { isMainFile } from './editor-files'
  2. import getMeta from '../../../utils/meta'
  3. import { deleteJSON, postJSON } from '../../../infrastructure/fetch-json'
  4. import { debounce, DebouncedFunc } 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. import { Dispatch, SetStateAction } from 'react'
  10. import { OpenDocuments } from '@/features/ide-react/editor/open-documents'
  11. import { DocumentContainer } from '@/features/ide-react/editor/document-container'
  12. import { CompileOptions, CompileResponseData } from '@ol-types/compile'
  13. import { DeliveryLatencies } from './types'
  14. const AUTO_COMPILE_MAX_WAIT = 5000
  15. // We add a 2 second debounce to sending user changes to server if they aren't
  16. // collaborating with anyone. This needs to be higher than SINGLE_USER_FLUSH_DELAY, and allow for
  17. // client to server latency, otherwise we compile before the op reaches the server
  18. // and then again on ack.
  19. const AUTO_COMPILE_DEBOUNCE = 2500
  20. // If there is a pending op, wait for it to be saved before compiling
  21. const PENDING_OP_MAX_WAIT = 10000
  22. const searchParams = new URLSearchParams(window.location.search)
  23. export default class DocumentCompiler {
  24. compilingRef: React.MutableRefObject<boolean>
  25. projectId: string
  26. setChangedAt: Dispatch<SetStateAction<number>>
  27. setCompiling: Dispatch<SetStateAction<boolean>>
  28. setData: Dispatch<SetStateAction<CompileResponseData | undefined>>
  29. setFirstRenderDone: Dispatch<SetStateAction<() => void>>
  30. setDeliveryLatencies: Dispatch<SetStateAction<DeliveryLatencies>>
  31. setError: Dispatch<SetStateAction<string | undefined>>
  32. cleanupCompileResult: () => void
  33. signal: AbortSignal
  34. openDocs: OpenDocuments
  35. projectRootDocId?: string | null
  36. clsiServerId: string | null
  37. currentDoc: DocumentContainer | null
  38. error: Error | undefined
  39. timer: number
  40. defaultOptions: CompileOptions
  41. debouncedAutoCompile: DebouncedFunc<() => void>
  42. constructor({
  43. compilingRef,
  44. projectId,
  45. setChangedAt,
  46. setCompiling,
  47. setData,
  48. setFirstRenderDone,
  49. setDeliveryLatencies,
  50. setError,
  51. cleanupCompileResult,
  52. signal,
  53. openDocs,
  54. }: {
  55. compilingRef: React.MutableRefObject<boolean>
  56. projectId: string
  57. setChangedAt: Dispatch<SetStateAction<number>>
  58. setCompiling: Dispatch<SetStateAction<boolean>>
  59. setData: Dispatch<SetStateAction<CompileResponseData | undefined>>
  60. setFirstRenderDone: Dispatch<SetStateAction<() => void>>
  61. setDeliveryLatencies: Dispatch<SetStateAction<DeliveryLatencies>>
  62. setError: Dispatch<SetStateAction<string | undefined>>
  63. cleanupCompileResult: () => void
  64. signal: AbortSignal
  65. openDocs: OpenDocuments
  66. }) {
  67. this.compilingRef = compilingRef
  68. this.projectId = projectId
  69. this.setChangedAt = setChangedAt
  70. this.setCompiling = setCompiling
  71. this.setData = setData
  72. this.setFirstRenderDone = setFirstRenderDone
  73. this.setDeliveryLatencies = setDeliveryLatencies
  74. this.setError = setError
  75. this.cleanupCompileResult = cleanupCompileResult
  76. this.signal = signal
  77. this.openDocs = openDocs
  78. this.projectRootDocId = null
  79. this.clsiServerId = null
  80. this.currentDoc = null
  81. this.error = undefined
  82. this.timer = 0
  83. this.defaultOptions = {
  84. draft: false,
  85. stopOnFirstError: false,
  86. }
  87. this.debouncedAutoCompile = debounce(
  88. () => {
  89. this.compile({ isAutoCompileOnChange: true })
  90. },
  91. AUTO_COMPILE_DEBOUNCE,
  92. {
  93. maxWait: AUTO_COMPILE_MAX_WAIT,
  94. }
  95. )
  96. }
  97. // The main "compile" function.
  98. // Call this directly to run a compile now, otherwise call debouncedAutoCompile.
  99. async compile(options: CompileOptions = {}) {
  100. options = { ...this.defaultOptions, ...options }
  101. if (options.isAutoCompileOnLoad && getMeta('ol-preventCompileOnLoad')) {
  102. return
  103. }
  104. // set "compiling" to true (in the React component's state), and return if it was already true
  105. const wasCompiling = this.compilingRef.current
  106. this.setCompiling(true)
  107. if (wasCompiling) {
  108. if (options.isAutoCompileOnChange) {
  109. this.debouncedAutoCompile()
  110. }
  111. return
  112. }
  113. try {
  114. await this.openDocs.awaitBufferedOps(
  115. signalWithTimeout(this.signal, PENDING_OP_MAX_WAIT)
  116. )
  117. // reset values
  118. this.setChangedAt(0) // TODO: wait for doc:saved?
  119. const params = this.buildCompileParams(options)
  120. const t0 = performance.now()
  121. const rootDocId = this.getRootDocOverrideId()
  122. const body = {
  123. rootDoc_id: rootDocId,
  124. draft: options.draft,
  125. check: 'silent', // NOTE: 'error' and 'validate' are possible, but unused
  126. // use incremental compile for all users but revert to a full compile
  127. // if there was previously a server error
  128. incrementalCompilesEnabled: !this.error,
  129. stopOnFirstError: options.stopOnFirstError,
  130. editorId: EDITOR_SESSION_ID,
  131. }
  132. const data: CompileResponseData = await postJSON(
  133. `/project/${this.projectId}/compile?${params}`,
  134. { body, signal: this.signal }
  135. )
  136. const compileTimeClientE2E = Math.ceil(performance.now() - t0)
  137. const { deliveryLatencies, firstRenderDone } = trackPdfDownload(
  138. data,
  139. compileTimeClientE2E,
  140. t0
  141. )
  142. this.setDeliveryLatencies(() => deliveryLatencies)
  143. this.setFirstRenderDone(() => firstRenderDone)
  144. // unset the error before it's set again later, so that components are recreated and events are tracked
  145. this.setError(undefined)
  146. data.options = options
  147. data.rootDocId = rootDocId
  148. if (data.clsiServerId) {
  149. this.clsiServerId = data.clsiServerId
  150. }
  151. this.setData(data)
  152. } catch (error: any) {
  153. debugConsole.error(error)
  154. this.cleanupCompileResult()
  155. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  156. } finally {
  157. this.setCompiling(false)
  158. }
  159. }
  160. // parse the text of the current doc in the editor
  161. // if it contains "\documentclass" then use this as the root doc
  162. getRootDocOverrideId() {
  163. // only override when not in the root doc itself
  164. if (this.currentDoc && this.currentDoc.doc_id !== this.projectRootDocId) {
  165. const snapshot = this.currentDoc.getSnapshot()
  166. if (snapshot && isMainFile(snapshot)) {
  167. return this.currentDoc.doc_id
  168. }
  169. }
  170. return null
  171. }
  172. // build the query parameters added to post-compile requests
  173. buildPostCompileParams() {
  174. const params = new URLSearchParams()
  175. // the id of the CLSI server that processed the previous compile request
  176. if (this.clsiServerId) {
  177. params.set('clsiserverid', this.clsiServerId)
  178. }
  179. return params
  180. }
  181. // build the query parameters for the compile request
  182. buildCompileParams(options: CompileOptions) {
  183. const params = new URLSearchParams()
  184. // note: no clsiserverid query param is set on "compile" requests,
  185. // as this is added in the backend by the web api
  186. // tell the server whether this is an automatic or manual compile request
  187. if (options.isAutoCompileOnLoad || options.isAutoCompileOnChange) {
  188. params.set('auto_compile', 'true')
  189. }
  190. // use the feature flag to enable PDF caching
  191. if (enablePdfCaching) {
  192. params.set('enable_pdf_caching', 'true')
  193. }
  194. // use the feature flag to enable "file line errors"
  195. if (searchParams.get('file_line_errors') === 'true') {
  196. params.set('file_line_errors', 'true')
  197. }
  198. return params
  199. }
  200. // send a request to stop the current compile
  201. stopCompile() {
  202. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  203. // and doesn't matter if it runs twice.
  204. const params = this.buildPostCompileParams()
  205. return postJSON(`/project/${this.projectId}/compile/stop?${params}`, {
  206. signal: this.signal,
  207. })
  208. .catch(error => {
  209. debugConsole.error(error)
  210. this.setError('error')
  211. })
  212. .finally(() => {
  213. this.setCompiling(false)
  214. })
  215. }
  216. // send a request to clear the cache
  217. clearCache() {
  218. const params = this.buildPostCompileParams()
  219. return deleteJSON(`/project/${this.projectId}/output?${params}`, {
  220. signal: this.signal,
  221. }).catch(error => {
  222. debugConsole.error(error)
  223. this.setError('clear-cache')
  224. })
  225. }
  226. setOption<Key extends keyof CompileOptions>(
  227. option: Key,
  228. value: CompileOptions[Key]
  229. ) {
  230. this.defaultOptions[option] = value
  231. }
  232. }