Coverage for src/romfarmer/farmhand/models.py: 0%
176 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Pydantic models for Farm-Hand deployment system.
3Defines the data structures for target profiles, volume information,
4deployment plans, and transfer tracking.
5"""
7from __future__ import annotations
9import enum
10from datetime import datetime
12from pydantic import BaseModel, Field
14# ---------------------------------------------------------------------------
15# Enums
16# ---------------------------------------------------------------------------
19class VolumeRole(str, enum.Enum):
20 """Role assignment for a storage volume on the target."""
22 PRIMARY = "primary" # Default ROM storage (e.g., /userdata)
23 SECONDARY = "secondary" # Overflow/large platforms (e.g., ext HDD)
24 ARCHIVE = "archive" # Cold storage, rarely accessed
25 SYSTEM = "system" # OS / boot — not for ROMs
28class PlatformTier(str, enum.Enum):
29 """Size classification for a platform's full output."""
31 TINY = "tiny" # <1 GB — always include all
32 SMALL = "small" # 1–10 GB — always include all
33 MEDIUM = "medium" # 10–100 GB — include if space allows
34 LARGE = "large" # 100–500 GB — needs selection/budget
35 MASSIVE = "massive" # >500 GB — always needs aggressive selection
38class DeploymentStatus(str, enum.Enum):
39 """Status of a deployment operation."""
41 PENDING = "pending"
42 PLANNING = "planning"
43 BUILDING = "building"
44 TRANSFERRING = "transferring"
45 VERIFYING = "verifying"
46 COMPLETED = "completed"
47 FAILED = "failed"
48 CANCELLED = "cancelled"
51class SelectionAction(str, enum.Enum):
52 """What to do with a platform during deployment."""
54 INCLUDE_ALL = "include_all" # Deploy the full set
55 BUDGET_SELECT = "budget_select" # Use rating_budget strategy
56 CURATED_LIST = "curated_list" # Use a curated keep list
57 SKIP = "skip" # Do not deploy this platform
60# ---------------------------------------------------------------------------
61# Volume & System Info
62# ---------------------------------------------------------------------------
65class VolumeInfo(BaseModel):
66 """Information about a mounted storage volume on the target."""
68 mount_point: str = Field(description="Mount point path (e.g., /userdata)")
69 filesystem: str = Field(default="", description="Filesystem type (ext4, vfat, etc.)")
70 device: str = Field(default="", description="Block device (e.g., /dev/nvme0n1p2)")
71 total_bytes: int = Field(description="Total volume capacity in bytes")
72 used_bytes: int = Field(description="Used space in bytes")
73 available_bytes: int = Field(description="Available space in bytes")
74 use_percent: float = Field(description="Usage percentage (0-100)")
75 role: VolumeRole = Field(default=VolumeRole.SYSTEM, description="Assigned role")
76 rom_path: str | None = Field(
77 default=None,
78 description="Path where ROMs should go on this volume (e.g., /userdata/roms)",
79 )
81 @property
82 def available_gb(self) -> float:
83 return self.available_bytes / (1024**3)
85 @property
86 def total_gb(self) -> float:
87 return self.total_bytes / (1024**3)
89 @property
90 def used_gb(self) -> float:
91 return self.used_bytes / (1024**3)
94class SystemInfo(BaseModel):
95 """System information gathered from a remote target."""
97 hostname: str = ""
98 os_name: str = "" # e.g., "Batocera" or "RockNIX"
99 os_version: str = ""
100 architecture: str = ""
101 cpu_model: str = ""
102 cpu_cores: int = 0
103 cpu_threads: int = 0
104 memory_total_mb: int = 0
105 memory_available_mb: int = 0
106 display_resolution: str = ""
107 kernel_version: str = ""
110class TargetCapabilities(BaseModel):
111 """What the target system can do — discovered binaries and supported formats."""
113 binaries: list[str] = Field(default_factory=list, description="Available binaries on target")
114 emulators: list[str] = Field(
115 default_factory=list, description="Detected emulator cores/executables"
116 )
117 supported_formats: dict[str, list[str]] = Field(
118 default_factory=dict,
119 description="Per-platform supported file formats (e.g., {'psx': ['.chd', '.pbp']})",
120 )
121 has_7z: bool = Field(default=False, description="Whether 7z/7zr is available on target")
122 has_chdman: bool = Field(default=False, description="Whether chdman is available on target")
125# ---------------------------------------------------------------------------
126# Target Profile
127# ---------------------------------------------------------------------------
130class TargetProfile(BaseModel):
131 """Complete profile for a deployment target — persisted as YAML."""
133 name: str = Field(description="Human-readable target name (e.g., batocera-nuc-livingroom)")
134 host: str = Field(description="SSH host (IP or hostname)")
135 port: int = Field(default=22, description="SSH port")
136 user: str = Field(default="root", description="SSH username")
137 auth_method: str = Field(
138 default="password", description="Authentication method: password or key_file"
139 )
140 key_file: str | None = Field(default=None, description="Path to SSH private key")
141 frontend: str = Field(default="batocera", description="Frontend type (batocera, rocknix, etc.)")
142 device_type: str = Field(default="pc", description="Device type from rom-farmer targets")
144 # Discovered state (populated by analyzer)
145 system_info: SystemInfo | None = Field(default=None)
146 volumes: list[VolumeInfo] = Field(default_factory=list)
147 capabilities: TargetCapabilities | None = Field(default=None)
148 existing_roms: dict[str, list[str]] = Field(
149 default_factory=dict,
150 description="Platform -> list of ROM filenames already on target",
151 )
153 # Metadata
154 last_scanned: datetime | None = Field(default=None)
155 last_deployed: datetime | None = Field(default=None)
156 notes: str = Field(default="")
158 def get_rom_volumes(self) -> list[VolumeInfo]:
159 """Return volumes assigned to ROM storage (primary + secondary)."""
160 return [
161 v
162 for v in self.volumes
163 if v.role in (VolumeRole.PRIMARY, VolumeRole.SECONDARY) and v.rom_path
164 ]
166 def get_primary_volume(self) -> VolumeInfo | None:
167 """Return the primary ROM volume, if any."""
168 for v in self.volumes:
169 if v.role == VolumeRole.PRIMARY:
170 return v
171 return None
173 def total_available_bytes(self) -> int:
174 """Total available ROM storage across all ROM volumes."""
175 return sum(v.available_bytes for v in self.get_rom_volumes())
177 def total_available_gb(self) -> float:
178 return self.total_available_bytes() / (1024**3)
181# ---------------------------------------------------------------------------
182# Platform Allocation & Deployment Plan
183# ---------------------------------------------------------------------------
186class PlatformSizeInfo(BaseModel):
187 """Size data for a platform from rom-farmer's size_data.json."""
189 platform: str
190 compression: str = ""
191 full_set_bytes: int = 0
192 full_set_files: int = 0
193 tier: PlatformTier = PlatformTier.TINY
195 @property
196 def full_set_gb(self) -> float:
197 return self.full_set_bytes / (1024**3)
200class PlatformAllocation(BaseModel):
201 """Deployment decision for a single platform."""
203 platform: str = Field(description="Platform name (e.g., psx, nes, saturn)")
204 display_name: str = Field(default="", description="Human-readable name")
205 tier: PlatformTier = Field(description="Size classification")
206 action: SelectionAction = Field(description="What to do with this platform")
208 # Size info
209 full_set_bytes: int = Field(default=0, description="Size of full set from size_data")
210 allocated_bytes: int = Field(default=0, description="Budgeted size for this platform")
211 actual_bytes: int = Field(default=0, description="Actual deployed size (after transfer)")
213 # Volume assignment
214 target_volume: str = Field(default="", description="Mount point of target volume")
216 # Selection parameters (if action is BUDGET_SELECT)
217 selection_strategy: str = Field(default="", description="e.g., rating_budget")
218 selection_max_gb: float = Field(default=0, description="Budget in GB for selection")
219 selection_min_rating: float = Field(default=0, description="Minimum rating threshold")
220 selection_limit: int = Field(default=0, description="Max game count")
222 # Build config (if a custom build is needed)
223 build_config_name: str | None = Field(
224 default=None, description="Name of generated build config"
225 )
227 # Transfer state
228 files_total: int = Field(default=0)
229 files_transferred: int = Field(default=0)
230 bytes_transferred: int = Field(default=0)
232 @property
233 def allocated_gb(self) -> float:
234 return self.allocated_bytes / (1024**3)
236 @property
237 def full_set_gb(self) -> float:
238 return self.full_set_bytes / (1024**3)
241class DeploymentPlan(BaseModel):
242 """Complete deployment plan for a target — what goes where and how."""
244 target_name: str = Field(description="Target profile name")
245 created_at: datetime = Field(default_factory=datetime.now)
246 status: DeploymentStatus = Field(default=DeploymentStatus.PENDING)
248 # Budget
249 reserved_bytes: int = Field(
250 default=20 * 1024**3,
251 description="Space reserved for saves, BIOS, metadata, etc.",
252 )
253 total_available_bytes: int = Field(default=0, description="Total ROM-usable space on target")
255 # Per-volume breakdown
256 volume_allocations: dict[str, int] = Field(
257 default_factory=dict,
258 description="Mount point -> total bytes allocated to ROMs on that volume",
259 )
261 # Platform decisions
262 allocations: list[PlatformAllocation] = Field(
263 default_factory=list, description="Per-platform deployment decisions"
264 )
266 # Summary stats
267 platforms_included: int = Field(default=0)
268 platforms_skipped: int = Field(default=0)
269 total_allocated_bytes: int = Field(default=0)
270 total_estimated_files: int = Field(default=0)
272 # Build configs to generate (for platforms needing custom builds)
273 builds_needed: list[str] = Field(
274 default_factory=list,
275 description="Build config names that need to be created/run",
276 )
278 notes: list[str] = Field(
279 default_factory=list,
280 description="Human-readable plan notes and rationale",
281 )
283 @property
284 def total_allocated_gb(self) -> float:
285 return self.total_allocated_bytes / (1024**3)
287 @property
288 def total_available_gb(self) -> float:
289 return self.total_available_bytes / (1024**3)
291 @property
292 def headroom_bytes(self) -> int:
293 return self.total_available_bytes - self.total_allocated_bytes
295 @property
296 def headroom_gb(self) -> float:
297 return self.headroom_bytes / (1024**3)
299 def get_allocations_for_volume(self, mount_point: str) -> list[PlatformAllocation]:
300 """Get all platform allocations assigned to a specific volume."""
301 return [a for a in self.allocations if a.target_volume == mount_point]
303 def summary(self) -> str:
304 """Human-readable plan summary."""
305 lines = [
306 f"Deployment Plan for {self.target_name}",
307 f" Available: {self.total_available_gb:.1f} GB "
308 f"(reserved: {self.reserved_bytes / (1024**3):.0f} GB)",
309 f" Allocated: {self.total_allocated_gb:.1f} GB ({self.headroom_gb:.1f} GB headroom)",
310 f" Platforms: {self.platforms_included} included, {self.platforms_skipped} skipped",
311 f" Files: ~{self.total_estimated_files:,}",
312 ]
313 if self.builds_needed:
314 lines.append(f" Builds needed: {len(self.builds_needed)}")
315 return "\n".join(lines)
318# ---------------------------------------------------------------------------
319# Transfer Progress
320# ---------------------------------------------------------------------------
323class TransferProgress(BaseModel):
324 """Real-time transfer progress tracking."""
326 platform: str = ""
327 current_file: str = ""
328 files_total: int = 0
329 files_done: int = 0
330 bytes_total: int = 0
331 bytes_done: int = 0
332 bytes_per_second: float = 0
333 started_at: datetime | None = None
334 eta_seconds: float | None = None
336 @property
337 def percent(self) -> float:
338 if self.bytes_total == 0:
339 return 0.0
340 return (self.bytes_done / self.bytes_total) * 100
342 @property
343 def speed_mbps(self) -> float:
344 return self.bytes_per_second / (1024**2)