Coverage for fastblocks / adapters / templates / htmy.py: 39%

408 statements  

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

1"""HTMY Templates Adapter for FastBlocks. 

2 

3Provides native HTMY component rendering with advanced features including: 

4- Component discovery and caching system 

5- Multi-layer caching (Redis, cloud storage, filesystem) 

6- Bidirectional integration with Jinja2 templates 

7- Async component rendering with context sharing 

8- Template synchronization across cache/storage/filesystem layers 

9- Enhanced debugging and error handling 

10 

11Requirements: 

12- htmy>=0.1.0 

13- redis>=3.5.3 (for caching) 

14 

15Usage: 

16```python 

17# Oneiric imports - ACB imports removed 

18# htmy = depends.resolve("fastblocks", "htmy") 

19# HTMYTemplates = import_adapter("htmy") 

20# response = await htmy.render_component(request, "my_component", {"data": data}) 

21# component_class = await htmy.get_component_class("my_component") 

22``` 

23 

24Author: lesleslie <les@wedgwoodwebworks.com> 

25Created: 2025-01-13 

26""" 

27 

28import asyncio 

29import typing as t 

30from contextlib import suppress 

31from enum import Enum 

32from pathlib import Path 

33from typing import TYPE_CHECKING, Any 

34from uuid import UUID 

35 

36from anyio import Path as AsyncPath 

37from oneiric.core.config import OneiricSettings 

38 

39# Oneiric imports 

40from oneiric.core.resolution import Resolver 

41from starlette.responses import HTMLResponse 

42 

43 

44# Custom implementations for ACB compatibility 

45def get_adapter(adapter_name: str) -> t.Any: 

46 """Custom implementation for Oneiric compatibility.""" 

47 # This will be implemented using Oneiric's adapter system 

48 return None 

49 

50 

51class AdapterStatus: 

52 """Custom AdapterStatus for Oneiric compatibility.""" 

53 

54 STABLE = "STABLE" 

55 BETA = "BETA" 

56 ALPHA = "ALPHA" 

57 EXPERIMENTAL = "EXPERIMENTAL" 

58 

59 

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

61 """Custom debug function for Oneiric compatibility.""" 

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

63 

64 

65# Oneiric resolver for dependency injection 

66depends = Resolver() 

67 

68from ._base import TemplatesBase 

69from ._htmy_components import ( 

70 AdvancedHTMYComponentRegistry, 

71 ComponentLifecycleManager, 

72 ComponentMetadata, 

73 ComponentRenderError, 

74 ComponentStatus, 

75 ComponentType, 

76) 

77 

78if TYPE_CHECKING: 

79 from fastblocks.actions.sync.strategies import SyncDirection, SyncStrategy 

80 from fastblocks.actions.sync.templates import sync_templates 

81 

82try: 

83 from fastblocks.actions.sync.strategies import SyncDirection, SyncStrategy 

84 from fastblocks.actions.sync.templates import sync_templates 

85except ImportError: 

86 sync_templates: t.Callable[..., t.Any] | None = None # type: ignore[no-redef] 

87 SyncDirection: type[Enum] | None = None # type: ignore[no-redef] 

88 SyncStrategy: type[object] | None = None # type: ignore[no-redef] 

89 

90# Placeholder for cache and storage (will be implemented with Oneiric) 

91Cache, Storage, Models = None, None, None 

92 

93 

94# Custom root_path implementation for Oneiric compatibility 

95def root_path(): 

96 """Custom implementation for Oneiric compatibility.""" 

97 # This will be implemented using Oneiric's path system 

98 return "/" 

99 

100 

101class ComponentNotFound(Exception): 

102 pass 

103 

104 

105class ComponentCompilationError(Exception): 

106 pass 

107 

108 

109class HTMYComponentRegistry: 

110 def __init__( 

111 self, 

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

113 cache: t.Any = None, 

114 storage: t.Any = None, 

115 ) -> None: 

116 self.searchpaths = searchpaths or [] 

117 self.cache = cache 

118 self.storage = storage 

