Files
biliup-next/src/biliup_next/infra/storage_guard.py
2026-04-01 00:44:58 +08:00

42 lines
1.0 KiB
Python

from __future__ import annotations
import shutil
from pathlib import Path
from biliup_next.core.errors import ModuleError
def mb_to_bytes(value: object) -> int:
try:
number = int(value or 0)
except (TypeError, ValueError):
number = 0
return max(0, number) * 1024 * 1024
def free_bytes_for_path(path: Path) -> int:
target = path if path.exists() else path.parent
return int(shutil.disk_usage(target).free)
def ensure_free_space(
path: Path,
required_free_bytes: int,
*,
code: str,
message: str,
retryable: bool,
details: dict[str, object] | None = None,
) -> None:
free_bytes = free_bytes_for_path(path)
if free_bytes >= required_free_bytes:
return
payload = {
"path": str(path),
"required_free_bytes": int(required_free_bytes),
"available_free_bytes": int(free_bytes),
}
if details:
payload.update(details)
raise ModuleError(code=code, message=message, retryable=retryable, details=payload)