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