119 self._component_cache: dict[str, t.Any] = {} 

120 self._source_cache: dict[str, str] = {} 

121 

122 @staticmethod 

123 def get_cache_key(component_path: AsyncPath, cache_type: str = "source") -> str: 

124 return f"htmy_component_{cache_type}:{component_path}" 

125 

126 @staticmethod 

127 def get_storage_path(component_path: AsyncPath) -> AsyncPath: 

128 return component_path 

129 

130 async def discover_components(self) -> dict[str, AsyncPath]: 

131 components = {} 

132 for search_path in self.searchpaths: 

133 if not await search_path.exists(): 

134 continue 

135 async for component_file in search_path.rglob("*.py"): 

136 if component_file.name == "__init__.py": 

137 continue 

138 component_name = component_file.stem 

139 components[component_name] = component_file 

140 

141 return components 

142 

143 async def _cache_component_source( 

144 self, component_path: AsyncPath, source: str 

145 ) -> None: 

146 if self.cache is not None: 

147 cache_key = self.get_cache_key(component_path) 

148 await self.cache.set(cache_key, source.encode()) 

149 

150 async def _cache_component_bytecode( 

151 self, component_path: AsyncPath, bytecode: bytes 

152 ) -> None: 

153 if self.cache is not None: 

154 cache_key = self.get_cache_key(component_path, "bytecode") 

155 await self.cache.set(cache_key, bytecode) 

156 

157 async def _get_cached_source(self, component_path: AsyncPath) -> str | None: 

158 if self.cache is not None: 

159 cache_key = self.get_cache_key(component_path) 

160 cached = await self.cache.get(cache_key) 

161 if cached: 

162 return t.cast(str, cached.decode()) 

163 return None 

164 

165 async def _get_cached_bytecode(self, component_path: AsyncPath) -> bytes | None: 

166 if self.cache is not None: 

167 cache_key = self.get_cache_key(component_path, "bytecode") 

168 result = await self.cache.get(cache_key) 

169 return t.cast(bytes, result) 

170 return None 

171 

172 async def _sync_component_file( 

173 self, 

174 path: AsyncPath, 

175 storage_path: AsyncPath, 

176 ) -> tuple[str, int]: 

177 if sync_templates is None or SyncDirection is None or SyncStrategy is None: 

178 return await self._sync_from_storage_fallback(path, storage_path) 

179 

180 try: 

181 strategy = SyncStrategy(backup_on_conflict=False) 

182 component_paths = [path] 

183 result = await sync_templates( 

184 template_paths=component_paths, 

185 strategy=strategy, 

186 ) 

187 

188 source = await path.read_text() 

189 local_stat = await path.stat() 

190 local_mtime = int(local_stat.st_mtime) 

191 

192 debug(f"Component sync result: {result.sync_status} for {path}") 

193 return source, local_mtime 

194 

195 except Exception as e: 

196 debug(f"Sync action failed for {path}: {e}, falling back to primitive sync") 

197 return await self._sync_from_storage_fallback(path, storage_path) 

198 

199 async def _sync_from_storage_fallback( 

200 self, 

201 path: AsyncPath, 

202 storage_path: AsyncPath, 

203 ) -> tuple[str, int]: 

204 local_stat = await path.stat() 

205 local_mtime = int(local_stat.st_mtime) 

206 

207 if self.storage is not None: 

208 try: 

209 local_size = local_stat.st_size 

210 storage_stat = await self.storage.templates.stat(storage_path) 

211 storage_mtime = round(storage_stat.get("mtime", 0)) 

212 storage_size = storage_stat.get("size", 0) 

213 

214 if local_mtime < storage_mtime and local_size != storage_size: 

215 resp = await self.storage.templates.open(storage_path) 

216 await path.write_bytes(resp) 

217 source = resp.decode() 

218 return source, storage_mtime 

219 except Exception as e: 

220 debug(f"Storage fallback failed for {path}: {e}") 

221 

222 source = await path.read_text() 

223 return source, local_mtime 

224 

