Coverage for fastblocks / actions / gather / templates.py: 49%

272 statements  

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

1"""Template component gathering to consolidate loader, extension, processor, and filter collection.""" 

2 

3import typing as t 

4from contextlib import suppress 

5from importlib import import_module 

6from inspect import isclass 

7 

8from oneiric.core.logging import get_logger 

9from oneiric.core.resolution import Resolver 

10 

11 

12# Create debug function for Oneiric 

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

14 """Debug logging function.""" 

15 logger = get_logger("fastblocks.actions.gather.templates") 

16 logger.debug(msg) 

17 

18 

19# Create resolver instance 

20depends = Resolver() 

21 

22 

23from anyio import Path as AsyncPath 

24from jinja2.ext import Extension 

25 

26from .strategies import GatherStrategy, gather_with_strategy 

27 

28 

29class TemplateGatherResult: 

30 def __init__( 

31 self, 

32 *, 

33 loaders: list[t.Any] | None = None, 

34 extensions: list[t.Any] | None = None, 

35 context_processors: list[t.Callable[..., t.Any]] | None = None, 

36 filters: dict[str, t.Callable[..., t.Any]] | None = None, 

37 globals: dict[str, t.Any] | None = None, 

38 errors: list[Exception] | None = None, 

39 ) -> None: 

40 self.loaders = loaders if loaders is not None else [] 

41 self.extensions = extensions if extensions is not None else [] 

42 self.context_processors = ( 

43 context_processors if context_processors is not None else [] 

44 ) 

45 self.filters = filters if filters is not None else {} 

46 self.globals = globals if globals is not None else {} 

47 self.errors = errors if errors is not None else [] 

48 

49 @property 

50 def total_components(self) -> int: 

51 return ( 

52 len(self.loaders) 

53 + len(self.extensions) 

54 + len(self.context_processors) 

55 + len(self.filters) 

56 + len(self.globals) 

57 ) 

58 

59 @property 

60 def has_errors(self) -> bool: 

61 return len(self.errors) > 0 

62 

63 

64async def gather_templates( 

65 *, 

66 template_paths: list[AsyncPath] | None = None, 

67 loader_types: list[str] | None = None, 

68 extension_modules: list[str] | None = None, 

69 context_processor_paths: list[str] | None = None, 

70 filter_modules: list[str] | None = None, 

71 admin_mode: bool = False, 

72 strategy: GatherStrategy | None = None, 

73) -> TemplateGatherResult: 

74 config = _prepare_template_gather_config( 

75 template_paths, 

76 loader_types, 

77 extension_modules, 

78 context_processor_paths, 

79 filter_modules, 

80 admin_mode, 

81 strategy, 

82 ) 

83 result = TemplateGatherResult() 

84 

85 tasks = _build_template_gather_tasks(config) 

86 

87 gather_result = await gather_with_strategy( 

88 tasks, 

89 config["strategy"], 

90 cache_key=f"templates:{admin_mode}:{':'.join(config['loader_types'])}", 

91 ) 

92 

93 _process_template_gather_results(gather_result, result) 

94 

95 result.errors.extend(gather_result.errors) 

96 debug(f"Gathered {result.total_components} template components") 

97 

98 return result 

99 

100 

101def _prepare_template_gather_config( 

102 template_paths: list[AsyncPath] | None, 

103 loader_types: list[str] | None, 

104 extension_modules: list[str] | None, 

105 context_processor_paths: list[str] | None, 

106 filter_modules: list[str] | None, 

107 admin_mode: bool, 

108 strategy: GatherStrategy | None, 

109) -> dict[str, t.Any]: 

110 if loader_types is None: 

111 loader_types = ["redis", "storage", "filesystem"] 

112 if admin_mode: 

113 loader_types.append("package") 

114 

