ContentCacheManager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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 rawTable = await parseXrefTable(filePath, size, checkDeadline)
  115. rawTable.sort((a, b) => {
  116. return a.offset - b.offset
  117. })
  118. rawTable.forEach((obj, idx) => {
  119. obj.idx = idx
  120. })
  121. checkDeadline('after parsing')
  122. const uncompressedObjects = []
  123. for (const object of rawTable) {
  124. if (!object.uncompressed) {
  125. continue
  126. }
  127. const nextObject = rawTable[object.idx + 1]
  128. if (!nextObject) {
  129. // Ignore this possible edge case.
  130. // The last object should be part of the xRef table.
  131. continue
  132. } else {
  133. object.endOffset = nextObject.offset
  134. }
  135. const size = object.endOffset - object.offset
  136. object.size = size
  137. if (size < Settings.pdfCachingMinChunkSize) {
  138. continue
  139. }
  140. uncompressedObjects.push({ object, idx: uncompressedObjects.length })
  141. }
  142. checkDeadline('after finding uncompressed')
  143. const handle = await fs.promises.open(filePath)
  144. try {
  145. for (const { object, idx } of uncompressedObjects) {
  146. let buffer = Buffer.alloc(object.size, 0)
  147. const { bytesRead } = await handle.read(
  148. buffer,
  149. 0,
  150. object.size,
  151. object.offset
  152. )
  153. checkDeadline('after read ' + idx)
  154. if (bytesRead !== object.size) {
  155. throw new OError('could not read full chunk', {
  156. object,
  157. bytesRead,
  158. })
  159. }
  160. const idxObj = buffer.indexOf('obj')
  161. if (idxObj > 100) {
  162. throw new OError('objectId is too large', {
  163. object,
  164. idxObj,
  165. })
  166. }
  167. const objectIdRaw = buffer.subarray(0, idxObj)
  168. buffer = buffer.subarray(objectIdRaw.byteLength)
  169. const hash = pdfStreamHash(buffer)
  170. checkDeadline('after hash ' + idx)
  171. const range = {
  172. objectId: objectIdRaw.toString(),
  173. start: object.offset + objectIdRaw.byteLength,
  174. end: object.endOffset,
  175. hash,
  176. }
  177. ranges.push(range)
  178. // Optimization: Skip writing of duplicate streams.
  179. if (tracker.track(range)) continue
  180. await writePdfStream(contentDir, hash, buffer)
  181. checkDeadline('after write ' + idx)
  182. newRanges.push(range)
  183. }
  184. } finally {
  185. await handle.close()
  186. }
  187. // NOTE: Bailing out below does not make sense.
  188. // Let the next compile use the already written ranges.
  189. const reclaimedSpace = await tracker.deleteStaleHashes(5)
  190. await tracker.flush()
  191. return [ranges, newRanges, reclaimedSpace]
  192. }
  193. function getStatePath(contentDir) {
  194. return Path.join(contentDir, '.state.v0.json')
  195. }
  196. class HashFileTracker {
  197. constructor(contentDir, { hashAge = [], hashSize = [] }) {
  198. this.contentDir = contentDir
  199. this.hashAge = new Map(hashAge)
  200. this.hashSize = new Map(hashSize)
  201. }
  202. static async from(contentDir) {
  203. const statePath = getStatePath(contentDir)
  204. let state = {}
  205. try {
  206. const blob = await fs.promises.readFile(statePath)
  207. state = JSON.parse(blob)
  208. } catch (e) {}
  209. return new HashFileTracker(contentDir, state)
  210. }
  211. track(range) {
  212. const exists = this.hashAge.has(range.hash)
  213. if (!exists) {
  214. this.hashSize.set(range.hash, range.end - range.start)
  215. }
  216. this.hashAge.set(range.hash, 0)
  217. return exists
  218. }
  219. updateAge() {
  220. for (const [hash, age] of this.hashAge) {
  221. this.hashAge.set(hash, age + 1)
  222. }
  223. return this
  224. }
  225. findStale(maxAge) {
  226. const stale = []
  227. for (const [hash, age] of this.hashAge) {
  228. if (age > maxAge) {
  229. stale.push(hash)
  230. }
  231. }
  232. return stale
  233. }
  234. async flush() {
  235. const statePath = getStatePath(this.contentDir)
  236. const blob = JSON.stringify({
  237. hashAge: Array.from(this.hashAge.entries()),
  238. hashSize: Array.from(this.hashSize.entries()),
  239. })
  240. const atomicWrite = statePath + '~'
  241. try {
  242. await fs.promises.writeFile(atomicWrite, blob)
  243. } catch (err) {
  244. try {
  245. await fs.promises.unlink(atomicWrite)
  246. } catch (e) {}
  247. throw err
  248. }
  249. try {
  250. await fs.promises.rename(atomicWrite, statePath)
  251. } catch (err) {
  252. try {
  253. await fs.promises.unlink(atomicWrite)
  254. } catch (e) {}
  255. throw err
  256. }
  257. }
  258. async deleteStaleHashes(n) {
  259. // delete any hash file older than N generations
  260. const hashes = this.findStale(n)
  261. let reclaimedSpace = 0
  262. if (hashes.length === 0) {
  263. return reclaimedSpace
  264. }
  265. await promiseMapWithLimit(10, hashes, async hash => {
  266. await fs.promises.unlink(Path.join(this.contentDir, hash))
  267. this.hashAge.delete(hash)
  268. reclaimedSpace += this.hashSize.get(hash)
  269. this.hashSize.delete(hash)
  270. })
  271. return reclaimedSpace
  272. }
  273. }
  274. function pdfStreamHash(buffer) {
  275. const hash = crypto.createHash('sha256')
  276. hash.update(buffer)
  277. return hash.digest('hex')
  278. }
  279. async function writePdfStream(dir, hash, buffer) {
  280. const filename = Path.join(dir, hash)
  281. const atomicWriteFilename = filename + '~'
  282. if (Settings.enablePdfCachingDark) {
  283. // Write an empty file in dark mode.
  284. buffer = Buffer.alloc(0)
  285. }
  286. try {
  287. await fs.promises.writeFile(atomicWriteFilename, buffer)
  288. await fs.promises.rename(atomicWriteFilename, filename)
  289. } catch (err) {
  290. try {
  291. await fs.promises.unlink(atomicWriteFilename)
  292. } catch (_) {
  293. throw err
  294. }
  295. }
  296. }
  297. function getMaxOverhead(compileTime) {
  298. return Math.min(
  299. // Adding 10s to a 40s compile time is OK.
  300. // Adding 1s to a 3s compile time is OK.
  301. Math.max(compileTime / 4, 1000),
  302. // Adding 30s to a 120s compile time is not OK, limit to 10s.
  303. Settings.pdfCachingMaxProcessingTime
  304. )
  305. }
  306. function getDeadlineChecker(compileTime) {
  307. const maxOverhead = getMaxOverhead(compileTime)
  308. const deadline = Date.now() + maxOverhead
  309. let lastStage = { stage: 'start', now: Date.now() }
  310. let completedStages = 0
  311. return function (stage) {
  312. const now = Date.now()
  313. if (now > deadline) {
  314. throw new TimedOutError(stage, {
  315. completedStages,
  316. lastStage: lastStage.stage,
  317. diffToLastStage: now - lastStage.now,
  318. })
  319. }
  320. completedStages++
  321. lastStage = { stage, now }
  322. }
  323. }
  324. function promiseMapWithLimit(concurrency, array, fn) {
  325. const limit = pLimit(concurrency)
  326. return Promise.all(array.map(x => limit(() => fn(x))))
  327. }
  328. module.exports = {
  329. HASH_REGEX: /^[0-9a-f]{64}$/,
  330. update: callbackify(update),
  331. promises: {
  332. update,
  333. doUpdateInternalNoDeadline,
  334. },
  335. }