Coverage for fastblocks / actions / gather / application.py: 56%

249 statements  

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

1"""Application component gathering and initialization orchestration.""" 

2 

3import typing as t 

4from importlib import import_module 

5 

6from oneiric.core.resolution import Resolver 

7 

8# Migration from ACB to Oneiric 

9# Note: This file heavily depends on ACB's adapter system which requires 

10# special handling for Oneiric migration 

11depends = Resolver() 

12 

13 

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

15 """Debug function fallback for Oneiric migration.""" 

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

17 

18 

19def get_adapters(): 

20 """Adapter fallback - returns empty list for Oneiric mode.""" 

21 return [] 

22 

23 

24from .strategies import GatherStrategy, gather_with_strategy 

25 

26 

27class ApplicationGatherResult: 

28 def __init__( 

29 self, 

30 *, 

31 adapters: dict[str, t.Any] | None = None, 

32 acb_modules: dict[str, t.Any] | None = None, 

33 dependencies: dict[str, t.Any] | None = None, 

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

35 config: t.Any | None = None, 

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

37 ) -> None: 

38 self.adapters = adapters if adapters is not None else {} 

39 self.acb_modules = acb_modules if acb_modules is not None else {} 

40 self.dependencies = dependencies if dependencies is not None else {} 

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

42 self.config = config 

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

44 

45 @property 

46 def total_components(self) -> int: 

47 return ( 

48 len(self.adapters) 

49 + len(self.acb_modules) 

50 + len(self.dependencies) 

51 + len(self.initializers) 

52 ) 

53 

54 @property 

55 def has_errors(self) -> bool: 

56 return len(self.errors) > 0 

57 

58 

59async def gather_application( 

60 *, 

61 include_adapters: bool = True, 

62 include_acb_modules: bool = True, 

63 include_dependencies: bool = True, 

64 include_initializers: bool = True, 

65 adapter_patterns: list[str] | None = None, 

66 dependency_patterns: list[str] | None = None, 

67 strategy: GatherStrategy | None = None, 

68) -> ApplicationGatherResult: 

69 config = _prepare_application_gather_config( 

70 adapter_patterns, 

71 dependency_patterns, 

72 strategy, 

73 ) 

74 result = ApplicationGatherResult() 

75 

76 tasks = _build_application_gather_tasks( 

77 config, 

78 include_adapters, 

79 include_acb_modules, 

80 include_dependencies, 

81 include_initializers, 

82 ) 

83 

84 gather_result = await gather_with_strategy( 

85 tasks, 

86 config["strategy"], 

87 cache_key=f"application:{include_adapters}:{include_acb_modules}:{':'.join(config['dependency_patterns'])}", 

88 ) 

89 

90 _process_application_gather_results( 

91 gather_result, 

92 result, 

93 include_adapters, 

94 include_acb_modules, 

95 include_dependencies, 

96 include_initializers, 

97 ) 

98 

99 await _gather_application_config(result) 

100 

101 result.errors.extend(gather_result.errors) 

102 debug(f"Gathered {result.total_components} application components") 

103 

104 return result 

105 

106 

