ContentCacheManager.js 4.5 KB

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