Coverage for src/romfarmer/utils/storage_budget.py: 37%
99 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""Storage budget utilities.
3Handles parsing storage specifications like "512gb", "1tb" and computing
4usable storage after accounting for filesystem overhead and reserved space.
5"""
7import logging
8import re
9from dataclasses import dataclass
11logger = logging.getLogger(__name__)
13# Size unit multipliers (binary - 1GB = 1024^3 bytes)
14SIZE_UNITS = {
15 "b": 1,
16 "kb": 1024,
17 "mb": 1024**2,
18 "gb": 1024**3,
19 "tb": 1024**4,
20 "pb": 1024**5,
21}
23# Storage constants
24FILESYSTEM_OVERHEAD_FACTOR = 0.93 # ~7% lost to filesystem formatting
25DEFAULT_RESERVED_GB = 20 # Reserve for OS, saves, updates, etc.
28@dataclass
29class StorageBudget:
30 """Represents a parsed and computed storage budget.
32 Attributes:
33 raw_capacity_bytes: Advertised capacity in bytes (e.g., 512GB = 512*1024^3)
34 formatted_capacity_bytes: Usable after formatting (raw * 0.93)
35 reserved_bytes: Space reserved for system use
36 available_bytes: Actual available budget for ROMs
37 original_spec: Original specification string (e.g., "512gb")
38 """
40 raw_capacity_bytes: int
41 formatted_capacity_bytes: int
42 reserved_bytes: int
43 available_bytes: int
44 original_spec: str
46 @property
47 def available_gb(self) -> float:
48 """Available space in gigabytes."""
49 return self.available_bytes / SIZE_UNITS["gb"]
51 @property
52 def available_mb(self) -> int:
53 """Available space in megabytes (rounded down)."""
54 return int(self.available_bytes / SIZE_UNITS["mb"])
56 def __str__(self) -> str:
57 """Human-readable string representation."""
58 return (
59 f"StorageBudget({self.original_spec}): "
60 f"{self.available_gb:.1f}GB available "
61 f"(raw: {self.raw_capacity_bytes / SIZE_UNITS['gb']:.0f}GB, "
62 f"formatted: {self.formatted_capacity_bytes / SIZE_UNITS['gb']:.1f}GB, "
63 f"reserved: {self.reserved_bytes / SIZE_UNITS['gb']:.1f}GB)"
64 )
66 def is_unlimited(self) -> bool:
67 """Check if this represents unlimited storage."""
68 return self.original_spec.lower() == "unlimited"
71def parse_size_spec(spec: str) -> int:
72 """Parse a size specification to bytes.
74 Supports formats:
75 - "512gb", "512GB", "512 GB" - gigabytes
76 - "1tb", "1 TB" - terabytes
77 - "2048mb" - megabytes
78 - "123456789" - raw bytes
79 - "unlimited" - returns sys.maxsize
81 Args:
82 spec: Size specification string
84 Returns:
85 Size in bytes
87 Raises:
88 ValueError: If spec cannot be parsed
89 """
90 import sys
92 spec = spec.strip().lower()
94 # Special case: unlimited
95 if spec == "unlimited":
96 return sys.maxsize
98 # Try to parse with unit
99 match = re.match(r"^(\d+(?:\.\d+)?)\s*([a-z]+)?$", spec)
100 if not match:
101 raise ValueError(f"Cannot parse size spec: {spec}")
103 value_str, unit = match.groups()
104 value = float(value_str)
106 if unit is None:
107 # No unit = bytes
108 return int(value)
110 if unit not in SIZE_UNITS:
111 raise ValueError(f"Unknown size unit: {unit} (valid: {', '.join(SIZE_UNITS.keys())})")
113 return int(value * SIZE_UNITS[unit])
116def compute_storage_budget(
117 spec: str,
118 filesystem_overhead: float = FILESYSTEM_OVERHEAD_FACTOR,
119 reserved_gb: float = DEFAULT_RESERVED_GB,
120) -> StorageBudget:
121 """Compute available storage budget from a specification.
123 Takes into account:
124 1. Filesystem formatting overhead (~7% loss)
125 2. Reserved space for OS, saves, updates
127 Args:
128 spec: Size specification (e.g., "512gb", "1tb", "unlimited")
129 filesystem_overhead: Multiplier for formatted capacity (default 0.93)
130 reserved_gb: GB to reserve for system use (default 20)
132 Returns:
133 StorageBudget instance with computed values
135 Example:
136 >>> budget = compute_storage_budget("512gb")
137 >>> print(budget.available_gb) # ~456.16 GB
138 """
139 import sys
141 raw_bytes = parse_size_spec(spec)
143 # Handle unlimited case
144 if raw_bytes == sys.maxsize:
145 return StorageBudget(
146 raw_capacity_bytes=raw_bytes,
147 formatted_capacity_bytes=raw_bytes,
148 reserved_bytes=0,
149 available_bytes=raw_bytes,
150 original_spec=spec,
151 )
153 # Compute formatted capacity (after filesystem overhead)
154 formatted_bytes = int(raw_bytes * filesystem_overhead)
156 # Compute reserved space
157 reserved_bytes = int(reserved_gb * SIZE_UNITS["gb"])
159 # Compute available
160 available_bytes = max(0, formatted_bytes - reserved_bytes)
162 budget = StorageBudget(
163 raw_capacity_bytes=raw_bytes,
164 formatted_capacity_bytes=formatted_bytes,
165 reserved_bytes=reserved_bytes,
166 available_bytes=available_bytes,
167 original_spec=spec,
168 )
170 logger.debug(f"Computed storage budget: {budget}")
172 return budget
175def format_size(size_bytes: int, precision: int = 1) -> str:
176 """Format a byte size as human-readable string.
178 Args:
179 size_bytes: Size in bytes
180 precision: Decimal precision (default 1)
182 Returns:
183 Human-readable size string (e.g., "1.5 GB")
184 """
185 if size_bytes == 0:
186 return "0 B"
188 import sys
190 if size_bytes >= sys.maxsize:
191 return "unlimited"
193 for unit in ["B", "KB", "MB", "GB", "TB", "PB"]:
194 if abs(size_bytes) < 1024.0:
195 return f"{size_bytes:.{precision}f} {unit}"
196 size_bytes /= 1024.0
198 return f"{size_bytes:.{precision}f} PB"
201class BudgetTracker:
202 """Tracks storage budget usage during a build.
204 Provides methods to allocate and track space usage per platform.
205 """
207 def __init__(self, budget: StorageBudget):
208 """Initialize tracker with a storage budget.
210 Args:
211 budget: StorageBudget instance defining available space
212 """
213 self.budget = budget
214 self.allocations: dict[str, int] = {} # platform -> allocated bytes
215 self.actual_usage: dict[str, int] = {} # platform -> actual bytes used
217 @property
218 def total_allocated(self) -> int:
219 """Total bytes allocated so far."""
220 return sum(self.allocations.values())
222 @property
223 def total_used(self) -> int:
224 """Total bytes actually used so far."""
225 return sum(self.actual_usage.values())
227 @property
228 def remaining(self) -> int:
229 """Remaining available bytes."""
230 return self.budget.available_bytes - self.total_used
232 @property
233 def remaining_allocated(self) -> int:
234 """Remaining unallocated bytes."""
235 return self.budget.available_bytes - self.total_allocated
237 def can_allocate(self, size_bytes: int) -> bool:
238 """Check if size can be allocated within budget.
240 Args:
241 size_bytes: Size to check
243 Returns:
244 True if allocation would fit
245 """
246 if self.budget.is_unlimited():
247 return True
248 return (self.total_allocated + size_bytes) <= self.budget.available_bytes
250 def allocate(self, platform: str, size_bytes: int) -> bool:
251 """Allocate space for a platform.
253 Args:
254 platform: Platform name
255 size_bytes: Estimated size in bytes
257 Returns:
258 True if allocated, False if would exceed budget
259 """
260 if not self.can_allocate(size_bytes):
261 logger.warning(
262 f"Cannot allocate {format_size(size_bytes)} for {platform}: "
263 f"only {format_size(self.remaining_allocated)} remaining"
264 )
265 return False
267 self.allocations[platform] = size_bytes
268 logger.debug(f"Allocated {format_size(size_bytes)} for {platform}")
269 return True
271 def record_actual(self, platform: str, size_bytes: int):
272 """Record actual size used for a platform.
274 Args:
275 platform: Platform name
276 size_bytes: Actual size in bytes
277 """
278 self.actual_usage[platform] = size_bytes
280 # Log variance from allocation
281 if platform in self.allocations:
282 allocated = self.allocations[platform]
283 variance = size_bytes - allocated
284 variance_pct = (variance / allocated * 100) if allocated > 0 else 0
286 if abs(variance_pct) > 20:
287 logger.warning(
288 f"{platform}: actual {format_size(size_bytes)} vs "
289 f"allocated {format_size(allocated)} ({variance_pct:+.1f}%)"
290 )
292 def get_summary(self) -> dict:
293 """Get summary of budget usage.
295 Returns:
296 Dictionary with budget summary
297 """
298 return {
299 "total_budget": format_size(self.budget.available_bytes),
300 "total_allocated": format_size(self.total_allocated),
301 "total_used": format_size(self.total_used),
302 "remaining": format_size(self.remaining),
303 "platforms": len(self.actual_usage),
304 "utilization_pct": (
305 (self.total_used / self.budget.available_bytes * 100)
306 if not self.budget.is_unlimited()
307 else 0
308 ),
309 }