Spaces:
Configuration error
Configuration error
File size: 2,005 Bytes
03b405b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { getDb } = require("../config/db");
const { paths } = require("../config/paths");
const { nowIso } = require("../utils/time");
function getCached(inputHash, mode) {
const db = getDb();
const row = db.prepare("SELECT * FROM cache WHERE input_hash = ? AND mode = ?").get(inputHash, mode);
if (!row) return null;
// If we have a Telegram file_id, we can return a cache hit immediately even if files are not on disk!
if (row.file_id) {
db.prepare("UPDATE cache SET last_used_at = ? WHERE id = ?").run(nowIso(), row.id);
const files = row.output_paths ? JSON.parse(row.output_paths) : [];
return { ...row, outputPaths: files };
}
// Otherwise, we require local files to exist on disk
const files = row.output_paths ? JSON.parse(row.output_paths) : [];
if (files.length === 0 || !files.every((file) => fs.existsSync(file))) return null;
db.prepare("UPDATE cache SET last_used_at = ? WHERE id = ?").run(nowIso(), row.id);
return { ...row, outputPaths: files };
}
function saveCache({ inputHash, mode, fileId = null, outputPaths = [], sizeBefore = 0, sizeAfter = 0, duration = 0, platform = null, metadata = {} }) {
const db = getDb();
const id = crypto.randomUUID();
const now = nowIso();
db.prepare(`
INSERT OR REPLACE INTO cache
(id, input_hash, mode, file_id, output_paths, metadata, size_before, size_after, duration, platform, created_at, last_used_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
id,
inputHash,
mode,
fileId,
JSON.stringify(outputPaths),
JSON.stringify(metadata),
sizeBefore,
sizeAfter,
duration,
platform,
now,
now
);
}
function cachePathFor(hash, name) {
const dir = path.join(paths.cache, hash.slice(0, 2), hash);
fs.mkdirSync(dir, { recursive: true });
return path.join(dir, name);
}
module.exports = { getCached, saveCache, cachePathFor };
|