225 async def get_component_source(self, component_name: str) -> tuple[str, AsyncPath]: 

226 components = await self.discover_components() 

227 if component_name not in components: 

228 raise ComponentNotFound(f"Component '{component_name}' not found") 

229 component_path = components[component_name] 

230 cache_key = str(component_path) 

231 if cache_key in self._source_cache: 

232 return self._source_cache[cache_key], component_path 

233 cached_source = await self._get_cached_source(component_path) 

234 if cached_source: 

235 self._source_cache[cache_key] = cached_source 

236 return cached_source, component_path 

237 storage_path = self.get_storage_path(component_path) 

238 source, _ = await self._sync_component_file(component_path, storage_path) 

239 self._source_cache[cache_key] = source 

240 await self._cache_component_source(component_path, source) 

241 

242 return source, component_path 

243 

244 async def get_component_class(self, component_name: str) -> t.Any: 

245 if component_name in self._component_cache: 

246 return self._component_cache[component_name] 

247 

248 source, component_path = await self.get_component_source(component_name) 

249 cached_bytecode = await self._get_cached_bytecode(component_path) 

250 

251 # Try to load from cached bytecode first 

252 if cached_bytecode: 

253 component_class = await self._load_from_cached_bytecode( 

254 cached_bytecode, source, component_path, component_name 

255 ) 

256 if component_class: 

257 return component_class 

258 

259 # Otherwise, load from source 

260 return await self._load_from_source(source, component_path, component_name) 

261 

262 async def _load_from_cached_bytecode( 

263 self, cached_bytecode, source, component_path, component_name 

264 ): 

265 """Attempt to load component class from cached bytecode.""" 

266 try: 

267 # Instead of using pickle, we'll compile the source directly 

268 # Pickle is a security risk as mentioned in the semgrep error 

269 compile(source, str(component_path), "exec") 

270 # Create a module-like namespace to execute the compiled code 

271 import importlib.util 

272 import tempfile 

273 

274 # Create a temporary module to safely load the component 

275 with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: 

276 f.write(source) 

277 temp_module_path = f.name 

278 

279 try: 

280 spec = importlib.util.spec_from_file_location( 

281 component_path.stem, temp_module_path 

282 ) 

283 if spec is None or spec.loader is None: 

284 raise ComponentCompilationError( 

285 f"Could not load module from {component_path}" 

286 ) 

287 

288 module = importlib.util.module_from_spec(spec) 

289 spec.loader.exec_module(module) 

290 

291 component_class = None 

292 for obj in vars(module).values(): 

293 if hasattr(obj, "htmy") and callable(getattr(obj, "htmy")): 

294 component_class = obj 

295 break 

296 finally: 

297 # Clean up the temporary file 

298 Path(temp_module_path).unlink() 

299 

300 # Cache the compiled form instead of pickle-able bytecode 

301 self._component_cache[component_name] = component_class 

302 return component_class 

303 except Exception as e: 

304 debug(f"Failed to load cached bytecode for {component_name}: {e}") 

305 return None 

306 

307 async def _load_from_source(self, source, component_path, component_name): 

308 """Load component class from source file.""" 

309 try: 

310 # Import and analyze component safely 

311 import importlib.util 

312 import tempfile 

313 

314 # Create a temporary module to safely load the component 

315 with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: 

316 f.write(source) 

317 temp_module_path = f.name 

318 

319 try: 

320 spec = importlib.util.spec_from_file_location( 

321 component_path.stem, temp_module_path 

322 ) 

323 if spec is None or spec.loader is None: 

324 raise ComponentCompilationError( 

325 f"Could not load module from {component_path}" 

326 ) 

327 

328 module = importlib.util.module_from_spec(spec) 

329 spec.loader.exec_module(module) 

330 

331 component_class = None 

332 for obj in vars(module).values(): 

333 if hasattr(obj, "htmy") and callable(getattr(obj, "htmy")): 

334 component_class = obj 

335 break 

336 finally: 

337 # Clean up the temporary file 

338 Path(temp_module_path).unlink() 

339 

