Coverage for fastblocks / actions / gather / components.py: 92%

157 statements  

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

1"""FastBlocks Component Gathering Action. 

2 

3Provides unified component discovery and management for HTMY components, 

4integrating with the gather action system to provide comprehensive component 

5orchestration across the FastBlocks ecosystem. 

6 

7Features: 

8- Unified component discovery across all searchpaths 

9- Component metadata collection and analysis 

10- Performance-optimized gathering with parallel processing 

11- Integration with existing gather strategies 

12- HTMX-aware component categorization 

13- Advanced filtering and sorting capabilities 

14 

15Author: lesleslie <les@wedgwoodwebworks.com> 

16Created: 2025-01-13 

17""" 

18 

19import asyncio 

20from contextlib import suppress 

21from dataclasses import dataclass, field 

22from datetime import datetime 

23from typing import Any 

24 

25from oneiric.core.resolution import Resolver 

26 

27# Migration from ACB to Oneiric 

28depends = Resolver() 

29 

30# ACB compatibility imports - these will be migrated in future phases 

31try: 

32 # MIGRATED: Removed ACB import - debug import debug 

33 pass 

34except ImportError: 

35 # Fallback for Oneiric-only mode 

36 def debug(msg: str) -> None: 

37 """Debug function fallback.""" 

38 print(f"[DEBUG] {msg}") 

39 

40 

41from anyio import Path as AsyncPath 

42 

43from .strategies import GatherResult, GatherStrategy 

44 

45 

46@dataclass 

47class ComponentGatherResult(GatherResult): 

48 """Result from component gathering operation.""" 

49 

50 components: dict[str, Any] = field(default_factory=dict) 

51 component_count: int = 0 

52 validation_errors: list[str] = field(default_factory=list) 

53 htmx_components: list[str] = field(default_factory=list) 

54 dataclass_components: list[str] = field(default_factory=list) 

55 composite_components: list[str] = field(default_factory=list) 

56 searchpaths: list[AsyncPath] = field(default_factory=list) 

57 execution_time: float = 0.0 

58 items_processed: int = 0 

59 cache_hits: int = 0 

60 parallel_tasks: int = 0 

61 error_message: str = "" 

62 

63 def __post_init__(self) -> None: 

64 # Initialize parent GatherResult 

65 success_items = list(self.components.values()) if self.components else [] 

66 GatherResult.__init__(self, success=success_items, errors=[], cache_key=None) 

67 # Set component count 

68 self.component_count = len(self.components) 

69 

70 

71class ComponentGatherStrategy(GatherStrategy): 

72 """Strategy for gathering HTMY components.""" 

73 

74 def __init__( 

75 self, 

76 include_metadata: bool = True, 

77 validate_components: bool = True, 

78 filter_types: list[str] | None = None, 

79 max_parallel: int = 10, 

80 timeout: int = 300, 

81 ) -> None: 

82 super().__init__( 

83 max_concurrent=max_parallel, # Map max_parallel to max_concurrent 

84 timeout=float(timeout), 

85 retry_attempts=2, 

86 ) 

87 self.include_metadata = include_metadata 

88 self.validate_components = validate_components 

89 self.filter_types = filter_types or [] 

90 # Store max_parallel for compatibility 

91 self.max_parallel = max_parallel 

92 

93 async def gather_single(self, item: Any) -> Any: 

94 """Gather a single component.""" 

95 if isinstance(item, dict) and "name" in item and "metadata" in item: 

96 return item 

97 return None 

98 

99 async def gather_batch(self, items: list[Any]) -> list[Any]: 

100 """Gather a batch of components in parallel.""" 

101 if not items: 

102 return [] 

103 

104 tasks = [self.gather_single(item) for item in items] 

105 results = await asyncio.gather(*tasks, return_exceptions=True) 

106 

107 gathered = [] 

108 for result in results: 

109 if isinstance(result, Exception): 

110 debug(f"Component gather error: {result}") 

111 continue 

112 if result is not None: 

113 gathered.append(result) 

114 

115 return gathered 

116 

117 

118async def _get_htmy_adapter( 

119 start_time: datetime, 

120) -> tuple[Any | None, ComponentGatherResult | None]: 

121 """Get HTMY adapter or return error result.""" 

122 try: 

123 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

124 return htmy_adapter, None 

125 except Exception as e: 

126 debug(f"Could not get HTMY adapter: {e}") 

127 result = ComponentGatherResult( 

128 error_message=f"HTMY adapter not available: {e}", 

129 execution_time=(datetime.now() - start_time).total_seconds(), 

130 ) 

131 result.errors = [e] 

132 return None, result 

133 

134 

135async def _discover_components_metadata(htmy_adapter: Any) -> dict[str, Any]: 

136 """Discover components using adapter's discovery methods.""" 

