ContentCacheManager.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 OError = require('@overleaf/o-error')
  10. const pLimit = require('p-limit')
  11. const { parseXrefTable } = require('../lib/pdfjs/parseXrefTable')
  12. /**
  13. *
  14. * @param {String} contentDir path to directory where content hash files are cached
  15. * @param {String} filePath the pdf file to scan for streams
  16. * @param {number} size the pdf size
  17. */
  18. async function update(contentDir, filePath, size) {
  19. const ranges = []
  20. const newRanges = []
  21. // keep track of hashes expire old ones when they reach a generation > N.
  22. const tracker = await HashFileTracker.from(contentDir)
  23. tracker.updateAge()
  24. const rawTable = await parseXrefTable(filePath, size)
  25. rawTable.sort((a, b) => {
  26. return a.offset - b.offset
  27. })
  28. rawTable.forEach((obj, idx) => {
  29. obj.idx = idx
  30. })
  31. const uncompressedObjects = []
  32. for (const object of rawTable) {
  33. if (!object.uncompressed) {
  34. continue
  35. }
  36. const nextObject = rawTable[object.idx + 1]
  37. if (!nextObject) {
  38. // Ignore this possible edge case.
  39. // The last object should be part of the xRef table.
  40. continue
  41. } else {
  42. object.endOffset = nextObject.offset
  43. }
  44. const size = object.endOffset - object.offset
  45. object.size = size
  46. if (size < Settings.pdfCachingMinChunkSize) {
  47. continue
  48. }
  49. uncompressedObjects.push(object)
  50. }
  51. const handle = await fs.promises.open(filePath)
  52. try {
  53. for (const object of uncompressedObjects) {
  54. let buffer = Buffer.alloc(object.size, 0)
  55. const { bytesRead } = await handle.read(
  56. buffer,
  57. 0,
  58. object.size,
  59. object.offset
  60. )
  61. if (bytesRead !== object.size) {
  62. throw new OError('could not read full chunk', {
  63. object,
  64. bytesRead
  65. })
  66. }
  67. const idxObj = buffer.indexOf('obj')
  68. if (idxObj > 100) {
  69. throw new OError('objectId is too large', {
  70. object,
  71. idxObj
  72. })
  73. }
  74. const objectIdRaw = buffer.subarray(0, idxObj)
  75. buffer = buffer.subarray(objectIdRaw.byteLength)
  76. const hash = pdfStreamHash(buffer)
  77. const range = {
  78. objectId: objectIdRaw.toString(),
  79. start: object.offset + objectIdRaw.byteLength,
  80. end: object.endOffset,
  81. hash
  82. }
  83. ranges.push(range)
  84. // Optimization: Skip writing of duplicate streams.
  85. if (tracker.track(range)) continue
  86. await writePdfStream(contentDir, hash, buffer)
  87. newRanges.push(range)
  88. }
  89. } finally {
  90. await handle.close()
  91. }
  92. const reclaimedSpace = await tracker.deleteStaleHashes(5)
  93. await tracker.flush()
  94. return [ranges, newRanges, reclaimedSpace]
  95. }
  96. function getStatePath(contentDir) {
  97. return Path.join(contentDir, '.state.v0.json')
  98. }
  99. class HashFileTracker {
  100. constructor(contentDir, { hashAge = [], hashSize = [] }) {
  101. this.contentDir = contentDir
  102. this.hashAge = new Map(hashAge)
  103. this.hashSize = new Map(hashSize)
  104. }
  105. static async from(contentDir) {
  106. const statePath = getStatePath(contentDir)
  107. let state = {}
  108. try {
  109. const blob = await fs.promises.readFile(statePath)
  110. state = JSON.parse(blob)
  111. } catch (e) {}
  112. return new HashFileTracker(contentDir, state)
  113. }
  114. track(range) {
  115. const exists = this.hashAge.has(range.hash)
  116. if (!exists) {
  117. this.hashSize.set(range.hash, range.end - range.start)
  118. }
  119. this.hashAge.set(range.hash, 0)
  120. return exists
  121. }
  122. updateAge() {
  123. for (const [hash, age] of this.hashAge) {
  124. this.hashAge.set(hash, age + 1)
  125. }
  126. return this
  127. }
  128. findStale(maxAge) {
  129. const stale = []
  130. for (const [hash, age] of this.hashAge) {
  131. if (age > maxAge) {
  132. stale.push(hash)
  133. }
  134. }
  135. return stale
  136. }
  137. async flush() {
  138. const statePath = getStatePath(this.contentDir)
  139. const blob = JSON.stringify({
  140. hashAge: Array.from(this.hashAge.entries()),
  141. hashSize: Array.from(this.hashSize.entries())
  142. })
  143. const atomicWrite = statePath + '~'
  144. try {
  145. await fs.promises.writeFile(atomicWrite, blob)
  146. } catch (err) {
  147. try {
  148. await fs.promises.unlink(atomicWrite)
  149. } catch (e) {}
  150. throw err
  151. }
  152. try {
  153. await fs.promises.rename(atomicWrite, statePath)
  154. } catch (err) {
  155. try {
  156. await fs.promises.unlink(atomicWrite)
  157. } catch (e) {}
  158. throw err
  159. }
  160. }
  161. async deleteStaleHashes(n) {
  162. // delete any hash file older than N generations
  163. const hashes = this.findStale(n)
  164. let reclaimedSpace = 0
  165. if (hashes.length === 0) {
  166. return reclaimedSpace
  167. }
  168. await promiseMapWithLimit(10, hashes, async (hash) => {
  169. await fs.promises.unlink(Path.join(this.contentDir, hash))
  170. this.hashAge.delete(hash)
  171. reclaimedSpace += this.hashSize.get(hash)
  172. this.hashSize.delete(hash)
  173. })
  174. return reclaimedSpace
  175. }
  176. }
  177. function pdfStreamHash(buffer) {
  178. const hash = crypto.createHash('sha256')
  179. hash.update(buffer)
  180. return hash.digest('hex')
  181. }
  182. async function writePdfStream(dir, hash, buffer) {
  183. const filename = Path.join(dir, hash)
  184. const atomicWriteFilename = filename + '~'
  185. if (Settings.enablePdfCachingDark) {
  186. // Write an empty file in dark mode.
  187. buffer = Buffer.alloc(0)
  188. }
  189. try {
  190. await fs.promises.writeFile(atomicWriteFilename, buffer)
  191. await fs.promises.rename(atomicWriteFilename, filename)
  192. } catch (err) {
  193. try {
  194. await fs.promises.unlink(atomicWriteFilename)
  195. } catch (_) {
  196. throw err
  197. }
  198. }
  199. }
  200. function promiseMapWithLimit(concurrency, array, fn) {
  201. const limit = pLimit(concurrency)
  202. return Promise.all(array.map((x) => limit(() => fn(x))))
  203. }
  204. module.exports = {
  205. HASH_REGEX: /^[0-9a-f]{64}$/,
  206. update: callbackify(update),
  207. promises: {
  208. update
  209. }
  210. }