340 self._component_cache[component_name] = component_class 

341 return component_class 

342 except Exception as e: 

343 raise ComponentCompilationError( 

344 f"Failed to compile component '{component_name}': {e}" 

345 ) from e 

346 

347 

348class HTMYTemplatesSettings(OneiricSettings): 

349 searchpaths: list[str] = [] 

350 cache_timeout: int = 300 

351 enable_bidirectional: bool = True 

352 debug_components: bool = False 

353 enable_hot_reload: bool = True 

354 enable_lifecycle_hooks: bool = True 

355 enable_component_validation: bool = True 

356 enable_advanced_registry: bool = True 

357 

358 def __init__(self, **values: t.Any) -> None: 

359 # Extract cache_timeout from values before passing to parent 

360 cache_timeout = values.pop("cache_timeout", 300) 

361 super().__init__(**values) 

362 # Set cache_timeout directly for Oneiric compatibility 

363 self.cache_timeout = cache_timeout 

364 

365 

366class HTMYTemplates(TemplatesBase): 

367 def __init__(self, **kwargs: t.Any) -> None: 

368 super().__init__(**kwargs) 

369 self.htmy_registry: HTMYComponentRegistry | None = None 

370 self.advanced_registry: AdvancedHTMYComponentRegistry | None = None 

371 self.component_searchpaths: list[AsyncPath] = [] 

372 self.jinja_templates: t.Any = None 

373 self.settings = HTMYTemplatesSettings(**kwargs) 

374 

375 # Register with Oneiric resolver (fail gracefully if not supported) 

376 with suppress(Exception): 

377 depends.set(self, "htmy") 

378 

379 async def get_component_searchpaths(self, app_adapter: t.Any) -> list[AsyncPath]: 

380 searchpaths = [] 

381 # Use Oneiric root_path 

382 base_root = AsyncPath(root_path()) 

383 debug(f"get_component_searchpaths: app_adapter={app_adapter}") 

384 if app_adapter: 

385 category = getattr(app_adapter, "category", "app") 

386 debug(f"get_component_searchpaths: using category={category}") 

387 template_paths = self.get_searchpath( 

388 app_adapter, base_root / "templates" / category 

389 ) 

390 debug(f"get_component_searchpaths: template_paths={template_paths}") 

391 for template_path in template_paths: 

392 component_path = template_path / "components" 

393 searchpaths.append(component_path) 

394 debug( 

395 f"get_component_searchpaths: added component_path={component_path}" 

396 ) 

397 debug(f"get_component_searchpaths: final searchpaths={searchpaths}") 

398 return searchpaths 

399 

400 async def _init_htmy_registry(self) -> None: 

401 if self.htmy_registry is not None and self.advanced_registry is not None: 

402 return 

403 

404 # Use Oneiric resolver to get app adapter 

405 try: 

406 app_adapter = depends.resolve("fastblocks", "app") 

407 except Exception: 

408 from types import SimpleNamespace 

409 

410 app_adapter = SimpleNamespace(name="app", category="app") 

411 

412 self.component_searchpaths = await self.get_component_searchpaths(app_adapter) 

413 

414 # Initialize advanced registry if enabled 

415 if self.settings.enable_advanced_registry: 

416 self.advanced_registry = AdvancedHTMYComponentRegistry( 

417 searchpaths=self.component_searchpaths, 

418 cache=self.cache, 

419 storage=self.storage, 

420 ) 

421 

422 # Configure hot reload 

423 if self.settings.enable_hot_reload: 

424 self.advanced_registry.enable_hot_reload() 

425 

426 # Keep legacy registry for backward compatibility 

427 self.htmy_registry = HTMYComponentRegistry( 

428 searchpaths=self.component_searchpaths, 

429 cache=self.cache, 

430 storage=self.storage, 

431 ) 

432 

433 async def clear_component_cache(self, component_name: str | None = None) -> None: 

434 if self.htmy_registry is None: 

435 return 

436 if component_name: 

437 self.htmy_registry._component_cache.pop(component_name, None) 