137 if hasattr(htmy_adapter, "discover_components"): 

138 metadata: dict[str, Any] = await htmy_adapter.discover_components() 

139 return metadata 

140 

141 if hasattr(htmy_adapter, "htmy_registry") and htmy_adapter.htmy_registry: 

142 from fastblocks.adapters.templates._htmy_components import ( 

143 ComponentMetadata, 

144 ComponentStatus, 

145 ComponentType, 

146 ) 

147 

148 discovered = await htmy_adapter.htmy_registry.discover_components() 

149 return { 

150 name: ComponentMetadata( 

151 name=name, 

152 path=path, 

153 type=ComponentType.BASIC, 

154 status=ComponentStatus.DISCOVERED, 

155 ) 

156 for name, path in discovered.items() 

157 } 

158 

159 return {} 

160 

161 

162def _categorize_and_validate( 

163 components_metadata: dict[str, Any], filter_types: list[str] 

164) -> tuple[list[str], list[str], list[str], list[str]]: 

165 """Categorize components and collect validation errors.""" 

166 htmx_components = [] 

167 dataclass_components = [] 

168 composite_components = [] 

169 validation_errors = [] 

170 

171 for name, metadata in components_metadata.items(): 

172 if filter_types and metadata.type.value not in filter_types: 

173 continue 

174 

175 if metadata.type.value == "htmx": 

176 htmx_components.append(name) 

177 elif metadata.type.value == "dataclass": 

178 dataclass_components.append(name) 

179 elif metadata.type.value == "composite": 

180 composite_components.append(name) 

181 

182 if metadata.status.value == "error" and metadata.error_message: 

183 validation_errors.append(f"{name}: {metadata.error_message}") 

184 

185 return ( 

186 htmx_components, 

187 dataclass_components, 

188 composite_components, 

189 validation_errors, 

190 ) 

191 

192 

193async def gather_components( 

194 htmy_adapter: Any | None = None, 

195 include_metadata: bool = True, 

196 validate_components: bool = True, 

197 filter_types: list[str] | None = None, 

198 searchpaths: list[AsyncPath] | None = None, 

199 strategy: ComponentGatherStrategy | None = None, 

200) -> ComponentGatherResult: 

201 """Gather all HTMY components with comprehensive metadata. 

202 

203 Args: 

204 htmy_adapter: HTMY adapter instance (auto-detected if None) 

205 include_metadata: Include component metadata in results 

206 validate_components: Validate component structure 

207 filter_types: Filter components by type (htmx, dataclass, etc.) 

208 searchpaths: Custom searchpaths (uses adapter defaults if None) 

209 strategy: Custom gathering strategy 

210 

211 Returns: 

212 ComponentGatherResult with discovered components and metadata 

213 """ 

214 start_time = datetime.now() 

215 

216 if strategy is None: 

217 strategy = ComponentGatherStrategy( 

218 include_metadata=include_metadata, 

219 validate_components=validate_components, 

220 filter_types=filter_types or [], 

221 ) 

222 

223 if htmy_adapter is None: 

224 htmy_adapter, error_result = await _get_htmy_adapter(start_time) 

225 if error_result: 

226 return error_result 

227 

228 if htmy_adapter is None: 

229 result = ComponentGatherResult( 

230 error_message="HTMY adapter not found", 

231 execution_time=(datetime.now() - start_time).total_seconds(), 

232 ) 

233 result.errors = [Exception("HTMY adapter not found")] 

234 return result 

235 

236 try: 

237 if hasattr(htmy_adapter, "_init_htmy_registry"): 

238 await htmy_adapter._init_htmy_registry() 

239 

240 if searchpaths is None and hasattr(htmy_adapter, "component_searchpaths"): 

241 searchpaths = htmy_adapter.component_searchpaths 

242 elif searchpaths is None: 

243 searchpaths = [] 

244 

245 components_metadata = await _discover_components_metadata(htmy_adapter) 

246 

247 htmx, dataclass, composite, validation_errors = _categorize_and_validate( 

248 components_metadata, strategy.filter_types 

249 ) 

250 

251 component_items = [ 

252 { 

253 "name": name, 

254 "metadata": metadata, 

255 "type": metadata.type.value, 

256 "status": metadata.status.value, 

257 "path": str(metadata.path), 

258 "htmx_attributes": metadata.htmx_attributes, 

259 "dependencies": metadata.dependencies, 

260 "docstring": metadata.docstring, 

261 "last_modified": metadata.last_modified.isoformat() 

262 if metadata.last_modified 

263 else None, 

264 "error_message": metadata.error_message, 

265 } 

266 for name, metadata in components_metadata.items() 

267 ] 

268 

269 gathered_components = await strategy.gather_batch(component_items) 

270 

