Coverage for fastblocks / _health_integration.py: 24%

208 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Oneiric Health Service integration for FastBlocks. 

2 

3This module provides FastBlocks components with comprehensive health monitoring. 

4It includes custom health checks for templates, cache, routing, and database systems. 

5 

6Author: lesleslie <les@wedgwoodwebworks.com> 

7Created: 2025-10-01 

8""" 

9 

10import typing as t 

11from contextlib import suppress 

12from uuid import UUID 

13 

14# Oneiric imports for dependency injection 

15from oneiric.core.resolution import Resolver 

16from fastblocks.adapters.oneiric_helper import register_candidate 

17 

18# Custom Oneiric-compatible health system 

19depends = Resolver() 

20 

21# Health system availability 

22oneiric_health_available = True 

23 

24 

25# Custom Oneiric-compatible Health System 

26class HealthStatus: 

27 """Health status levels.""" 

28 

29 HEALTHY = "healthy" 

30 DEGRADED = "degraded" 

31 UNHEALTHY = "unhealthy" 

32 UNKNOWN = "unknown" 

33 

34 

35class HealthCheckResult: 

36 """Result of a health check.""" 

37 

38 def __init__( 

39 self, 

40 component_id: str, 

41 component_name: str, 

42 status: str, 

43 check_type: t.Any, 

44 message: str, 

45 details: dict[str, t.Any] | None = None, 

46 ): 

47 self.component_id = component_id 

48 self.component_name = component_name 

49 self.status = status 

50 self.check_type = check_type 

51 self.message = message 

52 self.details = details or {} 

53 

54 def to_dict(self) -> dict[str, t.Any]: 

55 """Convert health check result to dictionary.""" 

56 return { 

57 "component_id": self.component_id, 

58 "component_name": self.component_name, 

59 "status": self.status, 

60 "check_type": str(self.check_type) if self.check_type else None, 

61 "message": self.message, 

62 "details": self.details, 

63 } 

64 

65 

66class HealthService: 

67 """Simple health service for Oneiric-compatible health monitoring.""" 

68 

69 def __init__(self) -> None: 

70 self.components: dict[str, t.Any] = {} 

71 

72 async def register_component(self, component: t.Any) -> bool: 

73 """Register a health check component.""" 

74 with suppress(Exception): 

75 if hasattr(component, "component_id"): 

76 self.components[component.component_id] = component 

77 return True 

78 return False 

79 

80 async def get_component_health(self, component_id: str) -> HealthCheckResult | None: 

81 """Get health status for a specific component.""" 

82 with suppress(Exception): 

83 component = self.components.get(component_id) 

84 if component and hasattr(component, "_perform_health_check"): 

85 # Use a simple check type for now 

86 return await component._perform_health_check("standard") 

87 return None 

88 

89 

90class FastBlocksHealthCheck: 

91 """Base health check implementation for FastBlocks components.""" 

92 

93 def __init__( 

94 self, 

95 config: t.Any | None = None, 

96 component_id: str | None = None, 

97 component_name: str | None = None, 

98 ) -> None: 

99 self.config = config 

100 self._component_id: str = component_id or self.__class__.__name__.lower() 

101 self._component_name: str = component_name or self.__class__.__name__ 

102 

103 @property 

104 def component_id(self) -> str: 

105 """Get unique identifier for this component.""" 

106 return self._component_id 

107 

108 @property 

109 def component_name(self) -> str: 

110 """Get human-readable name for this component.""" 

111 return self._component_name 

112 

113 async def _perform_health_check( 

114 self, 

115 check_type: t.Any, # HealthCheckType when available 

116 ) -> t.Any: # HealthCheckResult when available 

117 """Default health check - override in subclasses.""" 

118 if not acb_health_available: 

119 return None 

120 

121 return HealthCheckResult( 

122 component_id=self.component_id, 

123 component_name=self.component_name, 

124 status=HealthStatus.HEALTHY, 

125 check_type=check_type, 

126 message=f"{self.component_name} is operational", 

127 ) 

128 

129 

130class TemplatesHealthCheck(FastBlocksHealthCheck): 

131 """Health check for FastBlocks template system.""" 

132 

133 def __init__(self) -> None: 

134 super().__init__( 

135 component_id="templates", 

136 component_name="Template System", 

137 ) 

138 

139 def _check_template_adapter_status( 

140 self, templates: t.Any, details: dict[str, t.Any] 

141 ) -> tuple[t.Any, str]: 

142 """Check templates adapter status and update details.""" 

143 if not hasattr(templates, "app") or templates.app is None: 

144 return HealthStatus.DEGRADED, "Template app not initialized" 

145 

146 details["jinja_env_initialized"] = True 

147 

148 # Check template directory accessibility 

149 if hasattr(templates.app, "env") and templates.app.env.loader: 

150 details["loader_available"] = True 

151 return HealthStatus.HEALTHY, "Template system operational" 

152 return HealthStatus.DEGRADED, "Template loader not configured" 

153 

154 async def _check_cache_availability(self, details: dict[str, t.Any]) -> None: 

155 """Check cache availability and update details.""" 

156 try: 

157 # For Oneiric, we'll use a simpler approach 

158 # In practice, this would be replaced with actual dependency resolution 

159 details["cache_available"] = True # Placeholder 

160 except Exception: 

161 details["cache_available"] = False 

162 

163 async def _perform_health_check( 

164 self, 

165 check_type: t.Any, 

166 ) -> HealthCheckResult: 

167 """Check template system health.""" 

168 details: dict[str, t.Any] = {} 

169 status = HealthStatus.HEALTHY 

170 message = "Template system operational" 

171 

172 try: 

173 # Try to get templates adapter 

174 # For Oneiric, we'll use a simpler approach 

175 templates = None # Placeholder - would use actual template system 

176 

177 if templates is None: 

178 status = HealthStatus.DEGRADED 

179 message = "Templates adapter not initialized" 

180 else: 

181 status, message = self._check_template_adapter_status( 

182 templates, details 

183 ) 

184 

185 # Check cache availability 

186 await self._check_cache_availability(details) 

187 

188 except Exception as e: 

189 status = HealthStatus.UNHEALTHY 

190 message = f"Template health check failed: {e}" 

191 details["error"] = str(e) 

192 

193 return HealthCheckResult( 

194 component_id=self.component_id, 

195 component_name=self.component_name, 

196 status=status, 

197 check_type=check_type, 

198 message=message, 

199 details=details, 

200 ) 

201 

202 

203class CacheHealthCheck(FastBlocksHealthCheck): 

204 """Health check for FastBlocks cache system.""" 

205 

206 def __init__(self) -> None: 

207 super().__init__( 

208 component_id="cache", 

209 component_name="Cache System", 

210 ) 

211 

212 async def _test_cache_operations( 

213 self, cache: t.Any, details: dict[str, t.Any] 

214 ) -> tuple[str, str]: # Returns (status, message) 

215 """Test cache read/write operations and update details.""" 

216 try: 

217 # Test set operation 

218 # For Oneiric, we'll use a simpler approach 

219 details["write_test"] = "passed" # Placeholder 

220 

221 # Test get operation 

222 # For Oneiric, we'll use a simpler approach 

223 details["read_test"] = "passed" # Placeholder 

224 return HealthStatus.HEALTHY, "Cache system operational" 

225 

226 except Exception as e: 

227 details["operation_error"] = str(e) 

228 return HealthStatus.DEGRADED, f"Cache operations failed: {e}" 

229 

230 async def _collect_cache_stats( 

231 self, cache: t.Any, details: dict[str, t.Any] 

232 ) -> None: 

233 """Collect cache statistics if available.""" 

234 # For Oneiric, we'll use a simpler approach 

235 # In practice, this would be replaced with actual cache stats 

236 details["cache_hit_ratio"] = 0.95 # Placeholder 

237 

238 async def _perform_health_check( 

239 self, 

240 check_type: t.Any, 

241 ) -> HealthCheckResult: 

242 """Check cache system health.""" 

243 details: dict[str, t.Any] = {} 

244 status = HealthStatus.HEALTHY 

245 message = "Cache system operational" 

246 

247 try: 

248 # Try to get cache adapter 

249 # For Oneiric, we'll use a simpler approach 

250 cache = None # Placeholder - would use actual cache system 

251 

252 if cache is None: 

253 status = HealthStatus.DEGRADED 

254 message = "Cache adapter not available (degraded mode)" 

255 details["reason"] = "cache_disabled_or_not_configured" 

256 else: 

257 # Test cache operations 

258 status, message = await self._test_cache_operations(cache, details) 

259 

260 # Collect stats if available 

261 await self._collect_cache_stats(cache, details) 

262 

263 except Exception as e: 

264 status = HealthStatus.UNHEALTHY 

265 message = f"Cache health check failed: {e}" 

266 details["error"] = str(e) 

267 

268 return HealthCheckResult( 

269 component_id=self.component_id, 

270 component_name=self.component_name, 

271 status=status, 

272 check_type=check_type, 

273 message=message, 

274 details=details, 

275 ) 

276 

277 

278class RoutesHealthCheck(FastBlocksHealthCheck): 

279 """Health check for FastBlocks routing system.""" 

280 

281 def __init__(self) -> None: 

282 super().__init__( 

283 component_id="routes", 

284 component_name="Routing System", 

285 ) 

286 

287 def _check_routes_adapter( 

288 self, routes: t.Any, details: dict[str, t.Any] 

289 ) -> tuple[t.Any, str]: # Returns (status, message) 

290 """Check routes adapter status and update details.""" 

291 if not hasattr(routes, "routes"): 

292 return HealthStatus.DEGRADED, "Routes collection not available" 

293 

294 route_count = len(routes.routes) if routes.routes else 0 

295 details["route_count"] = route_count 

296 

297 if route_count == 0: 

298 return HealthStatus.DEGRADED, "No routes registered" 

299 

300 return HealthStatus.HEALTHY, f"{route_count} routes registered" 

301 

302 async def _perform_health_check( 

303 self, 

304 check_type: t.Any, 

305 ) -> HealthCheckResult: 

306 """Check routing system health.""" 

307 details: dict[str, t.Any] = {} 

308 status = HealthStatus.HEALTHY 

309 message = "Routing system operational" 

310 

311 try: 

312 # Try to get routes adapter 

313 # For Oneiric, we'll use a simpler approach 

314 routes = None # Placeholder - would use actual routing system 

315 

316 if routes is None: 

317 status = HealthStatus.DEGRADED 

318 message = "Routes adapter not initialized" 

319 else: 

320 status, message = self._check_routes_adapter(routes, details) 

321 

322 except Exception as e: 

323 status = HealthStatus.UNHEALTHY 

324 message = f"Routes health check failed: {e}" 

325 details["error"] = str(e) 

326 

327 return HealthCheckResult( 

328 component_id=self.component_id, 

329 component_name=self.component_name, 

330 status=status, 

331 check_type=check_type, 

332 message=message, 

333 details=details, 

334 ) 

335 

336 

337class DatabaseHealthCheck(FastBlocksHealthCheck): 

338 """Health check for database connectivity.""" 

339 

340 def __init__(self) -> None: 

341 super().__init__( 

342 component_id="database", 

343 component_name="Database", 

344 ) 

345 

346 async def _perform_health_check( 

347 self, 

348 check_type: t.Any, 

349 ) -> HealthCheckResult: 

350 """Check database health.""" 

351 details: dict[str, t.Any] = {} 

352 status = HealthStatus.HEALTHY 

353 message = "Database operational" 

354 

355 try: 

356 # Try to get sql adapter 

357 # For Oneiric, we'll use a simpler approach 

358 sql = None # Placeholder - would use actual database system 

359 

360 if sql is None: 

361 status = HealthStatus.DEGRADED 

362 message = "Database adapter not configured" 

363 details["reason"] = "sql_adapter_not_available" 

364 else: 

365 # Try a simple database query 

366 try: 

367 # Most databases support SELECT 1 as a ping query 

368 # For Oneiric, we'll use a simpler approach 

369 details["connectivity_test"] = "passed" # Placeholder 

370 

371 # Check if we have connection pool info 

372 # For Oneiric, we'll use a simpler approach 

373 details["connection_info"] = {"pool_size": 10} # Placeholder 

374 

375 except Exception as e: 

376 status = HealthStatus.UNHEALTHY 

377 message = f"Database query failed: {e}" 

378 details["connectivity_test"] = "failed" 

379 details["error"] = str(e) 

380 

381 except Exception as e: 

382 status = HealthStatus.DEGRADED 

383 message = f"Database health check failed: {e}" 

384 details["error"] = str(e) 

385 

386 return HealthCheckResult( 

387 component_id=self.component_id, 

388 component_name=self.component_name, 

389 status=status, 

390 check_type=check_type, 

391 message=message, 

392 details=details, 

393 ) 

394 

395 

396async def register_fastblocks_health_checks() -> bool: 

397 """Register all FastBlocks components with Oneiric HealthService. 

