2021-05-13 09:07:54 -04:00
|
|
|
/**
|
|
|
|
* ContentCacheManager - maintains a cache of stream hashes from a PDF file
|
|
|
|
*/
|
|
|
|
|
|
|
|
const { callbackify } = require('util')
|
|
|
|
const fs = require('fs')
|
|
|
|
const crypto = require('crypto')
|
|
|
|
const Path = require('path')
|
2021-07-12 12:47:21 -04:00
|
|
|
const Settings = require('@overleaf/settings')
|
2021-05-31 04:20:25 -04:00
|
|
|
const OError = require('@overleaf/o-error')
|
2021-05-18 13:06:15 -04:00
|
|
|
const pLimit = require('p-limit')
|
2021-05-31 04:20:25 -04:00
|
|
|
const { parseXrefTable } = require('../lib/pdfjs/parseXrefTable')
|
2021-06-23 09:14:28 -04:00
|
|
|
const { TimedOutError } = require('./Errors')
|
2021-05-17 09:07:37 -04:00
|
|
|
|
2021-05-13 09:07:54 -04:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {String} contentDir path to directory where content hash files are cached
|
|
|
|
* @param {String} filePath the pdf file to scan for streams
|
2021-05-31 04:20:25 -04:00
|
|
|
* @param {number} size the pdf size
|
2021-06-23 09:14:28 -04:00
|
|
|
* @param {number} compileTime
|
2021-05-13 09:07:54 -04:00
|
|
|
*/
|
2021-06-23 09:14:28 -04:00
|
|
|
async function update(contentDir, filePath, size, compileTime) {
|
|
|
|
const checkDeadline = getDeadlineChecker(compileTime)
|
2021-05-13 09:07:54 -04:00
|
|
|
const ranges = []
|
|
|
|
const newRanges = []
|
2021-05-18 11:25:24 -04:00
|
|
|
// keep track of hashes expire old ones when they reach a generation > N.
|
2021-05-18 13:06:15 -04:00
|
|
|
const tracker = await HashFileTracker.from(contentDir)
|
2021-05-18 13:15:58 -04:00
|
|
|
tracker.updateAge()
|
|
|
|
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after init HashFileTracker')
|
|
|
|
|
|
|
|
const rawTable = await parseXrefTable(filePath, size, checkDeadline)
|
2021-05-31 04:20:25 -04:00
|
|
|
rawTable.sort((a, b) => {
|
|
|
|
return a.offset - b.offset
|
|
|
|
})
|
|
|
|
rawTable.forEach((obj, idx) => {
|
|
|
|
obj.idx = idx
|
|
|
|
})
|
|
|
|
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after parsing')
|
|
|
|
|
2021-05-31 04:20:25 -04:00
|
|
|
const uncompressedObjects = []
|
|
|
|
for (const object of rawTable) {
|
|
|
|
if (!object.uncompressed) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
const nextObject = rawTable[object.idx + 1]
|
|
|
|
if (!nextObject) {
|
|
|
|
// Ignore this possible edge case.
|
|
|
|
// The last object should be part of the xRef table.
|
|
|
|
continue
|
|
|
|
} else {
|
|
|
|
object.endOffset = nextObject.offset
|
|
|
|
}
|
|
|
|
const size = object.endOffset - object.offset
|
|
|
|
object.size = size
|
|
|
|
if (size < Settings.pdfCachingMinChunkSize) {
|
|
|
|
continue
|
|
|
|
}
|
2021-06-23 09:14:28 -04:00
|
|
|
uncompressedObjects.push({ object, idx: uncompressedObjects.length })
|
2021-05-31 04:20:25 -04:00
|
|
|
}
|
2021-05-18 04:50:13 -04:00
|
|
|
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after finding uncompressed')
|
|
|
|
|
2021-05-31 04:20:25 -04:00
|
|
|
const handle = await fs.promises.open(filePath)
|
|
|
|
try {
|
2021-06-23 09:14:28 -04:00
|
|
|
for (const { object, idx } of uncompressedObjects) {
|
2021-05-31 04:20:25 -04:00
|
|
|
let buffer = Buffer.alloc(object.size, 0)
|
|
|
|
const { bytesRead } = await handle.read(
|
|
|
|
buffer,
|
|
|
|
0,
|
|
|
|
object.size,
|
|
|
|
object.offset
|
|
|
|
)
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after read ' + idx)
|
2021-05-31 04:20:25 -04:00
|
|
|
if (bytesRead !== object.size) {
|
|
|
|
throw new OError('could not read full chunk', {
|
|
|
|
object,
|
2021-07-13 07:04:48 -04:00
|
|
|
bytesRead,
|
2021-05-31 04:20:25 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
const idxObj = buffer.indexOf('obj')
|
|
|
|
if (idxObj > 100) {
|
|
|
|
throw new OError('objectId is too large', {
|
|
|
|
object,
|
2021-07-13 07:04:48 -04:00
|
|
|
idxObj,
|
2021-05-31 04:20:25 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
const objectIdRaw = buffer.subarray(0, idxObj)
|
|
|
|
buffer = buffer.subarray(objectIdRaw.byteLength)
|
|
|
|
|
|
|
|
const hash = pdfStreamHash(buffer)
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after hash ' + idx)
|
2021-05-31 04:20:25 -04:00
|
|
|
const range = {
|
|
|
|
objectId: objectIdRaw.toString(),
|
|
|
|
start: object.offset + objectIdRaw.byteLength,
|
|
|
|
end: object.endOffset,
|
2021-07-13 07:04:48 -04:00
|
|
|
hash,
|
2021-05-31 04:20:25 -04:00
|
|
|
}
|
2021-05-13 09:07:54 -04:00
|
|
|
ranges.push(range)
|
2021-05-18 04:50:13 -04:00
|
|
|
|
|
|
|
// Optimization: Skip writing of duplicate streams.
|
2021-05-18 13:15:58 -04:00
|
|
|
if (tracker.track(range)) continue
|
2021-05-18 04:50:13 -04:00
|
|
|
|
2021-05-31 04:20:25 -04:00
|
|
|
await writePdfStream(contentDir, hash, buffer)
|
2021-06-23 09:14:28 -04:00
|
|
|
checkDeadline('after write ' + idx)
|
2021-05-18 13:15:58 -04:00
|
|
|
newRanges.push(range)
|
2021-05-13 09:07:54 -04:00
|
|
|
}
|
2021-05-31 04:20:25 -04:00
|
|
|
} finally {
|
|
|
|
await handle.close()
|
2021-05-13 09:07:54 -04:00
|
|
|
}
|
2021-05-31 04:20:25 -04:00
|
|
|
|
2021-06-23 09:14:28 -04:00
|
|
|
// NOTE: Bailing out below does not make sense.
|
|
|
|
// Let the next compile use the already written ranges.
|
2021-05-18 13:06:15 -04:00
|
|
|
const reclaimedSpace = await tracker.deleteStaleHashes(5)
|
|
|
|
await tracker.flush()
|
|
|
|
return [ranges, newRanges, reclaimedSpace]
|
|
|
|
}
|
|
|
|
|
|
|
|
function getStatePath(contentDir) {
|
|
|
|
return Path.join(contentDir, '.state.v0.json')
|
2021-05-13 09:07:54 -04:00
|
|
|
}
|
|
|
|
|
2021-05-18 11:25:24 -04:00
|
|
|
class HashFileTracker {
|
2021-05-18 13:06:15 -04:00
|
|
|
constructor(contentDir, { hashAge = [], hashSize = [] }) {
|
|
|
|
this.contentDir = contentDir
|
|
|
|
this.hashAge = new Map(hashAge)
|
|
|
|
this.hashSize = new Map(hashSize)
|
|
|
|
}
|
|
|
|
|
|
|
|
static async from(contentDir) {
|
|
|
|
const statePath = getStatePath(contentDir)
|
|
|
|
let state = {}
|
|
|
|
try {
|
|
|
|
const blob = await fs.promises.readFile(statePath)
|
|
|
|
state = JSON.parse(blob)
|
|
|
|
} catch (e) {}
|
|
|
|
return new HashFileTracker(contentDir, state)
|
2021-05-18 11:25:24 -04:00
|
|
|
}
|
|
|
|
|
2021-05-18 13:15:58 -04:00
|
|
|
track(range) {
|
|
|
|
const exists = this.hashAge.has(range.hash)
|
|
|
|
if (!exists) {
|
|
|
|
this.hashSize.set(range.hash, range.end - range.start)
|
|
|
|
}
|
|
|
|
this.hashAge.set(range.hash, 0)
|
|
|
|
return exists
|
|
|
|
}
|
|
|
|
|
|
|
|
updateAge() {
|
2021-05-18 11:25:24 -04:00
|
|
|
for (const [hash, age] of this.hashAge) {
|
|
|
|
this.hashAge.set(hash, age + 1)
|
|
|
|
}
|
2021-05-18 13:06:15 -04:00
|
|
|
return this
|
2021-05-18 11:25:24 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
findStale(maxAge) {
|
2021-05-18 13:06:15 -04:00
|
|
|
const stale = []
|
2021-05-18 11:25:24 -04:00
|
|
|
for (const [hash, age] of this.hashAge) {
|
|
|
|
if (age > maxAge) {
|
|
|
|
stale.push(hash)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return stale
|
|
|
|
}
|
|
|
|
|
2021-05-18 13:06:15 -04:00
|
|
|
async flush() {
|
|
|
|
const statePath = getStatePath(this.contentDir)
|
|
|
|
const blob = JSON.stringify({
|
|
|
|
hashAge: Array.from(this.hashAge.entries()),
|
2021-07-13 07:04:48 -04:00
|
|
|
hashSize: Array.from(this.hashSize.entries()),
|
2021-05-18 13:06:15 -04:00
|
|
|
})
|
|
|
|
const atomicWrite = statePath + '~'
|
|
|
|
try {
|
|
|
|
await fs.promises.writeFile(atomicWrite, blob)
|
|
|
|
} catch (err) {
|
|
|
|
try {
|
|
|
|
await fs.promises.unlink(atomicWrite)
|
|
|
|
} catch (e) {}
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
await fs.promises.rename(atomicWrite, statePath)
|
|
|
|
} catch (err) {
|
|
|
|
try {
|
|
|
|
await fs.promises.unlink(atomicWrite)
|
|
|
|
} catch (e) {}
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async deleteStaleHashes(n) {
|
|
|
|
// delete any hash file older than N generations
|
|
|
|
const hashes = this.findStale(n)
|
2021-05-18 11:25:24 -04:00
|
|
|
|
2021-05-18 13:06:15 -04:00
|
|
|
let reclaimedSpace = 0
|
|
|
|
if (hashes.length === 0) {
|
|
|
|
return reclaimedSpace
|
|
|
|
}
|
2021-05-18 11:25:24 -04:00
|
|
|
|
2021-07-13 07:04:48 -04:00
|
|
|
await promiseMapWithLimit(10, hashes, async hash => {
|
2021-05-18 13:06:15 -04:00
|
|
|
await fs.promises.unlink(Path.join(this.contentDir, hash))
|
|
|
|
this.hashAge.delete(hash)
|
|
|
|
reclaimedSpace += this.hashSize.get(hash)
|
|
|
|
this.hashSize.delete(hash)
|
|
|
|
})
|
|
|
|
return reclaimedSpace
|
|
|
|
}
|
2021-05-18 11:25:24 -04:00
|
|
|
}
|
|
|
|
|
2021-05-31 04:20:25 -04:00
|
|
|
function pdfStreamHash(buffer) {
|
2021-05-13 09:07:54 -04:00
|
|
|
const hash = crypto.createHash('sha256')
|
2021-05-31 04:20:25 -04:00
|
|
|
hash.update(buffer)
|
2021-05-13 09:07:54 -04:00
|
|
|
return hash.digest('hex')
|
|
|
|
}
|
|
|
|
|
2021-05-31 04:20:25 -04:00
|
|
|
async function writePdfStream(dir, hash, buffer) {
|
2021-05-13 09:07:54 -04:00
|
|
|
const filename = Path.join(dir, hash)
|
2021-05-17 09:18:07 -04:00
|
|
|
const atomicWriteFilename = filename + '~'
|
2021-05-13 09:07:54 -04:00
|
|
|
if (Settings.enablePdfCachingDark) {
|
|
|
|
// Write an empty file in dark mode.
|
2021-05-31 04:20:25 -04:00
|
|
|
buffer = Buffer.alloc(0)
|
2021-05-13 09:07:54 -04:00
|
|
|
}
|
|
|
|
try {
|
2021-05-31 04:20:25 -04:00
|
|
|
await fs.promises.writeFile(atomicWriteFilename, buffer)
|
2021-05-17 09:18:07 -04:00
|
|
|
await fs.promises.rename(atomicWriteFilename, filename)
|
|
|
|
} catch (err) {
|
|
|
|
try {
|
|
|
|
await fs.promises.unlink(atomicWriteFilename)
|
|
|
|
} catch (_) {
|
|
|
|
throw err
|
2021-05-13 09:07:54 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-23 09:14:28 -04:00
|
|
|
function getDeadlineChecker(compileTime) {
|
|
|
|
const maxOverhead = Math.min(
|
2021-06-23 09:42:39 -04:00
|
|
|
// Adding 10s to a 40s compile time is OK.
|
|
|
|
// Adding 1s to a 3s compile time is OK.
|
|
|
|
Math.max(compileTime / 4, 1000),
|
2021-06-23 09:14:28 -04:00
|
|
|
// Adding 30s to a 120s compile time is not OK, limit to 10s.
|
|
|
|
Settings.pdfCachingMaxProcessingTime
|
|
|
|
)
|
|
|
|
|
|
|
|
const deadline = Date.now() + maxOverhead
|
|
|
|
let lastStage = { stage: 'start', now: Date.now() }
|
2021-06-23 09:42:39 -04:00
|
|
|
let completedStages = 0
|
2021-06-23 09:14:28 -04:00
|
|
|
return function (stage) {
|
|
|
|
const now = Date.now()
|
|
|
|
if (now > deadline) {
|
|
|
|
throw new TimedOutError(stage, {
|
2021-06-23 09:42:39 -04:00
|
|
|
completedStages,
|
2021-06-23 09:14:28 -04:00
|
|
|
lastStage: lastStage.stage,
|
2021-07-13 07:04:48 -04:00
|
|
|
diffToLastStage: now - lastStage.now,
|
2021-06-23 09:14:28 -04:00
|
|
|
})
|
|
|
|
}
|
2021-06-23 09:42:39 -04:00
|
|
|
completedStages++
|
2021-06-23 09:14:28 -04:00
|
|
|
lastStage = { stage, now }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-18 13:06:15 -04:00
|
|
|
function promiseMapWithLimit(concurrency, array, fn) {
|
|
|
|
const limit = pLimit(concurrency)
|
2021-07-13 07:04:48 -04:00
|
|
|
return Promise.all(array.map(x => limit(() => fn(x))))
|
2021-05-18 13:06:15 -04:00
|
|
|
}
|
|
|
|
|
2021-05-13 09:56:15 -04:00
|
|
|
module.exports = {
|
|
|
|
HASH_REGEX: /^[0-9a-f]{64}$/,
|
2021-05-31 04:20:25 -04:00
|
|
|
update: callbackify(update),
|
|
|
|
promises: {
|
2021-07-13 07:04:48 -04:00
|
|
|
update,
|
|
|
|
},
|
2021-05-13 09:56:15 -04:00
|
|
|
}
|