271 final_components = { 

272 item["name"]: item 

273 for item in gathered_components 

274 if item and "name" in item 

275 } 

276 

277 execution_time = (datetime.now() - start_time).total_seconds() 

278 debug(f"Gathered {len(final_components)} components in {execution_time:.2f}s") 

279 

280 result = ComponentGatherResult( 

281 components=final_components, 

282 component_count=len(final_components), 

283 validation_errors=validation_errors, 

284 htmx_components=htmx, 

285 dataclass_components=dataclass, 

286 composite_components=composite, 

287 searchpaths=searchpaths or [], 

288 execution_time=execution_time, 

289 items_processed=len(component_items), 

290 cache_hits=0, 

291 parallel_tasks=min(strategy.max_parallel, len(component_items)), 

292 ) 

293 # Set success list with component values 

294 result.success = list(final_components.values()) if final_components else [] 

295 return result 

296 

297 except Exception as e: 

298 execution_time = (datetime.now() - start_time).total_seconds() 

299 debug(f"Component gathering failed: {e}") 

300 

301 result = ComponentGatherResult( 

302 error_message=str(e), 

303 execution_time=execution_time, 

304 searchpaths=searchpaths or [], 

305 ) 

306 result.errors = [e] 

307 return result 

308 

309 

310async def gather_component_dependencies( 

311 component_name: str, 

312 htmy_adapter: Any | None = None, 

313 recursive: bool = True, 

314 max_depth: int = 5, 

315) -> dict[str, Any]: 

316 """Gather component dependencies recursively. 

317 

318 Args: 

319 component_name: Name of component to analyze 

320 htmy_adapter: HTMY adapter instance 

321 recursive: Whether to gather dependencies recursively 

322 max_depth: Maximum recursion depth 

323 

324 Returns: 

325 Dictionary with component dependency tree 

326 """ 

327 if htmy_adapter is None: 

328 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

329 

330 if htmy_adapter is None: 

331 return {"error": "HTMY adapter not available"} 

332 

333 try: 

334 # Get component metadata 

335 if not hasattr(htmy_adapter, "validate_component"): 

336 return {"error": "Component validation not available"} 

337 

338 metadata = await htmy_adapter.validate_component(component_name) 

339 

340 dependencies = { 

341 "name": component_name, 

342 "type": metadata.type.value, 

343 "direct_dependencies": metadata.dependencies, 

344 "children": {}, 

345 } 

346 

347 if recursive and max_depth > 0: 

348 for dep in metadata.dependencies: 

349 with suppress(Exception): 

350 child_deps = await gather_component_dependencies( 

351 dep, htmy_adapter, recursive, max_depth - 1 

352 ) 

353 dependencies["children"][dep] = child_deps 

354 

355 return dependencies 

356 

357 except Exception as e: 

358 return {"error": str(e)} 

359 

360 

361async def analyze_component_usage( 

362 htmy_adapter: Any | None = None, 

363) -> dict[str, Any]: 

364 """Analyze component usage patterns across the application. 

365 

366 Args: 

367 htmy_adapter: HTMY adapter instance 

368 

369 Returns: 

370 Dictionary with usage analysis 

371 """ 

372 if htmy_adapter is None: 

373 htmy_adapter = await depends.resolve("fastblocks", "htmy") 

374 

375 if htmy_adapter is None: 

376 return {"error": "HTMY adapter not available"} 

377 

378 try: 

379 components_result = await gather_components(htmy_adapter) 

380 

381 if not components_result.is_success: 

382 return {"error": components_result.error_message} 

383 

384 analysis: dict[str, Any] = { 

385 "total_components": components_result.component_count, 

386 "by_type": { 

387 "htmx": len(components_result.htmx_components), 

388 "dataclass": len(components_result.dataclass_components), 

389 "composite": len(components_result.composite_components), 

390 }, 

391 "validation_errors": len(components_result.validation_errors), 

392 "searchpaths": [str(p) for p in components_result.searchpaths], 

393 "components": {}, 

394 } 

395 

396 # Analyze each component 

397 for name, component_data in components_result.components.items(): 

398 analysis["components"][name] = { 

399 "type": component_data.get("type"), 

400 "status": component_data.get("status"), 

401 "has_htmx": bool(component_data.get("htmx_attributes")), 

402 "dependency_count": len(component_data.get("dependencies", [])), 

403 "has_documentation": bool(component_data.get("docstring")), 

404 "last_modified": component_data.get("last_modified"), 

405 } 

406 

407 return analysis 

408 

409 except Exception as e: 

410 return {"error": str(e)} 

411 

412 

413# Migration status indicator 

414# Note: Partial migration - ACB debug system still in use 

415_using_oneiric = True # Oneiric resolver available 

416_requires_further_migration = True # ACB debug system needs migration