107def _prepare_application_gather_config( 

108 adapter_patterns: list[str] | None, 

109 dependency_patterns: list[str] | None, 

110 strategy: GatherStrategy | None, 

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

112 return { 

113 "adapter_patterns": adapter_patterns 

114 or ["__init__.py", "models.py", "views.py"], 

115 "dependency_patterns": dependency_patterns 

116 or ["models", "config", "cache", "database"], 

117 "strategy": strategy or GatherStrategy(), 

118 } 

119 

120 

121def _build_application_gather_tasks( 

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

123 include_adapters: bool, 

124 include_acb_modules: bool, 

125 include_dependencies: bool, 

126 include_initializers: bool, 

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

128 tasks: list[t.Coroutine[t.Any, t.Any, t.Any]] = [] 

129 

130 if include_adapters: 

131 tasks.append(_gather_adapters_and_modules(config["adapter_patterns"])) 

132 if include_acb_modules: 

133 tasks.append(_gather_acb_modules()) 

134 if include_dependencies: 

135 tasks.append(_gather_application_dependencies(config["dependency_patterns"])) 

136 if include_initializers: 

137 tasks.append(_gather_initializers()) 

138 

139 return tasks 

140 

141 

142def _process_application_gather_results( 

143 gather_result: t.Any, 

144 result: ApplicationGatherResult, 

145 include_adapters: bool, 

146 include_acb_modules: bool, 

147 include_dependencies: bool, 

148 include_initializers: bool, 

149) -> None: 

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

151 task_index = 0 

152 

153 if include_adapters and i == task_index: 

154 result.adapters = success.get("adapters", {}) 

155 result.acb_modules.update(success.get("adapter_modules", {})) 

156 task_index += 1 

157 continue 

158 

159 if include_acb_modules and i == task_index: 

160 result.acb_modules.update(success) 

161 task_index += 1 

162 continue 

163 

164 if include_dependencies and i == task_index: 

165 result.dependencies = success 

166 task_index += 1 

167 continue 

168 

169 if include_initializers and i == task_index: 

170 result.initializers = success 

171 

172 

173async def _gather_application_config(result: ApplicationGatherResult) -> None: 

174 try: 

175 result.config = await _gather_config() 

176 except Exception as e: 

177 result.errors.append(e) 

178 

179 

180async def _gather_adapters_and_modules(adapter_patterns: list[str]) -> dict[str, t.Any]: 

181 adapters_info: dict[str, t.Any] = { 

182 "adapters": {}, 

183 "adapter_modules": {}, 

184 } 

185 for adapter in get_adapters(): 

186 adapter_name = adapter.name 

187 adapters_info["adapters"][adapter_name] = adapter 

188 for pattern in adapter_patterns: 

189 try: 

190 if pattern == "__init__.py": 

191 module_path = f"acb.adapters.{adapter_name}" 

192 module = import_module(module_path) 

193 adapters_info["adapter_modules"][f"{adapter_name}_init"] = module 

194 debug(f"Loaded adapter module: {module_path}") 

195 elif pattern.endswith(".py"): 

196 module_name = pattern.removesuffix(".py") 

197 module_path = f"acb.adapters.{adapter_name}.{module_name}" 

198 try: 

199 module = import_module(module_path) 

200 adapters_info["adapter_modules"][ 

201 f"{adapter_name}_{module_name}" 

202 ] = module 

203 debug(f"Loaded adapter module: {module_path}") 

204 except ModuleNotFoundError: 

205 debug(f"Module {module_path} not found, skipping") 

206 continue 

207 except Exception as e: 

208 debug(f"Error loading {adapter_name}/{pattern}: {e}") 

209 debug( 

210 f"Gathered {len(adapters_info['adapters'])} adapters and {len(adapters_info['adapter_modules'])} modules", 

211 ) 

212 return adapters_info 

213 

214 

215async def _gather_acb_modules() -> dict[str, t.Any]: 

216 acb_modules = {} 

217 core_modules = [ 

218 "acb.depends", 

219 "acb.config", 

220 "acb.debug", 

221 "acb.adapters", 

222 ] 

223 optional_modules = [ 

224 "acb.storage", 

225 "acb.cache", 

226 "acb.queue", 

227 "acb.testing", 

228 ] 

229 for module_path in core_modules: 

230 try: 

231 module = import_module(module_path) 

232 module_name = module_path.split(".")[-1] 

233 acb_modules[module_name] = module 

234 debug(f"Loaded core ACB module: {module_path}") 

235 except Exception as e: 

236 debug(f"Error loading core ACB module {module_path}: {e}") 

237 for module_path in optional_modules: 

238 try: 

239 module = import_module(module_path) 

240 module_name = module_path.split(".")[-1] 

241 acb_modules[module_name] = module 

242 debug(f"Loaded optional ACB module: {module_path}") 

243 except ModuleNotFoundError: 

244 debug(f"Optional ACB module {module_path} not available") 

245 except Exception as e: 

246 debug(f"Error loading optional ACB module {module_path}: {e}") 

247 debug(f"Gathered {len(acb_modules)} ACB modules") 

248 return acb_modules 

249 

250 

251async def _gather_application_dependencies( 

252 dependency_patterns: list[str], 

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

254 dependencies: dict[str, t.Any] = {} 

255 try: 

256 # MIGRATED: Removed ACB import - using Oneiric equivalent 

257 

258 for dep_name in dependency_patterns: 

259 try: 

260 dependency = await depends.get(dep_name) 

261 if dependency is not None: 

262 dependencies[dep_name] = dependency 

263 debug(f"Gathered dependency: {dep_name}") 

264 except Exception as e: 

265 debug(f"Could not get dependency {dep_name}: {e}") 

266 except Exception as e: 

267 debug(f"Error accessing depends system: {e}") 

268 app_modules = [ 

269 "models", 

270 "views", 

271 "utils", 

272 "services", 

273 "handlers", 

274 ] 

275 for module_name in app_modules: 

276 try: 

277 module = import_module(module_name) 

278 dependencies[f"app_{module_name}"] = module 

279 debug(f"Loaded application module: {module_name}") 

280 except ModuleNotFoundError: 

281 continue 

282 except Exception as e: 

283 debug(f"Error loading application module {module_name}: {e}") 

284 debug(f"Gathered {len(dependencies)} application dependencies") 

285 return dependencies 

286 

287 

288async def _gather_initializers() -> list[t.Callable[..., t.Any]]: 

289 initializers: list[t.Callable[..., t.Any]] = [] 

290 await _gather_standard_initializers(initializers) 

291 await _gather_adapter_initializers(initializers) 

292 debug(f"Gathered {len(initializers)} initialization functions") 

293 return initializers 

294 

295 

296async def _gather_standard_initializers( 

297 initializers: list[t.Callable[..., t.Any]], 

298) -> None: 

299 initializer_paths = [ 

300 "initializers.init_app", 

301 "app.init_app", 

302 "main.init_app", 

303 "startup.init_app", 

304 "init.init_app", 

305 ] 

306 

307 for init_path in initializer_paths: 

308 try: 

309 module_path, func_name = init_path.rsplit(".", 1) 

310 module = import_module(module_path) 

311 init_func = getattr(module, func_name) 

312 if callable(init_func): 

313 initializers.append(init_func) 

314 debug(f"Found initializer: {init_path}") 

315 except (ModuleNotFoundError, AttributeError): 

316 continue 

317 except Exception as e: 

318 debug(f"Error loading initializer {init_path}: {e}") 

319 

320 

321async def _gather_adapter_initializers( 

322 initializers: list[t.Callable[..., t.Any]], 

323) -> None: 

324 for adapter in get_adapters(): 

325 try: 

326 adapter_init_path = f"acb.adapters.{adapter.name}.init" 

327 module = import_module(adapter_init_path) 

328 _collect_adapter_init_functions(module, adapter.name, initializers) 

329 except ModuleNotFoundError: 

330 continue 

331 except Exception as e: 

332 debug(f"Error loading adapter initializer for {adapter.name}: {e}") 

333 

334 

335def _collect_adapter_init_functions( 

336 module: t.Any, 

337 adapter_name: str, 

338 initializers: list[t.Callable[..., t.Any]], 

339) -> None: 

340 for func_name in ("init", "initialize", "setup", "configure"): 

341 if hasattr(module, func_name): 

342 init_func = getattr(module, func_name) 

343 if callable(init_func): 

344 initializers.append(init_func) 

345 debug(f"Found adapter initializer: {adapter_name}.{func_name}") 

346 

347 

348async def _gather_config() -> t.Any: 

349 try: 

350 # MIGRATED: Removed ACB import - using Oneiric equivalent 

351 

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

353 if config: 

354 debug("Gathered application config from depends") 

355 return config 

356 except Exception as e: 

357 debug(f"Error getting config from depends: {e}") 

358 try: 

359 # MIGRATED: Removed ACB import - using Oneiric equivalent 

360 

361 debug("Gathered application config directly") 

362 return Config() 

363 except Exception as e: 

364 debug(f"Error importing config directly: {e}") 

365 raise 

366 

367 

368async def initialize_application_components( 

369 gather_result: ApplicationGatherResult, 

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

371 initialization_results: dict[str, t.Any] = { 

372 "adapters_initialized": [], 

373 "dependencies_set": [], 

374 "initializers_run": [], 

375 "errors": [], 

376 } 

377 

378 for adapter_name in gather_result.adapters: 

379 try: 

380 initialization_results["adapters_initialized"].append(adapter_name) 

381 debug(f"Initialized adapter: {adapter_name}") 

382 

383 except Exception as e: 

384 initialization_results["errors"].append(e) 

385 debug(f"Error initializing adapter {adapter_name}: {e}") 

386 

387 try: 

388 # MIGRATED: Removed ACB import - using Oneiric equivalent 

389 

390 for dep_name, dependency in gather_result.dependencies.items(): 

391 try: 

392 depends.set(dep_name, dependency) 

393 initialization_results["dependencies_set"].append(dep_name) 

394 debug(f"Set dependency: {dep_name}") 

395 

396 except Exception as e: 

397 initialization_results["errors"].append(e) 

398 debug(f"Error setting dependency {dep_name}: {e}") 

399 

400 except Exception as e: 

401 initialization_results["errors"].append(e) 

402 debug(f"Error accessing depends system: {e}") 

403 

404 for i, initializer in enumerate(gather_result.initializers): 

405 try: 

406 import inspect 

407 

408 sig = inspect.signature(initializer) 

409 

410 if len(sig.parameters) > 0: 

411 result = initializer(gather_result.config) 

412 else: 

413 result = initializer() 

414 

415 if inspect.iscoroutine(result): 

416 await result 

417 

418 initialization_results["initializers_run"].append(f"initializer_{i}") 

419 debug(f"Ran initializer {i}") 

420 

421 except Exception as e: 

422 initialization_results["errors"].append(e) 

423 debug(f"Error running initializer {i}: {e}") 

424 

425 debug( 

426 f"Initialized {len(initialization_results['adapters_initialized'])} adapters, " 

427 f"{len(initialization_results['dependencies_set'])} dependencies, " 

428 f"{len(initialization_results['initializers_run'])} initializers", 

429 ) 

430 

431 return initialization_results 

432 

433 

434def get_application_info(gather_result: ApplicationGatherResult) -> dict[str, t.Any]: 

435 info: dict[str, t.Any] = { 

436 "total_components": gather_result.total_components, 

437 "adapters": { 

438 "count": len(gather_result.adapters), 

439 "names": list(gather_result.adapters.keys()), 

440 }, 

441 "acb_modules": { 

442 "count": len(gather_result.acb_modules), 

443 "modules": list(gather_result.acb_modules.keys()), 

444 }, 

445 "dependencies": { 

446 "count": len(gather_result.dependencies), 

447 "types": list(gather_result.dependencies.keys()), 

448 }, 

449 "initializers": { 

450 "count": len(gather_result.initializers), 

451 }, 

452 "config_available": gather_result.config is not None, 

453 "has_errors": gather_result.has_errors, 

454 "error_count": len(gather_result.errors), 

455 } 

456 if gather_result.config: 

457 info["config_info"] = { 

458 "type": type(gather_result.config).__name__, 

459 "deployed": getattr(gather_result.config, "deployed", False), 

460 "debug": getattr(gather_result.config, "debug", False), 

461 } 

462 

463 return info 

464 

465 

466async def create_application_manager( 

467 gather_result: ApplicationGatherResult, 

468) -> t.Any: 

469 try: 

470 from fastblocks.applications import ( 

471 ApplicationManager, # type: ignore[attr-defined] 

472 ) 

473 except ImportError: 

474 

475 class SimpleApplicationManager: 

476 def __init__(self, gather_result: ApplicationGatherResult) -> None: 

477 self.adapters = gather_result.adapters 

478 self.dependencies = gather_result.dependencies 

479 self.config = gather_result.config 

480 self.initializers = gather_result.initializers 

481 

482 return SimpleApplicationManager(gather_result) 

483 

484 manager = ApplicationManager() 

485 

486 manager._adapters = gather_result.adapters 

487 manager._dependencies = gather_result.dependencies 

488 manager._config = gather_result.config 

489 manager._initializers = gather_result.initializers 

490 

491 debug( 

492 f"Created application manager with {gather_result.total_components} components", 

493 ) 

494 

495 return manager 

496 

497 

498# Migration status indicator 

499# Note: Partial migration - ACB adapter system still in use 

500_using_oneiric = True # Oneiric resolver available 

501_requires_further_migration = True # ACB adapter system needs migration