output-files.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import HumanReadableLogs from '../../../ide/human-readable-logs/HumanReadableLogs'
  2. import BibLogParser from '../../../ide/log-parser/bib-log-parser'
  3. import { enablePdfCaching } from './pdf-caching-flags'
  4. import { debugConsole } from '@/utils/debugging'
  5. import { dirname, findEntityByPath } from '@/features/file-tree/util/path'
  6. import '@/utils/readable-stream-async-iterator-polyfill'
  7. import { EDITOR_SESSION_ID } from '@/features/pdf-preview/util/metrics'
  8. // Warnings that may disappear after a second LaTeX pass
  9. const TRANSIENT_WARNING_REGEX = /^(Reference|Citation).+undefined on input line/
  10. const MAX_LOG_SIZE = 1024 * 1024 // 1MB
  11. const MAX_BIB_LOG_SIZE_PER_FILE = MAX_LOG_SIZE
  12. export function handleOutputFiles(outputFiles, projectId, data) {
  13. const outputFile = outputFiles.get('output.pdf')
  14. if (!outputFile) return null
  15. outputFile.editorId = outputFile.editorId || EDITOR_SESSION_ID
  16. // build the URL for viewing the PDF in the preview UI
  17. const params = new URLSearchParams()
  18. if (data.compileGroup) {
  19. params.set('compileGroup', data.compileGroup)
  20. }
  21. if (data.clsiServerId) {
  22. params.set('clsiserverid', data.clsiServerId)
  23. }
  24. if (enablePdfCaching) {
  25. // Tag traffic that uses the pdf caching logic.
  26. params.set('enable_pdf_caching', 'true')
  27. }
  28. outputFile.pdfUrl = `${buildURL(
  29. outputFile,
  30. data.pdfDownloadDomain
  31. )}?${params}`
  32. if (data.fromCache) {
  33. outputFile.pdfDownloadUrl = outputFile.downloadURL
  34. } else {
  35. // build the URL for downloading the PDF
  36. params.set('popupDownload', 'true') // save PDF download as file
  37. outputFile.pdfDownloadUrl = `/download/project/${projectId}/build/${outputFile.build}/output/output.pdf?${params}`
  38. }
  39. return outputFile
  40. }
  41. let nextEntryId = 1
  42. function generateEntryKey() {
  43. return 'compile-log-entry-' + nextEntryId++
  44. }
  45. export const handleLogFiles = async (outputFiles, data, signal) => {
  46. const result = {
  47. log: null,
  48. logEntries: {
  49. errors: [],
  50. warnings: [],
  51. typesetting: [],
  52. },
  53. }
  54. function accumulateResults(newEntries, type) {
  55. for (const key in result.logEntries) {
  56. if (newEntries[key]) {
  57. for (const entry of newEntries[key]) {
  58. if (type) {
  59. entry.type = newEntries.type
  60. }
  61. if (entry.file) {
  62. entry.file = normalizeFilePath(entry.file)
  63. }
  64. entry.key = generateEntryKey()
  65. }
  66. result.logEntries[key].push(...newEntries[key])
  67. }
  68. }
  69. }
  70. const logFile = outputFiles.get('output.log')
  71. if (logFile) {
  72. result.log = await fetchFileWithSizeLimit(
  73. buildURL(logFile, data.pdfDownloadDomain),
  74. signal,
  75. MAX_LOG_SIZE
  76. )
  77. try {
  78. let { errors, warnings, typesetting } = HumanReadableLogs.parse(
  79. result.log,
  80. {
  81. ignoreDuplicates: true,
  82. }
  83. )
  84. if (data.status === 'stopped-on-first-error') {
  85. // Hide warnings that could disappear after a second pass
  86. warnings = warnings.filter(warning => !isTransientWarning(warning))
  87. }
  88. accumulateResults({ errors, warnings, typesetting })
  89. } catch (e) {
  90. debugConsole.warn(e) // ignore failure to parse the log file, but log a warning
  91. }
  92. }
  93. const blgFiles = []
  94. for (const [filename, file] of outputFiles) {
  95. if (filename.endsWith('.blg')) {
  96. blgFiles.push(file)
  97. }
  98. }
  99. for (const blgFile of blgFiles) {
  100. const log = await fetchFileWithSizeLimit(
  101. buildURL(blgFile, data.pdfDownloadDomain),
  102. signal,
  103. MAX_BIB_LOG_SIZE_PER_FILE
  104. )
  105. try {
  106. const { errors, warnings } = new BibLogParser(log, {
  107. maxErrors: 100,
  108. }).parse()
  109. accumulateResults({ errors, warnings }, 'BibTeX:')
  110. } catch (e) {
  111. // BibLog parsing errors are ignored
  112. }
  113. }
  114. result.logEntries.all = [
  115. ...result.logEntries.errors,
  116. ...result.logEntries.warnings,
  117. ...result.logEntries.typesetting,
  118. ]
  119. return result
  120. }
  121. export function buildLogEntryAnnotations(entries, fileTreeData, rootDocId) {
  122. const rootDocDirname = dirname(fileTreeData, rootDocId)
  123. const logEntryAnnotations = {}
  124. const seenLine = {}
  125. for (const entry of entries) {
  126. if (entry.file) {
  127. entry.file = normalizeFilePath(entry.file, rootDocDirname)
  128. const entity = findEntityByPath(fileTreeData, entry.file)?.entity
  129. if (entity) {
  130. if (!(entity._id in logEntryAnnotations)) {
  131. logEntryAnnotations[entity._id] = []
  132. }
  133. const annotation = {
  134. id: entry.key,
  135. entryIndex: logEntryAnnotations[entity._id].length, // used for maintaining the order of items on the same line
  136. row: entry.line - 1,
  137. type: entry.level === 'error' ? 'error' : 'warning',
  138. text: entry.message,
  139. source: 'compile', // NOTE: this is used in Ace for filtering the annotations
  140. ruleId: entry.ruleId,
  141. command: entry.command,
  142. }
  143. // set firstOnLine for the first non-typesetting annotation on a line
  144. if (entry.level !== 'typesetting') {
  145. if (!seenLine[entry.line]) {
  146. annotation.firstOnLine = true
  147. seenLine[entry.line] = true
  148. }
  149. }
  150. logEntryAnnotations[entity._id].push(annotation)
  151. }
  152. }
  153. }
  154. return logEntryAnnotations
  155. }
  156. export const buildRuleCounts = (entries = []) => {
  157. const counts = {}
  158. for (const entry of entries) {
  159. const key = `${entry.level}_${entry.ruleId}`
  160. counts[key] = counts[key] ? counts[key] + 1 : 1
  161. }
  162. return counts
  163. }
  164. export const buildRuleDeltas = (ruleCounts, previousRuleCounts) => {
  165. const counts = {}
  166. // keys that are defined in the current log entries
  167. for (const [key, value] of Object.entries(ruleCounts)) {
  168. const previousValue = previousRuleCounts[key] ?? 0
  169. counts[`delta_${key}`] = value - previousValue
  170. }
  171. // keys that are no longer defined in the current log entries
  172. for (const [key, value] of Object.entries(previousRuleCounts)) {
  173. if (!(key in ruleCounts)) {
  174. counts[key] = 0
  175. counts[`delta_${key}`] = -value
  176. }
  177. }
  178. return counts
  179. }
  180. function buildURL(file, pdfDownloadDomain) {
  181. if (file.build && pdfDownloadDomain) {
  182. // Downloads from the compiles domain must include a build id.
  183. // The build id is used implicitly for access control.
  184. return `${pdfDownloadDomain}${file.url}`
  185. }
  186. // Go through web instead, which uses mongo for checking project access.
  187. return `${window.origin}${file.url}`
  188. }
  189. function normalizeFilePath(path, rootDocDirname) {
  190. path = path.replace(/\/\//g, '/')
  191. path = path.replace(
  192. /^.*\/compiles\/[0-9a-f]{24}(-[0-9a-f]{24})?\/(\.\/)?/,
  193. ''
  194. )
  195. path = path.replace(/^\/compile\//, '')
  196. if (rootDocDirname) {
  197. path = path.replace(/^\.\//, rootDocDirname + '/')
  198. }
  199. return path
  200. }
  201. function isTransientWarning(warning) {
  202. return TRANSIENT_WARNING_REGEX.test(warning.message)
  203. }
  204. async function fetchFileWithSizeLimit(url, signal, maxSize) {
  205. let result = ''
  206. try {
  207. const abortController = new AbortController()
  208. // abort fetching the log file if the main signal is aborted
  209. signal.addEventListener('abort', () => {
  210. abortController.abort()
  211. })
  212. const response = await fetch(url, {
  213. signal: abortController.signal,
  214. })
  215. if (!response.ok) {
  216. throw new Error('Failed to fetch log file')
  217. }
  218. const reader = response.body.pipeThrough(new TextDecoderStream())
  219. for await (const chunk of reader) {
  220. result += chunk
  221. if (result.length > maxSize) {
  222. abortController.abort()
  223. }
  224. }
  225. } catch (e) {
  226. debugConsole.warn(e) // ignore failure to fetch the log file, but log a warning
  227. }
  228. return result
  229. }