Repository Public
1/** Where things live under ATLAS_DATA_DIR, how much room they take, and how much room is left. */2import { existsSync, statfsSync } from "node:fs";3import { readdir, stat } from "node:fs/promises";4import { join } from "node:path";5import { env } from "../lib/env";67export const paths = {8 get media() { return join(env.dataDir, "media"); }, // served, once the capsule that names a file is published9 get masters() { return join(env.dataDir, "masters"); }, // original uploads, by SHA-256 — never served, never modified10 get resources() { return join(env.dataDir, "resources"); }, // downloadable files, served through /telecharger under canDownload11 get uploads() { return join(env.dataDir, "uploads"); }, // chunks of uploads in progress12 get work() { return join(env.dataDir, "work"); }, // scratch space of the worker and of imports13 get backups() { return join(env.dataDir, "backups"); },14};1516export async function dirSize(dir: string): Promise<{ bytes: number; files: number }> {17 let bytes = 0, files = 0;18 const walk = async (d: string): Promise<void> => {19 for (const e of await readdir(d, { withFileTypes: true }).catch(() => [])) {20 if (e.isDirectory()) await walk(join(d, e.name));21 else if (e.isFile()) { const s = await stat(join(d, e.name)).catch(() => null); if (s) { bytes += s.size; files++; } }22 }23 };24 await walk(dir);25 return { bytes, files };26}2728export interface StorageUsage {29 parts: Record<"media" | "masters" | "resources" | "uploads" | "work" | "backups" | "database", { bytes: number; files: number }>;30 usedBytes: number; freeBytes: number | null; volumeBytes: number | null; quotaBytes: number;31 /** ok · warning (≥ 80 % of the budget, or less free space than ATLAS_MIN_FREE_GB) · critical (≥ 95 %, or less than a quarter of that) */32 level: "ok" | "warning" | "critical"; message: string | null;33}34type G = typeof globalThis & { __atlasUsage?: { key: string; at: number; value: StorageUsage } };3536export function freeSpace(): { free: number; total: number } | null {37 try { const s = statfsSync(existsSync(env.dataDir) ? env.dataDir : join(env.dataDir, "..")); return { free: Number(s.bavail) * Number(s.bsize), total: Number(s.blocks) * Number(s.bsize) }; } catch { return null; }38}3940/** Walks the data directory. Cached for 30 s: the dashboard and every upload ask for it. */41export async function storageUsage(fresh = false): Promise<StorageUsage> {42 const g = globalThis as G;43 if (!fresh && g.__atlasUsage?.key === env.dataDir && Date.now() - g.__atlasUsage.at < 30_000) return g.__atlasUsage.value;44 const names = ["media", "masters", "resources", "uploads", "work", "backups"] as const;45 const sizes = await Promise.all(names.map((n) => dirSize(paths[n])));46 let dbBytes = 0, dbFiles = 0;47 for (const f of ["atlas.db", "atlas.db-wal", "atlas.db-shm"]) { const s = await stat(join(/* turbopackIgnore: true */ env.dataDir, f)).catch(() => null); if (s) { dbBytes += s.size; dbFiles++; } }48 const parts = { ...Object.fromEntries(names.map((n, i) => [n, sizes[i]!])), database: { bytes: dbBytes, files: dbFiles } } as StorageUsage["parts"];49 const usedBytes = Object.values(parts).reduce((a, p) => a + p.bytes, 0), fs = freeSpace(), quota = env.quotaBytes;50 // Free space is judged in absolute terms (a nearly full 2 TB disk still has room for a course), the budget as a share.51 const ratioQuota = quota ? usedBytes / quota : 0, free = fs?.free ?? Infinity, floor = env.minFreeBytes;52 const level: StorageUsage["level"] = ratioQuota >= 0.95 || free < floor / 4 ? "critical" : ratioQuota >= 0.8 || free < floor ? "warning" : "ok";53 const gb = (n: number) => `${(n / 1e9).toFixed(1).replace(".", ",")} Go`;54 const message = level === "ok" ? null : quota && ratioQuota >= 0.8 ? `Le stockage occupe ${gb(usedBytes)} sur les ${gb(quota)} prévus (${Math.round(ratioQuota * 100)} %).` : `Il ne reste que ${gb(fs?.free ?? 0)} libres sur le volume (seuil d'alerte : ${gb(floor)}).`;55 const value: StorageUsage = { parts, usedBytes, freeBytes: fs?.free ?? null, volumeBytes: fs?.total ?? null, quotaBytes: quota, level, message };56 g.__atlasUsage = { key: env.dataDir, at: Date.now(), value };57 return value;58}5960/** Whether `bytes` more can be stored, leaving `factor` times that amount free (a master needs room for its renditions too). */61export async function roomFor(bytes: number, factor = 1): Promise<{ ok: boolean; reason: string | null }> {62 const u = await storageUsage();63 if (u.quotaBytes && u.usedBytes + bytes > u.quotaBytes) return { ok: false, reason: "Le budget de stockage du studio serait dépassé. Libérez de l'espace ou augmentez ATLAS_QUOTA_GB." };64 if (u.freeBytes !== null && u.freeBytes < bytes * factor + 500_000_000) return { ok: false, reason: "Il ne reste pas assez d'espace libre sur le volume pour ce fichier et son traitement." };65 return { ok: true, reason: null };66}67