compiler.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. import getMeta from '../../../utils/meta'
  2. import { deleteJSON, postJSON } from '../../../infrastructure/fetch-json'
  3. import { debounce, DebouncedFunc } from 'lodash'
  4. import { EDITOR_SESSION_ID, trackPdfDownload } from './metrics'
  5. import { enablePdfCaching } from './pdf-caching-flags'
  6. import { debugConsole } from '@/utils/debugging'
  7. import { signalWithTimeout } from '@/utils/abort-signal'
  8. import { Dispatch, SetStateAction } from 'react'
  9. import { OpenDocuments } from '@/features/ide-react/editor/open-documents'
  10. import { CompileOptions, CompileResponseData } from '@ol-types/compile'
  11. import { DeliveryLatencies } from './types'
  12. import { RootDocInfo } from '@/shared/hooks/use-root-doc'
  13. const AUTO_COMPILE_MAX_WAIT = 5000
  14. // We add a 2 second debounce to sending user changes to server if they aren't
  15. // collaborating with anyone. This needs to be higher than SINGLE_USER_FLUSH_DELAY, and allow for
  16. // client to server latency, otherwise we compile before the op reaches the server
  17. // and then again on ack.
  18. const AUTO_COMPILE_DEBOUNCE = 2500
  19. // If there is a pending op, wait for it to be saved before compiling
  20. const PENDING_OP_MAX_WAIT = 10000
  21. const searchParams = new URLSearchParams(window.location.search)
  22. export default class DocumentCompiler {
  23. compilingRef: React.MutableRefObject<boolean>
  24. projectId: string
  25. setChangedAt: Dispatch<SetStateAction<number>>
  26. setCompiling: Dispatch<SetStateAction<boolean>>
  27. setData: Dispatch<SetStateAction<CompileResponseData | undefined>>
  28. setFirstRenderDone: Dispatch<SetStateAction<() => void>>
  29. setDeliveryLatencies: Dispatch<SetStateAction<DeliveryLatencies>>
  30. setError: Dispatch<SetStateAction<string | undefined>>
  31. cleanupCompileResult: () => void
  32. signal: AbortSignal
  33. openDocs: OpenDocuments
  34. clsiServerId: string | null
  35. error: Error | undefined
  36. timer: number
  37. defaultOptions: CompileOptions
  38. debouncedAutoCompile: DebouncedFunc<() => void>
  39. getRootDocInfo: () => RootDocInfo
  40. constructor({
  41. compilingRef,
  42. projectId,
  43. setChangedAt,
  44. setCompiling,
  45. setData,
  46. setFirstRenderDone,
  47. setDeliveryLatencies,
  48. setError,
  49. cleanupCompileResult,
  50. signal,
  51. openDocs,
  52. getRootDocInfo,
  53. }: {
  54. compilingRef: React.MutableRefObject<boolean>
  55. projectId: string
  56. setChangedAt: Dispatch<SetStateAction<number>>
  57. setCompiling: Dispatch<SetStateAction<boolean>>
  58. setData: Dispatch<SetStateAction<CompileResponseData | undefined>>
  59. setFirstRenderDone: Dispatch<SetStateAction<() => void>>
  60. setDeliveryLatencies: Dispatch<SetStateAction<DeliveryLatencies>>
  61. setError: Dispatch<SetStateAction<string | undefined>>
  62. cleanupCompileResult: () => void
  63. signal: AbortSignal
  64. openDocs: OpenDocuments
  65. getRootDocInfo: () => RootDocInfo
  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.getRootDocInfo = getRootDocInfo
  79. this.clsiServerId = null
  80. this.error = undefined
  81. this.timer = 0
  82. this.defaultOptions = {
  83. draft: false,
  84. stopOnFirstError: false,
  85. }
  86. this.debouncedAutoCompile = debounce(
  87. () => {
  88. this.compile({ isAutoCompileOnChange: true })
  89. },
  90. AUTO_COMPILE_DEBOUNCE,
  91. {
  92. maxWait: AUTO_COMPILE_MAX_WAIT,
  93. }
  94. )
  95. }
  96. // The main "compile" function.
  97. // Call this directly to run a compile now, otherwise call debouncedAutoCompile.
  98. async compile(options: CompileOptions = {}) {
  99. options = { ...this.defaultOptions, ...options }
  100. if (options.isAutoCompileOnLoad && getMeta('ol-preventCompileOnLoad')) {
  101. return
  102. }
  103. // set "compiling" to true (in the React component's state), and return if it was already true
  104. const wasCompiling = this.compilingRef.current
  105. this.setCompiling(true)
  106. if (wasCompiling) {
  107. if (options.isAutoCompileOnChange) {
  108. this.debouncedAutoCompile()
  109. }
  110. return
  111. }
  112. try {
  113. await this.openDocs.awaitBufferedOps(
  114. signalWithTimeout(this.signal, PENDING_OP_MAX_WAIT)
  115. )
  116. // reset values
  117. this.setChangedAt(0) // TODO: wait for doc:saved?
  118. const params = this.buildCompileParams(options)
  119. const t0 = performance.now()
  120. const { rootDocId, rootResourcePath } = this.getRootDocInfo()
  121. const body = {
  122. rootDoc_id: rootDocId,
  123. rootResourcePath,
  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 = {
  147. ...options,
  148. rootResourcePath,
  149. }
  150. data.rootDocId = rootDocId
  151. if (data.clsiServerId) {
  152. this.clsiServerId = data.clsiServerId
  153. }
  154. this.setData(data)
  155. } catch (error: any) {
  156. debugConsole.error(error)
  157. this.cleanupCompileResult()
  158. this.setError(error.info?.statusCode === 429 ? 'rate-limited' : 'error')
  159. } finally {
  160. this.setCompiling(false)
  161. }
  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: CompileOptions) {
  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.set('file_line_errors', 'true')
  188. }
  189. return params
  190. }
  191. // send a request to stop the current compile
  192. stopCompile() {
  193. // NOTE: no stoppingCompile state, as this should happen fairly quickly
  194. // and doesn't matter if it runs twice.
  195. const params = this.buildPostCompileParams()
  196. return postJSON(`/project/${this.projectId}/compile/stop?${params}`, {
  197. signal: this.signal,
  198. })
  199. .catch(error => {
  200. debugConsole.error(error)
  201. this.setError('error')
  202. })
  203. .finally(() => {
  204. this.setCompiling(false)
  205. })
  206. }
  207. // send a request to clear the cache
  208. clearCache() {
  209. const params = this.buildPostCompileParams()
  210. return deleteJSON(`/project/${this.projectId}/output?${params}`, {
  211. signal: this.signal,
  212. }).catch(error => {
  213. debugConsole.error(error)
  214. this.setError('clear-cache')
  215. })
  216. }
  217. setOption<Key extends keyof CompileOptions>(
  218. option: Key,
  219. value: CompileOptions[Key]
  220. ) {
  221. this.defaultOptions[option] = value
  222. }
  223. }