ContentCacheManager.js 3.5 KB

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