ContentCacheManager.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. /**
  2. * ContentCacheManager - maintains a cache of stream hashes from a PDF file
  3. */
  4. const { callbackify } = require('util')
  5. const fs = require('fs')
  6. const crypto = require('crypto')
  7. const Path = require('path')
  8. const Settings = require('settings-sharelatex')
  9. const MIN_CHUNK_SIZE = Settings.pdfCachingMinChunkSize
  10. const START_OF_STREAM_MARKER = 'stream'
  11. const END_OF_STREAM_MARKER = 'endstream'
  12. const START_OF_STREAM_MARKER_LENGTH = START_OF_STREAM_MARKER.length
  13. const END_OF_STREAM_MARKER_LENGTH = END_OF_STREAM_MARKER.length
  14. /**
  15. *
  16. * @param {String} contentDir path to directory where content hash files are cached
  17. * @param {String} filePath the pdf file to scan for streams
  18. */
  19. async function update(contentDir, filePath) {
  20. const stream = fs.createReadStream(filePath)
  21. const extractor = new PdfStreamsExtractor()
  22. const ranges = []
  23. const newRanges = []
  24. for await (const chunk of stream) {
  25. const pdfStreams = extractor.consume(chunk)
  26. for (const pdfStream of pdfStreams) {
  27. if (pdfStream.end - pdfStream.start < MIN_CHUNK_SIZE) continue
  28. const hash = pdfStreamHash(pdfStream.buffers)
  29. const range = { start: pdfStream.start, end: pdfStream.end, hash }
  30. ranges.push(range)
  31. if (await writePdfStream(contentDir, hash, pdfStream.buffers)) {
  32. newRanges.push(range)
  33. }
  34. }
  35. }
  36. return [ranges, newRanges]
  37. }
  38. class PdfStreamsExtractor {
  39. constructor() {
  40. this.fileIndex = 0
  41. this.inStream = false
  42. this.streamStartIndex = 0
  43. this.buffers = []
  44. this.lastChunk = Buffer.alloc(0)
  45. }
  46. consume(chunk) {
  47. let chunkIndex = 0
  48. const pdfStreams = []
  49. chunk = Buffer.concat([this.lastChunk, chunk])
  50. while (true) {
  51. if (!this.inStream) {
  52. // Not in a stream, look for stream start
  53. const index = chunk.indexOf(START_OF_STREAM_MARKER, chunkIndex)
  54. if (index === -1) {
  55. // Couldn't find stream start
  56. break
  57. }
  58. // Found stream start, start a stream
  59. this.inStream = true
  60. this.streamStartIndex = this.fileIndex + index
  61. chunkIndex = index
  62. } else {
  63. // In a stream, look for stream end
  64. const index = chunk.indexOf(END_OF_STREAM_MARKER, chunkIndex)
  65. if (index === -1) {
  66. break
  67. }
  68. // add "endstream" part
  69. const endIndex = index + END_OF_STREAM_MARKER_LENGTH
  70. this.buffers.push(chunk.slice(chunkIndex, endIndex))
  71. pdfStreams.push({
  72. start: this.streamStartIndex,
  73. end: this.fileIndex + endIndex,
  74. buffers: this.buffers
  75. })
  76. this.inStream = false
  77. this.buffers = []
  78. chunkIndex = endIndex
  79. }
  80. }
  81. const remaining = chunk.length - chunkIndex
  82. const nextMarkerLength = this.inStream
  83. ? END_OF_STREAM_MARKER_LENGTH
  84. : START_OF_STREAM_MARKER_LENGTH
  85. if (remaining > nextMarkerLength) {
  86. const retainMarkerSection = chunk.length - nextMarkerLength
  87. if (this.inStream) {
  88. this.buffers.push(chunk.slice(chunkIndex, retainMarkerSection))
  89. }
  90. this.lastChunk = chunk.slice(retainMarkerSection)
  91. this.fileIndex += retainMarkerSection
  92. } else {
  93. this.lastChunk = chunk.slice(chunkIndex)
  94. this.fileIndex += chunkIndex
  95. }
  96. return pdfStreams
  97. }
  98. }
  99. function pdfStreamHash(buffers) {
  100. const hash = crypto.createHash('sha256')
  101. for (const buffer of buffers) {
  102. hash.update(buffer)
  103. }
  104. return hash.digest('hex')
  105. }
  106. async function writePdfStream(dir, hash, buffers) {
  107. const filename = Path.join(dir, hash)
  108. try {
  109. await fs.promises.stat(filename)
  110. // The file exists. Do not rewrite the content.
  111. // It would change the modified-time of the file and hence invalidate the
  112. // ETags used for client side caching via browser internals.
  113. return false
  114. } catch (e) {}
  115. const atomicWriteFilename = filename + '~'
  116. const file = await fs.promises.open(atomicWriteFilename, 'w')
  117. if (Settings.enablePdfCachingDark) {
  118. // Write an empty file in dark mode.
  119. buffers = []
  120. }
  121. try {
  122. try {
  123. for (const buffer of buffers) {
  124. await file.write(buffer)
  125. }
  126. } finally {
  127. await file.close()
  128. }
  129. await fs.promises.rename(atomicWriteFilename, filename)
  130. } catch (err) {
  131. try {
  132. await fs.promises.unlink(atomicWriteFilename)
  133. } catch (_) {
  134. throw err
  135. }
  136. }
  137. return true
  138. }
  139. module.exports = {
  140. HASH_REGEX: /^[0-9a-f]{64}$/,
  141. update: callbackify(update)
  142. }