Coverage for fastblocks / mcp / health.py: 72%
187 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-02 20:00 -0800
1"""Health check and validation system for FastBlocks adapters."""
3import asyncio
4import time
5from datetime import datetime
6from typing import Any
8from .registry import AdapterRegistry
11class HealthCheckResult:
12 """Result of a health check operation."""
14 def __init__(
15 self,
16 adapter_name: str,
17 status: str,
18 message: str = "",
19 details: dict[str, Any] | None = None,
20 duration_ms: float = 0.0,
21 timestamp: datetime | None = None,
22 ):
23 self.adapter_name = adapter_name
24 self.status = status # 'healthy', 'warning', 'error', 'unknown'
25 self.message = message
26 self.details = details or {}
27 self.duration_ms = duration_ms
28 self.timestamp = timestamp or datetime.now()
30 def to_dict(self) -> dict[str, Any]:
31 """Convert result to dictionary."""
32 return {
33 "adapter_name": self.adapter_name,
34 "status": self.status,
35 "message": self.message,
36 "details": self.details,
37 "duration_ms": self.duration_ms,
38 "timestamp": self.timestamp.isoformat(),
39 }
42class HealthCheckSystem:
43 """Health monitoring and validation system for adapters."""
45 def __init__(self, registry: AdapterRegistry):
46 """Initialize health check system."""
47 self.registry = registry
48 self._check_history: dict[str, list[HealthCheckResult]] = {}
49 self._check_config: dict[str, dict[str, Any]] = {}
50 self._running_checks: dict[str, bool] = {}
52 async def check_adapter_health(self, adapter_name: str) -> HealthCheckResult:
53 """Perform comprehensive health check on an adapter."""
54 start_time = time.time()
56 try:
57 # Prevent concurrent checks on same adapter
58 if self._running_checks.get(adapter_name, False):
59 return HealthCheckResult(
60 adapter_name, "warning", "Health check already in progress"
61 )
63 self._running_checks[adapter_name] = True
65 # Basic validation check
66 validation_result = await self.registry.validate_adapter(adapter_name)
68 if not validation_result["valid"]:
69 duration_ms = (time.time() - start_time) * 1000
70 result = HealthCheckResult(
71 adapter_name,
72 "error",
73 f"Validation failed: {', '.join(validation_result['errors'])}",
74 validation_result,
75 duration_ms,
76 )
77 else:
78 # Get adapter instance for functional tests
79 adapter = await self.registry.get_adapter(adapter_name)
81 if not adapter:
82 duration_ms = (time.time() - start_time) * 1000
83 result = HealthCheckResult(
84 adapter_name,
85 "error",
86 "Could not instantiate adapter",
87 duration_ms=duration_ms,
88 )
89 else:
90 # Perform functional health checks
91 result = await self._perform_functional_checks(
92 adapter_name, adapter, start_time
93 )
95 except Exception as e:
96 duration_ms = (time.time() - start_time) * 1000
97 result = HealthCheckResult(
98 adapter_name,
99 "error",
100 f"Health check failed: {e}",
101 duration_ms=duration_ms,
102 )
103 finally:
104 self._running_checks[adapter_name] = False
106 # Store result in history
107 self._store_check_result(result)
109 return result
111 def _determine_health_status(
112 self, checks: list[str], warnings: list[str]
113 ) -> tuple[str, str]:
114 """Determine health status and message based on checks and warnings."""
115 if checks:
116 status = "warning" if warnings else "healthy"
117 message = f"Passed {len(checks)} checks"
118 if warnings:
119 message += f", {len(warnings)} warnings"
120 else:
121 status = "error"
122 message = "No functional checks passed"
123 return status, message
125 async def _perform_category_specific_checks(
126 self, adapter_info: Any, adapter: Any
127 ) -> list[str]:
128 """Perform category-specific health checks."""
129 checks = []
130 category = adapter_info.category
132 # Category-specific health checks
133 if category == "images":
134 checks.extend(await self._check_image_adapter(adapter))
135 elif category == "styles":
136 checks.extend(await self._check_style_adapter(adapter))
137 elif category == "icons":
138 checks.extend(await self._check_icon_adapter(adapter))
139 elif category == "fonts":
140 checks.extend(await self._check_font_adapter(adapter))
141 elif category == "templates":
142 checks.extend(await self._check_template_adapter(adapter))
144 return checks
146 async def _check_acb_registration(
147 self, adapter_name: str
148 ) -> tuple[list[str], list[str]]:
149 """Check ACB registration for the adapter."""
150 checks = []
151 warnings = []
153 try:
154 from oneiric.core.resolution import Resolver
156 # Use Oneiric resolver
157 depends = Resolver()
159 registered_adapter = depends.get_sync(adapter_name)
160 if registered_adapter:
161 checks.append("Registered with ACB")
162 else:
163 warnings.append("Not registered with ACB")
164 except Exception:
165 warnings.append("ACB registration check failed")
167 return checks, warnings
169 async def _perform_functional_checks(
170 self, adapter_name: str, adapter: Any, start_time: float
171 ) -> HealthCheckResult:
172 """Perform functional health checks on an adapter."""
173 checks = []
174 warnings = []
176 # Check if adapter has required methods based on its type
177 adapter_info = await self.registry.get_adapter_info(adapter_name)
179 if adapter_info:
180 checks.extend(
181 await self._perform_category_specific_checks(adapter_info, adapter)
182 )
184 # Check settings availability
185 if hasattr(adapter, "settings"):
186 checks.append("Settings available")
187 else:
188 warnings.append("No settings found")
190 # Check ACB registration
191 acb_checks, acb_warnings = await self._check_acb_registration(adapter_name)
192 checks.extend(acb_checks)
193 warnings.extend(acb_warnings)
195 duration_ms = (time.time() - start_time) * 1000
197 # Determine overall status
198 status, message = self._determine_health_status(checks, warnings)
200 return HealthCheckResult(
201 adapter_name,
202 status,
203 message,
204 {
205 "checks_passed": checks,
206 "warnings": warnings,
207 "category": adapter_info.category if adapter_info else "unknown",
208 },
209 duration_ms,
210 )
212 async def _check_image_adapter(self, adapter: Any) -> list[str]:
213 """Check image adapter functionality."""
214 checks = []
216 if hasattr(adapter, "get_img_tag"):
217 checks.append("get_img_tag method available")
219 if hasattr(adapter, "get_image_url"):
220 checks.append("get_image_url method available")
222 if hasattr(adapter, "upload_image"):
223 checks.append("upload_image method available")
225 return checks
227 async def _check_style_adapter(self, adapter: Any) -> list[str]:
228 """Check style adapter functionality."""
229 checks = []
231 if hasattr(adapter, "get_stylesheet_links"):
232 checks.append("get_stylesheet_links method available")
234 if hasattr(adapter, "get_component_class"):
235 checks.append("get_component_class method available")
237 if hasattr(adapter, "get_utility_classes"):
238 checks.append("get_utility_classes method available")
240 return checks
242 async def _check_icon_adapter(self, adapter: Any) -> list[str]:
243 """Check icon adapter functionality."""
244 checks = []
246 if hasattr(adapter, "get_icon_tag"):
247 checks.append("get_icon_tag method available")
249 if hasattr(adapter, "get_stylesheet_links"):
250 checks.append("get_stylesheet_links method available")
252 if hasattr(adapter, "get_icon_class"):
253 checks.append("get_icon_class method available")
255 return checks
257 async def _check_font_adapter(self, adapter: Any) -> list[str]:
258 """Check font adapter functionality."""
259 checks = []
261 if hasattr(adapter, "get_font_import"):
262 checks.append("get_font_import method available")
264 if hasattr(adapter, "get_font_family"):
265 checks.append("get_font_family method available")
267 return checks
269 async def _check_template_adapter(self, adapter: Any) -> list[str]:
270 """Check template adapter functionality."""
271 checks = []
273 if hasattr(adapter, "render_template"):
274 checks.append("render_template method available")
276 if hasattr(adapter, "get_template"):
277 checks.append("get_template method available")
279 if hasattr(adapter, "list_templates"):
280 checks.append("list_templates method available")
282 return checks
284 async def check_all_adapters(self) -> dict[str, HealthCheckResult]:
285 """Perform health checks on all available adapters."""
286 available_adapters = await self.registry.list_available_adapters()
287 results = {}
289 # Run checks concurrently
290 tasks = []
291 for adapter_name in available_adapters.keys():
292 task = asyncio.create_task(self.check_adapter_health(adapter_name))
293 tasks.append((adapter_name, task))
295 for adapter_name, task in tasks:
296 try:
297 result = await task
298 results[adapter_name] = result
299 except Exception as e:
300 results[adapter_name] = HealthCheckResult(
301 adapter_name, "error", f"Check failed: {e}"
302 )
304 return results
306 def _store_check_result(self, result: HealthCheckResult) -> None:
307 """Store health check result in history."""
308 if result.adapter_name not in self._check_history:
309 self._check_history[result.adapter_name] = []
311 self._check_history[result.adapter_name].append(result)
313 # Keep only last 100 results per adapter
314 if len(self._check_history[result.adapter_name]) > 100:
315 self._check_history[result.adapter_name] = self._check_history[
316 result.adapter_name
317 ][-100:]
319 def get_check_history(
320 self, adapter_name: str, limit: int = 10
321 ) -> list[HealthCheckResult]:
322 """Get health check history for an adapter."""
323 return self._check_history.get(adapter_name, [])[-limit:]
325 def get_system_health_summary(self) -> dict[str, Any]:
326 """Get overall system health summary."""
327 summary: dict[str, Any] = {
328 "healthy_adapters": 0,
329 "warning_adapters": 0,
330 "error_adapters": 0,
331 "unknown_adapters": 0,
332 "total_adapters": 0,
333 "last_check_time": None,
334 "adapter_status": {},
335 }
337 latest_results = {}
339 # Get latest result for each adapter
340 for adapter_name, history in self._check_history.items():
341 if history:
342 latest_results[adapter_name] = history[-1]
344 # Count statuses
345 for adapter_name, result in latest_results.items():
346 summary["adapter_status"][adapter_name] = {
347 "status": result.status,
348 "last_check": result.timestamp.isoformat(),
349 "message": result.message,
350 }
352 if result.status == "healthy":
353 summary["healthy_adapters"] += 1
354 elif result.status == "warning":
355 summary["warning_adapters"] += 1
356 elif result.status == "error":
357 summary["error_adapters"] += 1
358 else:
359 summary["unknown_adapters"] += 1
361 summary["total_adapters"] = len(latest_results)
363 if latest_results:
364 latest_time = max(result.timestamp for result in latest_results.values())
365 summary["last_check_time"] = latest_time.isoformat()
367 return summary
369 def configure_health_checks(
370 self, adapter_name: str, config: dict[str, Any]
371 ) -> None:
372 """Configure health check parameters for an adapter."""
373 self._check_config[adapter_name] = config
375 def get_health_check_config(self, adapter_name: str) -> dict[str, Any]:
376 """Get health check configuration for an adapter."""
377 return self._check_config.get(adapter_name, {})
379 async def schedule_periodic_checks(self, interval_minutes: int = 30) -> None:
380 """Schedule periodic health checks for all adapters."""
381 while True:
382 try:
383 await self.check_all_adapters()
384 await asyncio.sleep(interval_minutes * 60)
385 except Exception:
386 # Log error but continue
387 await asyncio.sleep(60) # Wait 1 minute before retrying