115 return { 

116 "template_paths": template_paths 

117 if template_paths is not None 

118 else [AsyncPath("templates")], 

119 "loader_types": loader_types, 

120 "extension_modules": extension_modules, 

121 "context_processor_paths": context_processor_paths, 

122 "filter_modules": filter_modules, 

123 "admin_mode": admin_mode, 

124 "strategy": strategy or GatherStrategy(), 

125 } 

126 

127 

128def _build_template_gather_tasks( 

129 config: dict[str, t.Any], 

130) -> list[t.Coroutine[t.Any, t.Any, t.Any]]: 

131 tasks = [] 

132 

133 tasks.append( 

134 _gather_loaders( 

135 config["template_paths"], 

136 config["loader_types"], 

137 config["admin_mode"], 

138 ), 

139 ) 

140 

141 if config["extension_modules"]: 

142 tasks.append(_gather_extensions(config["extension_modules"])) 

143 else: 

144 tasks.append(_gather_default_extensions()) 

145 

146 if config["context_processor_paths"]: 

147 tasks.append(_gather_context_processors(config["context_processor_paths"])) 

148 else: 

149 tasks.append(_gather_default_context_processors()) 

150 

151 if config["filter_modules"]: 

152 tasks.append(_gather_filters(config["filter_modules"])) 

153 else: 

154 tasks.append(_gather_default_filters()) 

155 

156 tasks.append(_gather_template_globals()) 

157 

158 return tasks 

159 

160 

161def _process_template_gather_results( 

162 gather_result: t.Any, 

163 result: TemplateGatherResult, 

164) -> None: 

165 component_mapping = [ 

166 "loaders", 

167 "extensions", 

168 "context_processors", 

169 "filters", 

170 "globals", 

171 ] 

172 

173 for i, success in enumerate(gather_result.success): 

174 if i < len(component_mapping): 

175 setattr(result, component_mapping[i], success) 

176 

177 

178async def _gather_loaders( 

179 template_paths: list[AsyncPath], 

180 loader_types: list[str], 

181 admin_mode: bool, 

182) -> list[t.Any]: 

183 try: 

184 jinja2_module = __import__( 

185 "fastblocks.adapters.templates.jinja2", 

186 fromlist=[ 

187 "ChoiceLoader", 

188 "FileSystemLoader", 

189 "PackageLoader", 

190 "RedisLoader", 

191 "StorageLoader", 

192 ], 

193 ) 

194 jinja2_module.ChoiceLoader 

195 FileSystemLoader = jinja2_module.FileSystemLoader 

196 PackageLoader = jinja2_module.PackageLoader 

197 RedisLoader = jinja2_module.RedisLoader 

198 StorageLoader = jinja2_module.StorageLoader 

199 except (ImportError, AttributeError) as e: 

200 debug(f"Error loading template loader classes: {e}") 

201 raise 

202 

203 searchpaths: list[AsyncPath] = [] 

204 for path in template_paths: 

205 searchpaths.extend([path, path / "blocks"]) 

206 

207 loaders = [] 

208 

209 if "redis" in loader_types: 

210 loaders.append(RedisLoader(searchpaths)) 

211 

212 if "storage" in loader_types: 

213 loaders.append(StorageLoader(searchpaths)) 

214 

215 if "filesystem" in loader_types: 

216 loaders.append(FileSystemLoader(searchpaths)) 

217 

218 if "package" in loader_types and admin_mode: 

219 try: 

220 # MIGRATED: Removed ACB import - using Oneiric equivalent 

221 

222 enabled_admin = get_adapter("admin") 

223 if enabled_admin: 

224 loaders.append(PackageLoader(enabled_admin.name, "templates", "admin")) 

225 except Exception as e: 

226 debug(f"Could not create package loader: {e}") 

227 

228 debug(f"Created {len(loaders)} template loaders") 

229 return loaders 

230 

231 

232async def _gather_extensions(extension_modules: list[str]) -> list[t.Any]: 

233 extensions = [] 

234 from jinja2.ext import debug as jinja_debug 

