output-files.ts 9.0 KB

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