438 if self.cache: 

439 components = await self.htmy_registry.discover_components() 

440 if component_name in components: 

441 component_path = components[component_name] 

442 source_key = HTMYComponentRegistry.get_cache_key(component_path) 

443 bytecode_key = HTMYComponentRegistry.get_cache_key( 

444 component_path, "bytecode" 

445 ) 

446 await self.cache.delete(source_key) 

447 await self.cache.delete(bytecode_key) 

448 debug(f"HTMY component cache cleared for: {component_name}") 

449 else: 

450 self.htmy_registry._component_cache.clear() 

451 self.htmy_registry._source_cache.clear() 

452 if self.cache: 

453 with suppress(NotImplementedError, AttributeError): 

454 await self.cache.clear("htmy_component_source") 

455 await self.cache.clear("htmy_component_bytecode") 

456 debug("All HTMY component caches cleared") 

457 

458 async def get_component_class(self, component_name: str) -> t.Any: 

459 if self.htmy_registry is None: 

460 await self._init_htmy_registry() 

461 

462 if self.htmy_registry is not None: 

463 return await self.htmy_registry.get_component_class(component_name) 

464 raise ComponentNotFound( 

465 f"Component registry not initialized for '{component_name}'" 

466 ) 

467 

468 async def render_component_advanced( 

469 self, 

470 request: t.Any, 

471 component: str, 

472 context: dict[str, t.Any] | None = None, 

473 status_code: int = 200, 

474 headers: dict[str, str] | None = None, 

475 **kwargs: t.Any, 

476 ) -> HTMLResponse: 

477 """Render component using advanced registry with lifecycle management.""" 

478 if context is None: 

479 context = {} 

480 if headers is None: 

481 headers = {} 

482 

483 if self.advanced_registry is None: 

484 await self._init_htmy_registry() 

485 

486 if self.advanced_registry is None: 

487 raise ComponentRenderError( 

488 f"Advanced registry not initialized for '{component}'" 

489 ) 

490 

491 try: 

492 # Add kwargs to context 

493 enhanced_context = context | kwargs 

494 

495 rendered_content = ( 

496 await self.advanced_registry.render_component_with_lifecycle( 

497 component, enhanced_context, request 

498 ) 

499 ) 

500 

501 return HTMLResponse( 

502 content=rendered_content, 

503 status_code=status_code, 

504 headers=headers, 

505 ) 

506 

507 except Exception as e: 

508 error_content = ( 

509 f"<html><body>Component {component} error: {e}</body></html>" 

510 ) 

511 if self.settings.debug_components: 

512 import traceback 

513 

514 error_content = f"<html><body><h3>Component {component} error:</h3><pre>{traceback.format_exc()}</pre></body></html>" 

515 

516 return HTMLResponse( 

517 content=error_content, 

518 status_code=500, 

519 headers=headers, 

520 ) 

521 

522 async def render_component( 

523 self, 

524 request: t.Any, 

525 component: str, 

526 context: dict[str, t.Any] | None = None, 

527 status_code: int = 200, 

528 headers: dict[str, str] | None = None, 

529 **kwargs: t.Any, 

530 ) -> HTMLResponse: 

531 if context is None: 

532 context = {} 

533 if headers is None: 

534 headers = {} 

535 

536 # Use advanced registry if available and enabled 

537 if ( 

538 self.settings.enable_advanced_registry 

539 and self.advanced_registry is not None 

540 ): 

541 return await self.render_component_advanced( 

542 request, component, context, status_code, headers, **kwargs 

543 ) 

544 

545 if self.htmy_registry is None: 

546 await self._init_htmy_registry() 

547 

548 if self.htmy_registry is None: 

549 raise ComponentNotFound( 

550 f"Component registry not initialized for '{component}'" 

551 ) 

552 

553 try: 

554 component_class = await self.htmy_registry.get_component_class(component) 

555 

556 component_instance = component_class(**context, **kwargs) 

557 