235 from jinja2.ext import i18n, loopcontrols 

236 

237 extensions.extend([loopcontrols, i18n, jinja_debug]) 

238 for module_path in extension_modules: 

239 try: 

240 module = import_module(module_path) 

241 for attr_name in dir(module): 

242 attr = getattr(module, attr_name) 

243 if ( 

244 isclass(attr) 

245 and attr.__name__ != "Extension" 

246 and issubclass(attr, Extension) 

247 ): 

248 extensions.append(attr) 

249 debug(f"Found extension {attr.__name__} in {module_path}") 

250 except Exception as e: 

251 debug(f"Error loading extensions from {module_path}: {e}") 

252 debug(f"Gathered {len(extensions)} Jinja2 extensions") 

253 return extensions 

254 

255 

256async def _gather_default_extensions() -> list[t.Any]: 

257 from jinja2.ext import debug as jinja_debug 

258 from jinja2.ext import i18n, loopcontrols 

259 

260 extensions = [loopcontrols, i18n, jinja_debug] 

261 await _load_config_extensions(extensions) 

262 

263 return extensions 

264 

265 

266async def _load_config_extensions(extensions: list[t.Any]) -> None: 

267 with suppress(Exception): 

268 # MIGRATED: Removed ACB import - using Oneiric equivalent 

269 

270 config = await depends.resolve("fastblocks", "config") 

271 if _has_template_extensions_config(config): 

272 _process_extension_paths(config.templates.extensions, extensions) 

273 

274 

275def _has_template_extensions_config(config: t.Any) -> bool: 

276 return hasattr(config, "templates") and hasattr(config.templates, "extensions") 

277 

278 

279def _process_extension_paths(ext_paths: list[str], extensions: list[t.Any]) -> None: 

280 for ext_path in ext_paths: 

281 try: 

282 module = import_module(ext_path) 

283 _extract_extension_classes_from_module(module, extensions) 

284 except Exception as e: 

285 debug(f"Error loading extension {ext_path}: {e}") 

286 

287 

288def _extract_extension_classes_from_module( 

289 module: t.Any, 

290 extensions: list[t.Any], 

291) -> None: 

292 for attr_name in dir(module): 

293 attr = getattr(module, attr_name) 

294 if _is_valid_extension_class(attr): 

295 extensions.append(attr) 

296 

297 

298def _is_valid_extension_class(attr: t.Any) -> bool: 

299 return ( 

300 isclass(attr) and attr.__name__ != "Extension" and issubclass(attr, Extension) 

301 ) 

302 

303 

304async def _gather_context_processors( 

305 processor_paths: list[str], 

306) -> list[t.Callable[..., t.Any]]: 

307 processors = [] 

308 for processor_path in processor_paths: 

309 try: 

310 module_path, func_name = processor_path.rsplit(".", 1) 

311 module = import_module(module_path) 

312 processor = getattr(module, func_name) 

313 if callable(processor): 

314 processors.append(processor) 

315 debug(f"Found context processor {func_name} in {module_path}") 

316 else: 

317 debug(f"Context processor {func_name} is not callable") 

318 except Exception as e: 

319 debug(f"Error loading context processor {processor_path}: {e}") 

320 debug(f"Gathered {len(processors)} context processors") 

321 return processors 

322 

323 

324async def _gather_default_context_processors() -> list[t.Callable[..., t.Any]]: 

325 processors = [] 

326 with suppress(Exception): 

327 # MIGRATED: Removed ACB import - using Oneiric equivalent 

328 

329 config = await depends.resolve("fastblocks", "config") 

330 if hasattr(config, "templates") and hasattr( 

331 config.templates, 

332 "context_processors", 

333 ): 

334 for processor_path in config.templates.context_processors: 

335 try: 

336 module_path, func_name = processor_path.rsplit(".", 1) 

337 module = import_module(module_path) 

338 processor = getattr(module, func_name) 

339 if callable(processor): 

