ContentCacheManager.js 7.1 KB

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