ContentCacheManager.js 9.9 KB

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