398 

399 Returns: 

400 True if registration successful, False if health service unavailable 

401 """ 

402 try: 

403 # Create Oneiric-compatible health service 

404 health_service = HealthService() 

405 

406 # Register all FastBlocks health checks 

407 await health_service.register_component(TemplatesHealthCheck()) 

408 await health_service.register_component(CacheHealthCheck()) 

409 await health_service.register_component(RoutesHealthCheck()) 

410 await health_service.register_component(DatabaseHealthCheck()) 

411 

412 # Store health service in depends for retrieval 

413 register_candidate( 

414 depends, 

415 domain="fastblocks", 

416 key="health", 

417 factory=lambda: health_service, 

418 metadata={ 

419 "class": "HealthService", 

420 "module": "fastblocks._health_integration", 

421 }, 

422 ) 

423 

424 return True 

425 

426 except Exception: 

427 # Graceful degradation if registration fails 

428 return False 

429 

430 

431def _determine_overall_health_status(results: dict[str, t.Any]) -> str: 

432 """Determine overall health status from individual component results.""" 

433 statuses = [r.get("status", "unknown") for r in results.values()] 

434 

435 if "unhealthy" in statuses or "critical" in statuses: 

436 return "unhealthy" 

437 elif "degraded" in statuses: 

438 return "degraded" 

439 elif all(s == "healthy" for s in statuses): 

440 return "healthy" 

441 return "unknown" 

442 

443 

444async def _get_component_health_results(health_service: t.Any) -> dict[str, t.Any]: 

445 """Get health results for all components.""" 

446 component_ids = ["templates", "cache", "routes", "database"] 

447 results = {} 

448 

449 for component_id in component_ids: 

450 try: 

451 result = await health_service.get_component_health(component_id) 

452 if result: 

453 results[component_id] = result.to_dict() 

454 except Exception: 

455 results[component_id] = { 

456 "status": "unknown", 

457 "message": "Health check failed", 

458 } 

459 

460 return results 

461 

462 

463async def get_fastblocks_health_summary() -> dict[str, t.Any]: 

464 """Get comprehensive health summary for all FastBlocks components. 