558 htmy_context = { 

559 "request": request, 

560 **context, 

561 "render_template": self._create_template_renderer(request), 

562 "render_block": self._create_block_renderer(request), 

563 "_template_system": "htmy", 

564 "_request": request, 

565 } 

566 

567 if asyncio.iscoroutinefunction(component_instance.htmy): 

568 rendered_content = await component_instance.htmy(htmy_context) 

569 else: 

570 rendered_content = component_instance.htmy(htmy_context) 

571 

572 html_content = str(rendered_content) 

573 

574 return HTMLResponse( 

575 content=html_content, 

576 status_code=status_code, 

577 headers=headers, 

578 ) 

579 

580 except (ComponentNotFound, ComponentCompilationError) as e: 

581 return HTMLResponse( 

582 content=f"<html><body>Component {component} error: {e}</body></html>", 

583 status_code=404, 

584 headers=headers, 

585 ) 

586 

587 def _create_template_renderer( 

588 self, request: t.Any = None 

589 ) -> t.Callable[..., t.Any]: 

590 async def render_template( 

591 template_name: str, 

592 context: dict[str, t.Any] | None = None, 

593 inherit_context: bool = True, # noqa: ARG001 

594 **kwargs: t.Any, 

595 ) -> str: 

596 if context is None: 

597 context = {} 

598 

599 template_context = context | kwargs 

600 

601 if self.jinja_templates and hasattr(self.jinja_templates, "app"): 

602 try: 

603 template = self.jinja_templates.app.get_template(template_name) 

604 if asyncio.iscoroutinefunction(template.render): 

605 rendered = await template.render(template_context) 

606 else: 

607 rendered = template.render(template_context) 

608 return t.cast(str, rendered) 

609 except Exception as e: 

610 debug( 

611 f"Failed to render template '{template_name}' in HTMY component: {e}" 

612 ) 

613 return f"<!-- Error rendering template '{template_name}': {e} -->" 

614 else: 

615 debug( 

616 f"No Jinja2 adapter available to render template '{template_name}' in HTMY component" 

617 ) 

618 return f"<!-- No template renderer available for '{template_name}' -->" 

619 

620 return render_template 

621 

622 async def discover_components(self) -> dict[str, ComponentMetadata]: 

623 """Discover all components and return metadata.""" 

624 if self.advanced_registry is None: 

625 await self._init_htmy_registry() 

626 

627 if self.advanced_registry is not None: 

628 return await self.advanced_registry.discover_components() 

629 

630 # Fallback to basic discovery 

631 components = {} 

632 if self.htmy_registry is not None: 

633 discovered = await self.htmy_registry.discover_components() 

634 for name, path in discovered.items(): 

635 components[name] = ComponentMetadata( 

636 name=name, 

637 path=path, 

638 type=ComponentType.BASIC, 

639 status=ComponentStatus.DISCOVERED, 

640 ) 

641 return components 

642 

643 async def scaffold_component( 

644 self, 

645 name: str, 

646 component_type: ComponentType = ComponentType.DATACLASS, 

647 props: dict[str, type] | None = None, 

648 htmx_enabled: bool = False, 

649 endpoint: str = "", 

650 trigger: str = "click", 

651 target: str = "#content", 

652 children: list[str] | None = None, 

653 target_path: AsyncPath | None = None, 

654 ) -> AsyncPath: 

655 """Scaffold a new component.""" 

656 if self.advanced_registry is None: 

657 await self._init_htmy_registry() 

658 

659 if self.advanced_registry is None: 

660 raise ComponentRenderError( 

661 "Advanced registry not available for scaffolding" 

662 ) 

663 

664 kwargs: dict[str, Any] = {} 

665 if props: 

666 kwargs["props"] = props 

667 if htmx_enabled: 

668 kwargs["htmx_enabled"] = True 

669 if endpoint: 

670 kwargs["endpoint"] = endpoint 

671 kwargs["trigger"] = trigger 

672 kwargs["target"] = target 

673 if children: 

674 kwargs["children"] = children 

675 

676 return await self.advanced_registry.scaffold_component( 

677 name, component_type, target_path, **kwargs 

678 ) 

