ContentCacheManager.js 10 KB

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