* fix(admin): make "Storage used" report storage used (#1164) The tile summed photos.size_bytes — the catalogued size of the ORIGINALS, which has no relationship to the disk PicPeak runs on. In reference mode those files are never copied and sit on the NAS; duplicate rows counted the same file twice (#1162); and it ignored everything PicPeak genuinely does write locally: thumbnails, previews, hero renditions, watermarks and the per-event download cache. The reporter's tile read ~80 GB against 21 GB of real usage. Worse than the label: the same number drove the storage soft-limit warning bar and, via /storage/info, the recommended soft limit — so a reference-mode install got a disk-capacity recommendation computed from bytes that are not on the disk. - new localStorageUsage service walks the storage root and reports the total plus a breakdown. Walking rather than summing DB columns is the point: thumbnail/preview/hero rows record a key and never a byte count, and orphans from a deleted event or an interrupted import are real bytes. Symlinks are not followed, so a link into the media mount cannot put the NAS back in the total. Cached for 5 minutes, since the dashboard polls. - the dashboard tile and /storage/info now report that, with the catalogued figure kept and labelled as such next to it. A failed measurement reads as "unavailable" rather than substituting a number that means something else. On the local rig: 64.37 MB used against 15.75 MB catalogued, of which 27.9 MB is watermarks and 6.8 MB is download cache — none of which the old figure could see. Not addressed here: `.download-cache/all.zip` still has no TTL or size cap. It is now at least visible in the breakdown, which is what makes the case for capping it. * fix(admin): exclude the media share from local storage usage (#1164) External review found the walk could reintroduce the exact over-count it replaces. EXTERNAL_MEDIA_ROOT's compose default is `<storage>/external-media`, where the NAS is bind-mounted. That is a plain directory, not a symlink, so the symlink guard did not cover it and the walk descended into the share — putting every referenced original back into a figure whose whole purpose is to leave them out, and comparing NAS bytes against statfs() of the local disk. On the reference-mode installs this issue is about, that is the failure mode reappearing inside its own fix. The configured root is now skipped when it lies inside the storage root, and the result reports which path was excluded. A directory that merely shares the name is still counted, because those really are local bytes. Also from the review: - concurrent cold-cache callers now share one walk. /dashboard/stats, /storage/info and the sidebar are routinely requested together, and each was starting its own stat-per-file traversal of the whole library. - storage_partial is surfaced in the StorageInfo type and the sidebar tile, not just the dashboard and analytics cards. An unreadable subtree makes the total a floor, and a floor silently compared against a soft limit reads as "safely under". * fix(admin): do not report a disk walk on an S3 backend (#1164) Second review round. S3 installs were regressed. With STORAGE_BACKEND=s3 the originals, renditions, archives and download caches are objects in the bucket and STORAGE_PATH holds only incidental local files — so the walk reported near-zero and the soft-limit recommendation was derived from it. Those installs now keep the catalogued figure, which is the approximation they had before this PR, and the response says which measurement it is (`storage_measurement: 'disk' | 'catalog'`) so the UI labels it instead of implying a disk measurement that never happened. The Settings → Status storage card ignored storage_partial, formatting a lower bound as exact and deriving the limit percentage from it — so an unreadable subtree could read as safely under the limit. It now carries the same `+` marker as the sidebar and dashboard. * fix(admin): stop rendering an absent measurement as zero usage (#1164) Third review round, two findings. The analytics storage bar coerced a null measurement to 0, drawing an empty bar labelled "0% of limit" and suppressing the over-limit state — reading as plenty of room at exactly the moment nothing is known. It now shows the catalogued figure on S3, where that IS the available answer, and says "no measurement available" rather than inventing a percentage when there is none. /storage/info walked the filesystem before checking the backend and then threw the result away on S3. The sidebar polls that endpoint, so a migrated install still holding a large local tree paid a full stat-per-file traversal on every cold cache for nothing. Gated before the walk, as the dashboard route already was. * fix(admin): tell "no disk to measure" apart from "the measurement failed" (#1164) External review of the stable twin. Both were reported as `storage_measurement: 'catalog'`, so a failed local walk made the dashboard claim the objects live in S3. They are different things — one is a fact about the install, the other is a fault — and there is now an `unavailable` state for the second. The analytics percentage could reach the billions. `safeSoftLimit` fell back to `storageUsed || 1`, and on S3 that is null → 1, while the figure beside it came from `catalogedBytes`. An editor or viewer holds `analytics.view` but not `settings.view`, so `/storage/info` 403s for them and `storageInfo` is undefined — which is exactly when that fallback fires. It now falls back to the measured figure, and suppresses the percentage entirely when there is no real limit rather than dividing usage by itself and always reading 100%. Also lands the AnalyticsPage half of the previous round, which the commit message claimed but the commit did not contain — only its backend counterpart was staged. The stable twin has carried it since it was written, so this is the parity gap in the unusual direction. --------- Co-authored-by: Paul Nothaft <[email protected]>
217 lines
7.7 KiB
JavaScript
217 lines
7.7 KiB
JavaScript
/**
|
|
* What PicPeak actually occupies on this machine (#1164).
|
|
*
|
|
* The dashboard's "Storage used" tile summed photos.size_bytes, which is the
|
|
* catalogued size of the ORIGINALS — a number with no relationship to the disk
|
|
* PicPeak runs on:
|
|
*
|
|
* - in reference mode the originals are never copied. Those bytes are on the
|
|
* NAS. The reporter's tile read ~80 GB against 21 GB of real local usage.
|
|
* - duplicate rows counted the same file twice (#1162).
|
|
* - it ignored everything PicPeak genuinely does write: thumbnails, previews,
|
|
* hero renditions, and the per-event download cache — an 11.8 GB
|
|
* `.download-cache/all.zip` sat outside the figure entirely.
|
|
*
|
|
* So the one number an admin reaches for when asking "am I running out of
|
|
* disk" pointed away from the answer and omitted exactly the things filling
|
|
* the disk. This walks the storage root instead and reports what is there.
|
|
*
|
|
* Walking rather than summing DB columns is deliberate: thumbnail/preview/hero
|
|
* rows record a key, never a byte count, and orphans (a deleted event's
|
|
* leftovers, an interrupted import's thumbnails) are real bytes on a real
|
|
* disk. A `du` is the only honest answer, and the only one that notices what
|
|
* PicPeak has forgotten about.
|
|
*
|
|
* The external media root is EXCLUDED, and that is the whole point rather than
|
|
* a detail. Its compose default is `<storage>/external-media`, where the NAS is
|
|
* bind-mounted — a plain directory, not a symlink — so walking it would add
|
|
* every referenced original back into a figure that exists to leave them out,
|
|
* and compare NAS bytes against statfs() of the local disk. That is the
|
|
* over-count this replaces, reintroduced by the fix for it.
|
|
*
|
|
* Cached, because it is one stat per file. On a large install that is seconds,
|
|
* and the dashboard is polled — and concurrent misses share one walk rather
|
|
* than each starting their own.
|
|
*/
|
|
|
|
const path = require('path');
|
|
const fsp = require('fs').promises;
|
|
const logger = require('../utils/logger');
|
|
const { getStoragePath } = require('../config/storage');
|
|
|
|
const TTL_MS = 5 * 60 * 1000;
|
|
|
|
let cache = null;
|
|
// The walk in flight, if any. Two admins loading the dashboard, or the sidebar
|
|
// and the storage tab on one page, hit the same cold cache and would otherwise
|
|
// each stat every file on the disk.
|
|
let inFlight = null;
|
|
|
|
/**
|
|
* The external media root, resolved, when it lies inside the storage root.
|
|
* Returns null when it is elsewhere (the usual production case) or cannot be
|
|
* resolved — nothing to exclude then.
|
|
*/
|
|
function nestedExternalRoot(storageRoot) {
|
|
let externalRoot;
|
|
try {
|
|
externalRoot = require('./externalMediaService').getExternalMediaRoot();
|
|
} catch (err) {
|
|
return null;
|
|
}
|
|
if (!externalRoot) return null;
|
|
const resolvedExternal = path.resolve(externalRoot);
|
|
const resolvedStorage = path.resolve(storageRoot);
|
|
if (resolvedExternal === resolvedStorage) return null;
|
|
return resolvedExternal.startsWith(resolvedStorage + path.sep) ? resolvedExternal : null;
|
|
}
|
|
|
|
/**
|
|
* Which line of the breakdown a path belongs to.
|
|
*
|
|
* The names are the ones the writers actually use — `heroes` from
|
|
* imageProcessor, `watermarks` from watermarkService, and so on — rather than
|
|
* the ones the layout docs imply. Getting one wrong is not a crash, it is a
|
|
* silent 30 MB in "other", which is the least useful place for it to land.
|
|
*
|
|
* `.download-cache` is the case that needs the explicit check: it lives INSIDE
|
|
* an event directory, so the naive rule files an 11.8 GB zip as photography —
|
|
* and it is the one bucket that is pure disposable cache, which makes it the
|
|
* one an admin most wants to see on its own.
|
|
*
|
|
* There is no external-media bucket: that subtree is not walked at all (see
|
|
* nestedExternalRoot). Those bytes live on the media share, and counting them
|
|
* is the exact over-count this measurement exists to end.
|
|
*/
|
|
function categorize(relPath) {
|
|
const segments = relPath.split(path.sep);
|
|
if (segments.includes('.download-cache')) return 'downloadCache';
|
|
switch (segments[0]) {
|
|
case 'thumbnails': return 'thumbnails';
|
|
case 'previews': return 'previews';
|
|
case 'heroes': return 'heroes';
|
|
case 'watermarks': return 'watermarks';
|
|
case 'uploads': return 'uploads';
|
|
case 'temp': return 'temp';
|
|
case 'business-docs': return 'businessDocs';
|
|
case 'events':
|
|
return segments[1] === 'archived' ? 'archives' : 'originals';
|
|
default:
|
|
return 'other';
|
|
}
|
|
}
|
|
|
|
const EMPTY_BREAKDOWN = () => ({
|
|
originals: 0,
|
|
archives: 0,
|
|
thumbnails: 0,
|
|
previews: 0,
|
|
heroes: 0,
|
|
watermarks: 0,
|
|
uploads: 0,
|
|
businessDocs: 0,
|
|
downloadCache: 0,
|
|
temp: 0,
|
|
other: 0,
|
|
});
|
|
|
|
async function walk(absDir, relDir, acc) {
|
|
// The media share, bind-mounted under the storage root. Walking it would put
|
|
// every referenced original back into a local-usage figure, and on a real
|
|
// NAS the traversal alone would take far longer than the measurement is
|
|
// worth.
|
|
if (acc.excludeRoot && path.resolve(absDir) === acc.excludeRoot) {
|
|
acc.excludedExternalRoot = acc.excludeRoot;
|
|
return;
|
|
}
|
|
|
|
let entries;
|
|
try {
|
|
entries = await fsp.readdir(absDir, { withFileTypes: true });
|
|
} catch (err) {
|
|
// A directory that is not there yet (a fresh install has no /previews) is
|
|
// not an error. Anything else is worth knowing about but must not abort
|
|
// the measurement — a partial number beats no number, and `partial` says
|
|
// so to the caller.
|
|
if (err.code !== 'ENOENT') {
|
|
acc.partial = true;
|
|
logger.debug?.(`localStorageUsage: skipped ${absDir}: ${err.message}`);
|
|
}
|
|
return;
|
|
}
|
|
|
|
for (const entry of entries) {
|
|
const abs = path.join(absDir, entry.name);
|
|
const rel = relDir ? path.join(relDir, entry.name) : entry.name;
|
|
// Symlinks are not followed: a link into the external media mount would
|
|
// otherwise add the NAS to the local total, which is the exact confusion
|
|
// this replaces.
|
|
if (entry.isDirectory()) {
|
|
await walk(abs, rel, acc);
|
|
} else if (entry.isFile()) {
|
|
try {
|
|
const stats = await fsp.stat(abs);
|
|
acc.total += stats.size;
|
|
acc.files += 1;
|
|
acc.breakdown[categorize(rel)] += stats.size;
|
|
} catch (err) {
|
|
// Raced with a delete, most likely. Nothing to add.
|
|
if (err.code !== 'ENOENT') acc.partial = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param {{ force?: boolean }} [opts] force skips the TTL cache.
|
|
* @returns {Promise<{total:number, files:number, breakdown:object, partial:boolean, measuredAt:string, root:string}>}
|
|
*/
|
|
async function measureLocalStorageUsage(opts = {}) {
|
|
const now = Date.now();
|
|
if (!opts.force && cache && now - cache.at < TTL_MS) return cache.value;
|
|
// Share a walk already underway rather than starting a second one.
|
|
if (!opts.force && inFlight) return inFlight;
|
|
|
|
inFlight = runMeasurement()
|
|
.then((value) => { cache = { at: Date.now(), value }; return value; })
|
|
.finally(() => { inFlight = null; });
|
|
return inFlight;
|
|
}
|
|
|
|
async function runMeasurement() {
|
|
|
|
const root = getStoragePath();
|
|
const acc = {
|
|
total: 0,
|
|
files: 0,
|
|
breakdown: EMPTY_BREAKDOWN(),
|
|
partial: false,
|
|
excludeRoot: nestedExternalRoot(root),
|
|
excludedExternalRoot: null,
|
|
};
|
|
await walk(root, '', acc);
|
|
|
|
return {
|
|
total: acc.total,
|
|
files: acc.files,
|
|
breakdown: acc.breakdown,
|
|
partial: acc.partial,
|
|
// Set when the media share sits inside the storage root and was skipped,
|
|
// so the UI can say why the figure is smaller than `du` would report.
|
|
excludedExternalRoot: acc.excludedExternalRoot,
|
|
measuredAt: new Date().toISOString(),
|
|
root,
|
|
};
|
|
}
|
|
|
|
/** Test seam — the TTL cache would otherwise outlive a temp storage root. */
|
|
function resetLocalStorageUsageCache() {
|
|
cache = null;
|
|
inFlight = null;
|
|
}
|
|
|
|
module.exports = {
|
|
measureLocalStorageUsage,
|
|
resetLocalStorageUsageCache,
|
|
};
|