679 

680 async def validate_component(self, component_name: str) -> ComponentMetadata: 

681 """Validate a specific component.""" 

682 components = await self.discover_components() 

683 if component_name not in components: 

684 raise ComponentNotFound(f"Component '{component_name}' not found") 

685 

686 return components[component_name] 

687 

688 def get_lifecycle_manager(self) -> ComponentLifecycleManager | None: 

689 """Get the component lifecycle manager.""" 

690 if self.advanced_registry is not None: 

691 return self.advanced_registry.lifecycle_manager 

692 return None 

693 

694 def register_lifecycle_hook( 

695 self, event: str, callback: t.Callable[..., Any] 

696 ) -> None: 

697 """Register a lifecycle hook.""" 

698 lifecycle_manager = self.get_lifecycle_manager() 

699 if lifecycle_manager is not None: 

700 lifecycle_manager.register_hook(event, callback) 

701 

702 def _create_block_renderer(self, request: t.Any = None) -> t.Callable[..., t.Any]: 

703 async def render_block( 

704 block_name: str, context: dict[str, t.Any] | None = None, **kwargs: t.Any 

705 ) -> str: 

706 if context is None: 

707 context = {} 

708 

709 block_context = context | kwargs 

710 

711 if ( 

712 self.jinja_templates 

713 and hasattr(self.jinja_templates, "app") 

714 and hasattr(self.jinja_templates.app, "render_block") 

715 ): 

716 try: 

717 if asyncio.iscoroutinefunction( 

718 self.jinja_templates.app.render_block 

719 ): 

720 rendered = await self.jinja_templates.app.render_block( 

721 block_name, block_context 

722 ) 

723 else: 

724 rendered = self.jinja_templates.app.render_block( 

725 block_name, block_context 

726 ) 

727 return t.cast(str, rendered) 

728 except Exception as e: 

729 debug( 

730 f"Failed to render block '{block_name}' in HTMY component: {e}" 

731 ) 

732 return f"<!-- Error rendering block '{block_name}': {e} -->" 

733 else: 

734 debug( 

735 f"No block renderer available for '{block_name}' in HTMY component" 

736 ) 

737 return f"<!-- No block renderer available for '{block_name}' -->" 

738 

739 return render_block 

740 

741 async def init(self, cache: t.Any | None = None) -> None: 

742 if cache is None: 

743 try: 

744 cache = depends.resolve("fastblocks", "cache") 

745 except Exception: 

746 cache = None 

747 self.cache = cache 

748 try: 

749 self.storage = depends.resolve("fastblocks", "storage") 

750 except Exception: 

751 self.storage = None 

752 await self._init_htmy_registry() 

753 try: 

754 self.jinja_templates = depends.resolve("fastblocks", "templates") 

755 except Exception: 

756 self.jinja_templates = None 

757 # Already registered in __init__, but ensure it's set (fail gracefully) 

758 with suppress(Exception): 

759 depends.set("htmy", self) 

760 debug("HTMY Templates adapter initialized") 

761 

762 async def render_template( 

763 self, 

764 request: t.Any, 

765 template: str, 

766 context: dict[str, t.Any] | None = None, 

767 status_code: int = 200, 

768 headers: dict[str, str] | None = None, 

769 ) -> HTMLResponse: 

770 return await self.render_component( 

771 request=request, 

772 component=template, 

773 context=context, 

774 status_code=status_code, 

775 headers=headers, 

776 ) 

777 

778 

779MODULE_ID = UUID("01937d86-e1f2-7890-abcd-ef1234567890") 

780MODULE_STATUS = AdapterStatus.STABLE if AdapterStatus is not None else None 

781 

782TemplatesSettings = HTMYTemplatesSettings 

783Templates = HTMYTemplates 

784 

785# Register with Oneiric resolver (fail gracefully if not supported) 

786with suppress(Exception): 

787 depends.set(Templates, "htmy") 

788 

789__all__ = ["Templates", "TemplatesSettings", "HTMYTemplatesSettings", "HTMYTemplates"]