340 processors.append(processor) 

341 except Exception as e: 

342 debug(f"Error loading context processor {processor_path}: {e}") 

343 

344 return processors 

345 

346 

347async def _gather_filters( 

348 filter_modules: list[str], 

349) -> list[dict[str, t.Callable[..., t.Any]]]: 

350 filters: dict[str, t.Callable[..., t.Any]] = {} 

351 for module_path in filter_modules: 

352 try: 

353 module = import_module(module_path) 

354 _extract_filters_from_module(module, module_path, filters) 

355 except Exception as e: 

356 debug(f"Error loading filters from {module_path}: {e}") 

357 debug(f"Gathered {len(filters)} template filters") 

358 return [filters] 

359 

360 

361def _extract_filters_from_module( 

362 module: t.Any, 

363 module_path: str, 

364 filters: dict[str, t.Callable[..., t.Any]], 

365) -> None: 

366 if hasattr(module, "Filters"): 

367 filters_class = module.Filters 

368 _extract_filters_from_class(filters_class, module_path, filters) 

369 

370 _extract_filter_functions(module, module_path, filters) 

371 

372 

373def _extract_filters_from_class( 

374 filters_class: t.Any, 

375 module_path: str, 

376 filters: dict[str, t.Callable[..., t.Any]], 

377) -> None: 

378 for attr_name in dir(filters_class): 

379 if not attr_name.startswith("_"): 

380 attr = getattr(filters_class, attr_name) 

381 if callable(attr): 

382 filters[attr_name] = attr 

383 debug(f"Found filter {attr_name} in {module_path}") 

384 

385 

386def _extract_filter_functions( 

387 module: t.Any, 

388 module_path: str, 

389 filters: dict[str, t.Callable[..., t.Any]], 

390) -> None: 

391 for attr_name in dir(module): 

392 if attr_name.endswith("_filter") and not attr_name.startswith("_"): 

393 attr = getattr(module, attr_name) 

394 if callable(attr): 

395 filter_name = attr_name.removesuffix("_filter") 

396 filters[filter_name] = attr 

397 debug(f"Found filter function {filter_name} in {module_path}") 

398 

399 

400async def _gather_default_filters() -> list[dict[str, t.Callable[..., t.Any]]]: 

401 filters: dict[str, t.Callable[..., t.Any]] = {} 

402 try: 

403 filters_module = __import__( 

404 "fastblocks.adapters.templates._filters", 

405 fromlist=["Filters"], 

406 ) 

407 filters = getattr(filters_module, "Filters", {}) 

408 except Exception as e: 

409 debug(f"Error loading default filters: {e}") 

410 debug(f"Gathered {len(filters)} default template filters") 

411 return [filters] 

412 

413 

414async def _gather_template_globals() -> list[dict[str, t.Any]]: 

415 globals_dict = {} 

416 try: 

417 # MIGRATED: Removed ACB import - using Oneiric equivalent 

418 

419 config = await depends.resolve("fastblocks", "config") 

420 globals_dict["config"] = config 

421 try: 

422 models = await depends.resolve("fastblocks", "models") 

423 globals_dict["models"] = models 

424 except Exception: 

425 globals_dict["models"] = None 

426 if hasattr(config, "templates") and hasattr(config.templates, "globals"): 

427 globals_dict.update(config.templates.globals) 

428 except Exception as e: 

429 debug(f"Error gathering template globals: {e}") 

430 

431 return [globals_dict] 

432 

433 

434def _get_filesystem_loaders(loaders: list[t.Any]) -> list[t.Any]: 

435 """Get filesystem loaders from the list of loaders.""" 

436 return [loader for loader in loaders if "FileSystem" in str(type(loader))] 

437 

438 

439def _get_non_filesystem_loaders(loaders: list[t.Any]) -> list[t.Any]: 

440 """Get non-filesystem loaders from the list of loaders.""" 

441 return [loader for loader in loaders if "FileSystem" not in str(type(loader))] 