465 

466 Returns: 

467 Dictionary with health status for each component 

468 """ 

469 try: 

470 # Get Oneiric health service 

471 # For now, we'll create a new one since we don't have the actual service 

472 health_service = HealthService() 

473 

474 # Register components for this check 

475 await health_service.register_component(TemplatesHealthCheck()) 

476 await health_service.register_component(CacheHealthCheck()) 

477 await health_service.register_component(RoutesHealthCheck()) 

478 await health_service.register_component(DatabaseHealthCheck()) 

479 

480 # Get health status for all registered components 

481 results = await _get_component_health_results(health_service) 

482 

483 # Determine overall status 

484 overall_status = _determine_overall_health_status(results) 

485 

486 return { 

487 "status": overall_status, 

488 "message": f"FastBlocks health status: {overall_status}", 

489 "components": results, 

490 } 

491 

492 except Exception as e: 

493 return { 

494 "status": "error", 

495 "message": f"Health check failed: {e}", 

496 "components": {}, 

497 } 

498 

499 

500# Module metadata for Oneiric compatibility 

501MODULE_ID = UUID("01937d88-0000-7000-8000-000000000001") 

502MODULE_STATUS = "STABLE" # Oneiric-compatible status 

503 

504# Auto-register health checks on module import 

505# Note: Registration happens during application startup via depends.set() 

506# This ensures proper async context is available