Files
vitfit-r2/V2/app/core/storage.js
T
2026-06-13 08:03:45 -04:00

75 lines
1.9 KiB
JavaScript

'use strict';
const fs = require('fs');
const path = require('path');
const checkDiskSpace = require('check-disk-space').default;
const { AppError } = require('./errors');
const UPLOADS_DIR = () => process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads');
const WARN_BYTES = () => parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3), 10);
let cache = null;
let cacheTime = 0;
let inflightPromise = null;
async function getUploadsSize() {
const dir = UPLOADS_DIR();
let total = 0;
let count = 0;
try {
const files = fs.readdirSync(dir);
for (const f of files) {
try {
const stat = fs.statSync(path.join(dir, f));
if (stat.isFile()) { total += stat.size; count++; }
} catch {}
}
} catch {}
return { size: total, fileCount: count };
}
async function getStorageInfo() {
if (cache && Date.now() - cacheTime < 60_000) return cache;
if (inflightPromise) return inflightPromise;
inflightPromise = (async () => {
const [disk, uploads] = await Promise.all([
checkDiskSpace(UPLOADS_DIR()),
getUploadsSize(),
]);
const result = {
disk: {
total: disk.size,
used: disk.size - disk.free,
free: disk.free,
usedPercent: Math.round(((disk.size - disk.free) / disk.size) * 100),
},
uploads,
warning: disk.free < WARN_BYTES(),
warnThresholdBytes: WARN_BYTES(),
};
cache = result;
cacheTime = Date.now();
inflightPromise = null;
return result;
})();
return inflightPromise;
}
async function checkUploadAllowed(req, res, next) {
try {
const info = await getStorageInfo();
if (info.warning) {
return next(new AppError('STORAGE_INSUFFICIENT', 'Not enough disk space to upload. Contact your administrator.', 507));
}
next();
} catch (err) {
next(err);
}
}
module.exports = { getStorageInfo, checkUploadAllowed };