442 

443 

444def _get_cache_loaders(loaders: list[t.Any]) -> list[t.Any]: 

445 """Get cache loaders from the list of loaders.""" 

446 return [ 

447 loader 

448 for loader in loaders 

449 if any(x in str(type(loader)) for x in ("Redis", "Storage")) 

450 ] 

451 

452 

453def _get_non_cache_loaders(loaders: list[t.Any]) -> list[t.Any]: 

454 """Get non-cache loaders from the list of loaders.""" 

455 return [ 

456 loader 

457 for loader in loaders 

458 if not any(x in str(type(loader)) for x in ("Redis", "Storage")) 

459 ] 

460 

461 

462async def create_choice_loader( 

463 loaders: list[t.Any], 

464 config: t.Any | None = None, 

465) -> t.Any: 

466 try: 

467 jinja2_module = __import__( 

468 "fastblocks.adapters.templates.jinja2", 

469 fromlist=["ChoiceLoader"], 

470 ) 

471 ChoiceLoader = jinja2_module.ChoiceLoader 

472 except (ImportError, AttributeError) as e: 

473 debug(f"Error loading ChoiceLoader: {e}") 

474 raise 

475 

476 ordered_loaders = [] 

477 

478 if config and not getattr(config, "deployed", False): 

479 filesystem_loaders = _get_filesystem_loaders(loaders) 

480 other_loaders = _get_non_filesystem_loaders(loaders) 

481 ordered_loaders = filesystem_loaders + other_loaders 

482 else: 

483 cache_loaders = _get_cache_loaders(loaders) 

484 other_loaders = _get_non_cache_loaders(loaders) 

485 ordered_loaders = cache_loaders + other_loaders 

486 

487 debug(f"Created ChoiceLoader with {len(ordered_loaders)} loaders") 

488 return ChoiceLoader(ordered_loaders) 

489 

490 

491async def create_template_environment( 

492 gather_result: TemplateGatherResult, 

493 cache: t.Any | None = None, 

494) -> t.Any: 

495 from jinja2_async_environment.bccache import AsyncRedisBytecodeCache 

496 from starlette_async_jinja import AsyncJinja2Templates 

497 

498 bytecode_cache = AsyncRedisBytecodeCache(prefix="bccache", client=cache) 

499 

500 choice_loader = await create_choice_loader(gather_result.loaders) 

501 

502 templates = AsyncJinja2Templates( 

503 directory=AsyncPath("templates"), 

504 context_processors=gather_result.context_processors, 

505 extensions=gather_result.extensions, 

506 bytecode_cache=bytecode_cache, 

507 enable_async=True, 

508 ) 

509 

510 if choice_loader: 

511 templates.env.loader = choice_loader 

512 

513 for name, value in gather_result.globals.items(): 

514 templates.env.globals[name] = value 

515 

516 for name, filter_func in gather_result.filters.items(): 

517 templates.env.filters[name] = filter_func 

518 

519 templates.env.block_start_string = "[%" 

520 templates.env.block_end_string = "%]" 

521 templates.env.variable_start_string = "[[" 

522 templates.env.variable_end_string = "]]" 

523 templates.env.comment_start_string = "[#" 

524 templates.env.comment_end_string = "#]" 

525 

526 debug("Created Jinja2 environment with gathered components") 

527 return templates 

528 

529 

530def register_template_filters( 

531 templates: t.Any, 

532 filters: dict[str, t.Callable[..., t.Any]], 

533) -> None: 

534 for name, filter_func in filters.items(): 

535 if hasattr(templates, "filter"): 

536 templates.filter(name)(filter_func) 

537 else: 

538 templates.env.filters[name] = filter_func 

539 

540 debug(f"Registered {len(filters)} template filters") 

541 

542 

543# Migration status indicator 

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

545_using_oneiric = True # Oneiric resolver available 

546_requires_further_migration = True # ACB debug system needs migration