ContentCacheManager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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 { QueueLimitReachedError, TimedOutError } = require('./Errors')
  13. const workerpool = require('workerpool')
  14. const Metrics = require('@overleaf/metrics')
  15. let WORKER_POOL
  16. // NOTE: Check for main thread to avoid recursive start of pool.
  17. if (Settings.pdfCachingEnableWorkerPool && workerpool.isMainThread) {
  18. WORKER_POOL = workerpool.pool(Path.join(__dirname, 'ContentCacheWorker.js'), {
  19. // Cap number of worker threads.
  20. maxWorkers: Settings.pdfCachingWorkerPoolSize,
  21. // Warmup workers.
  22. minWorkers: Settings.pdfCachingWorkerPoolSize,
  23. // Limit queue back-log
  24. maxQueueSize: Settings.pdfCachingWorkerPoolBackLogLimit,
  25. })
  26. setInterval(() => {
  27. const {
  28. totalWorkers,
  29. busyWorkers,
  30. idleWorkers,
  31. pendingTasks,
  32. activeTasks,
  33. } = WORKER_POOL.stats()
  34. Metrics.gauge('pdf_caching_total_workers', totalWorkers)
  35. Metrics.gauge('pdf_caching_busy_workers', busyWorkers)
  36. Metrics.gauge('pdf_caching_idle_workers', idleWorkers)
  37. Metrics.gauge('pdf_caching_pending_tasks', pendingTasks)
  38. Metrics.gauge('pdf_caching_active_tasks', activeTasks)
  39. }, 15 * 1000)
  40. }
  41. /**
  42. *
  43. * @param {String} contentDir path to directory where content hash files are cached
  44. * @param {String} filePath the pdf file to scan for streams
  45. * @param {number} size the pdf size
  46. * @param {number} compileTime
  47. */
  48. async function update(contentDir, filePath, size, compileTime) {
  49. if (Settings.pdfCachingEnableWorkerPool) {
  50. return await updateOtherEventLoop(contentDir, filePath, size, compileTime)
  51. } else {
  52. return await updateSameEventLoop(contentDir, filePath, size, compileTime)
  53. }
  54. }
  55. /**
  56. *
  57. * @param {String} contentDir path to directory where content hash files are cached
  58. * @param {String} filePath the pdf file to scan for streams
  59. * @param {number} size the pdf size
  60. * @param {number} compileTime
  61. */
  62. async function updateOtherEventLoop(contentDir, filePath, size, compileTime) {
  63. const timeout = getMaxOverhead(compileTime)
  64. try {
  65. return await WORKER_POOL.exec('doUpdateInternalNoDeadline', [
  66. contentDir,
  67. filePath,
  68. size,
  69. ]).timeout(timeout)
  70. } catch (e) {
  71. if (e instanceof workerpool.Promise.TimeoutError) {
  72. throw new TimedOutError('context-lost-in-worker')
  73. }
  74. if (e.message.includes('Max queue size of ')) {
  75. throw new QueueLimitReachedError()
  76. }
  77. throw e
  78. }
  79. }
  80. /**
  81. *
  82. * @param {String} contentDir path to directory where content hash files are cached
  83. * @param {String} filePath the pdf file to scan for streams
  84. * @param {number} size the pdf size
  85. * @param {number} compileTime
  86. */
  87. async function updateSameEventLoop(contentDir, filePath, size, compileTime) {
  88. const checkDeadline = getDeadlineChecker(compileTime)
  89. return doUpdateInternal(contentDir, filePath, size, checkDeadline)
  90. }
  91. /**
  92. *
  93. * @param {String} contentDir path to directory where content hash files are cached
  94. * @param {String} filePath the pdf file to scan for streams
  95. * @param {number} size the pdf size
  96. */
  97. async function doUpdateInternalNoDeadline(contentDir, filePath, size) {
  98. return doUpdateInternal(contentDir, filePath, size, () => {})
  99. }
  100. /**
  101. *
  102. * @param {String} contentDir path to directory where content hash files are cached
  103. * @param {String} filePath the pdf file to scan for streams
  104. * @param {number} size the pdf size
  105. * @param {function} checkDeadline
  106. */
  107. async function doUpdateInternal(contentDir, filePath, size, checkDeadline) {
  108. const ranges = []
  109. const newRanges = []
  110. // keep track of hashes expire old ones when they reach a generation > N.
  111. const tracker = await HashFileTracker.from(contentDir)
  112. tracker.updateAge()
  113. checkDeadline('after init HashFileTracker')
  114. const { xRefEntries, startXRefTable } = await parseXrefTable(
  115. filePath,
  116. size,
  117. checkDeadline
  118. )
  119. xRefEntries.sort((a, b) => {
  120. return a.offset - b.offset
  121. })
  122. xRefEntries.forEach((obj, idx) => {
  123. obj.idx = idx
  124. })
  125. checkDeadline('after parsing')
  126. const uncompressedObjects = []
  127. for (const object of xRefEntries) {
  128. if (!object.uncompressed) {
  129. continue
  130. }
  131. const nextObject = xRefEntries[object.idx + 1]
  132. if (!nextObject) {
  133. // Ignore this possible edge case.
  134. // The last object should be part of the xRef table.
  135. continue
  136. } else {
  137. object.endOffset = nextObject.offset
  138. }
  139. const size = object.endOffset - object.offset
  140. object.size = size
  141. if (size < Settings.pdfCachingMinChunkSize) {
  142. continue
  143. }
  144. uncompressedObjects.push({ object, idx: uncompressedObjects.length })
  145. }
  146. checkDeadline('after finding uncompressed')
  147. const handle = await fs.promises.open(filePath)
  148. try {
  149. for (const { object, idx } of uncompressedObjects) {
  150. let buffer = Buffer.alloc(object.size, 0)
  151. const { bytesRead } = await handle.read(
  152. buffer,
  153. 0,
  154. object.size,
  155. object.offset
  156. )
  157. checkDeadline('after read ' + idx)
  158. if (bytesRead !== object.size) {
  159. throw new OError('could not read full chunk', {
  160. object,
  161. bytesRead,
  162. })
  163. }
  164. const idxObj = buffer.indexOf('obj')
  165. if (idxObj > 100) {
  166. throw new OError('objectId is too large', {
  167. object,
  168. idxObj,
  169. })
  170. }
  171. const objectIdRaw = buffer.subarray(0, idxObj)
  172. buffer = buffer.subarray(objectIdRaw.byteLength)
  173. const hash = pdfStreamHash(buffer)
  174. checkDeadline('after hash ' + idx)
  175. const range = {
  176. objectId: objectIdRaw.toString(),
  177. start: object.offset + objectIdRaw.byteLength,
  178. end: object.endOffset,
  179. hash,
  180. }
  181. ranges.push(range)
  182. // Optimization: Skip writing of duplicate streams.
  183. if (tracker.track(range)) continue
  184. await writePdfStream(contentDir, hash, buffer)
  185. checkDeadline('after write ' + idx)
  186. newRanges.push(range)
  187. }
  188. } finally {
  189. await handle.close()
  190. }
  191. // NOTE: Bailing out below does not make sense.
  192. // Let the next compile use the already written ranges.
  193. const reclaimedSpace = await tracker.deleteStaleHashes(5)
  194. await tracker.flush()
  195. return [ranges, newRanges, reclaimedSpace, startXRefTable]
  196. }
  197. function getStatePath(contentDir) {
  198. return Path.join(contentDir, '.state.v0.json')
  199. }
  200. class HashFileTracker {
  201. constructor(contentDir, { hashAge = [], hashSize = [] }) {
  202. this.contentDir = contentDir
  203. this.hashAge = new Map(hashAge)
  204. this.hashSize = new Map(hashSize)
  205. }
  206. static async from(contentDir) {
  207. const statePath = getStatePath(contentDir)
  208. let state = {}
  209. try {
  210. const blob = await fs.promises.readFile(statePath)
  211. state = JSON.parse(blob)
  212. } catch (e) {}
  213. return new HashFileTracker(contentDir, state)
  214. }
  215. track(range) {
  216. const exists = this.hashAge.has(range.hash)
  217. if (!exists) {
  218. this.hashSize.set(range.hash, range.end - range.start)
  219. }
  220. this.hashAge.set(range.hash, 0)
  221. return exists
  222. }
  223. updateAge() {
  224. for (const [hash, age] of this.hashAge) {
  225. this.hashAge.set(hash, age + 1)
  226. }
  227. return this
  228. }
  229. findStale(maxAge) {
  230. const stale = []
  231. for (const [hash, age] of this.hashAge) {
  232. if (age > maxAge) {
  233. stale.push(hash)
  234. }
  235. }
  236. return stale
  237. }
  238. async flush() {
  239. const statePath = getStatePath(this.contentDir)
  240. const blob = JSON.stringify({
  241. hashAge: Array.from(this.hashAge.entries()),
  242. hashSize: Array.from(this.hashSize.entries()),
  243. })
  244. const atomicWrite = statePath + '~'
  245. try {
  246. await fs.promises.writeFile(atomicWrite, blob)
  247. } catch (err) {
  248. try {
  249. await fs.promises.unlink(atomicWrite)
  250. } catch (e) {}
  251. throw err
  252. }
  253. try {
  254. await fs.promises.rename(atomicWrite, statePath)
  255. } catch (err) {
  256. try {
  257. await fs.promises.unlink(atomicWrite)
  258. } catch (e) {}
  259. throw err
  260. }
  261. }
  262. async deleteStaleHashes(n) {
  263. // delete any hash file older than N generations
  264. const hashes = this.findStale(n)
  265. let reclaimedSpace = 0
  266. if (hashes.length === 0) {
  267. return reclaimedSpace
  268. }
  269. await promiseMapWithLimit(10, hashes, async hash => {
  270. await fs.promises.unlink(Path.join(this.contentDir, hash))
  271. this.hashAge.delete(hash)
  272. reclaimedSpace += this.hashSize.get(hash)
  273. this.hashSize.delete(hash)
  274. })
  275. return reclaimedSpace
  276. }
  277. }
  278. function pdfStreamHash(buffer) {
  279. const hash = crypto.createHash('sha256')
  280. hash.update(buffer)
  281. return hash.digest('hex')
  282. }
  283. async function writePdfStream(dir, hash, buffer) {
  284. const filename = Path.join(dir, hash)
  285. const atomicWriteFilename = filename + '~'
  286. if (Settings.enablePdfCachingDark) {
  287. // Write an empty file in dark mode.
  288. buffer = Buffer.alloc(0)
  289. }
  290. try {
  291. await fs.promises.writeFile(atomicWriteFilename, buffer)
  292. await fs.promises.rename(atomicWriteFilename, filename)
  293. } catch (err) {
  294. try {
  295. await fs.promises.unlink(atomicWriteFilename)
  296. } catch (_) {
  297. throw err
  298. }
  299. }
  300. }
  301. function getMaxOverhead(compileTime) {
  302. return Math.min(
  303. // Adding 10s to a 40s compile time is OK.
  304. // Adding 1s to a 3s compile time is OK.
  305. Math.max(compileTime / 4, 1000),
  306. // Adding 30s to a 120s compile time is not OK, limit to 10s.
  307. Settings.pdfCachingMaxProcessingTime
  308. )
  309. }
  310. function getDeadlineChecker(compileTime) {
  311. const maxOverhead = getMaxOverhead(compileTime)
  312. const deadline = Date.now() + maxOverhead
  313. let lastStage = { stage: 'start', now: Date.now() }
  314. let completedStages = 0
  315. return function (stage) {
  316. const now = Date.now()
  317. if (now > deadline) {
  318. throw new TimedOutError(stage, {
  319. completedStages,
  320. lastStage: lastStage.stage,
  321. diffToLastStage: now - lastStage.now,
  322. })
  323. }
  324. completedStages++
  325. lastStage = { stage, now }
  326. }
  327. }
  328. function promiseMapWithLimit(concurrency, array, fn) {
  329. const limit = pLimit(concurrency)
  330. return Promise.all(array.map(x => limit(() => fn(x))))
  331. }
  332. module.exports = {
  333. HASH_REGEX: /^[0-9a-f]{64}$/,
  334. update: callbackify(update),
  335. promises: {
  336. update,
  337. doUpdateInternalNoDeadline,
  338. },
  339. }