Coverage for fastblocks / _workflows_integration.py: 22%

202 statements  

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

1"""Oneiric Workflows integration for FastBlocks. 

2 

3This module provides background job orchestration using Oneiric-compatible workflows, 

4with custom implementations for workflow execution and management. 

5 

6Author: lesleslie <les@wedgwoodwebworks.com> 

7Created: 2025-10-01 

8 

9Key Features: 

10- Cache warming workflows (template and static file caching) 

11- Template cleanup workflows (remove stale templates, optimize storage) 

12- Performance optimization workflows (database query optimization, index maintenance) 

13- Scheduled background tasks 

14- Oneiric-compatible dependency injection 

15 

16Usage: 

17 # Execute cache warming workflow 

18 from fastblocks._workflows_integration import execute_cache_warming 

19 result = await execute_cache_warming() 

20 

21 # Execute template cleanup workflow 

22 from fastblocks._workflows_integration import execute_template_cleanup 

23 result = await execute_template_cleanup() 

24 

25 # Execute performance optimization workflow 

26 from fastblocks._workflows_integration import execute_performance_optimization 

27 result = await execute_performance_optimization() 

28""" 

29 

30import typing as t 

31from contextlib import suppress 

32from datetime import datetime 

33 

34# Oneiric imports for dependency injection 

35from oneiric.core.resolution import Resolver 

36 

37# Custom Oneiric-compatible workflow system 

38depends = Resolver() 

39 

40 

41# Workflow system availability 

42oneiric_workflows_available = True 

43 

44 

45# Custom Oneiric-compatible Workflow System 

46class WorkflowState: 

47 """Workflow execution states.""" 

48 

49 PENDING = "pending" 

50 RUNNING = "running" 

51 COMPLETED = "completed" 

52 FAILED = "failed" 

53 

54 

55class WorkflowStep: 

56 """Workflow step definition.""" 

57 

58 def __init__( 

59 self, 

60 step_id: str, 

61 name: str, 

62 action: str, 

63 params: dict[str, t.Any], 

64 retry_on_failure: bool = False, 

65 max_retries: int = 0, 

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

67 ): 

68 self.step_id = step_id 

69 self.name = name 

70 self.action = action 

71 self.params = params 

72 self.retry_on_failure = retry_on_failure 

73 self.max_retries = max_retries 

74 self.depends_on = depends_on or [] 

75 

76 

77class WorkflowDefinition: 

78 """Workflow definition.""" 

79 

80 def __init__( 

81 self, 

82 workflow_id: str, 

83 name: str, 

84 description: str, 

85 steps: list[WorkflowStep], 

86 max_execution_time: int, 

87 ): 

88 self.workflow_id = workflow_id 

89 self.name = name 

90 self.description = description 

91 self.steps = steps 

92 self.max_execution_time = max_execution_time 

93 

94 

95class WorkflowResult: 

96 """Workflow execution result.""" 

97 

98 def __init__(self, state: str, step_results: dict[str, t.Any]): 

99 self.state = state 

100 self.step_results = step_results 

101 

102 

103class BasicWorkflowEngine: 

104 """Simple workflow engine for Oneiric-compatible workflow execution.""" 

105 

106 def __init__( 

107 self, 

108 max_concurrent_steps: int = 3, 

109 enable_retry: bool = True, 

110 max_retries: int = 2, 

111 ): 

112 self.max_concurrent_steps = max_concurrent_steps 

113 self.enable_retry = enable_retry 

114 self.max_retries = max_retries 

115 

116 async def execute( 

117 self, 

118 workflow: WorkflowDefinition, 

119 context: dict[str, t.Any], 

120 action_handlers: dict[str, t.Callable], 

121 ) -> WorkflowResult: 

122 """Execute a workflow.""" 

123 step_results = {} 

124 

125 try: 

126 # Execute steps sequentially (simplified for Oneiric) 

127 for step in workflow.steps: 

128 try: 

129 handler = action_handlers.get(step.action) 

130 if handler: 

131 result = await handler(context, step.params) 

132 step_results[step.step_id] = { 

133 "state": "completed", 

134 "result": result, 

135 "error": None, 

136 } 

137 else: 

138 step_results[step.step_id] = { 

139 "state": "failed", 

140 "result": None, 

141 "error": f"Handler not found for action: {step.action}", 

142 } 

143 except Exception as e: 

144 step_results[step.step_id] = { 

145 "state": "failed", 

146 "result": None, 

147 "error": str(e), 

148 } 

149 

150 # Determine overall state 

151 failed_steps = [s for s in step_results.values() if s["state"] == "failed"] 

152 state = WorkflowState.FAILED if failed_steps else WorkflowState.COMPLETED 

153 

154 return WorkflowResult(state, step_results) 

155 

156 except Exception as e: 

157 return WorkflowResult( 

158 WorkflowState.FAILED, 

159 { 

160 "error": str(e), 

161 "state": WorkflowState.FAILED, 

162 }, 

163 ) 

164 

165 

166class FastBlocksWorkflowService: 

167 """FastBlocks workflow service with Oneiric integration.""" 

168 

169 _instance: t.ClassVar["FastBlocksWorkflowService | None"] = None 

170 

171 def __new__(cls) -> "FastBlocksWorkflowService": 

172 """Singleton pattern - ensure only one instance exists.""" 

173 if cls._instance is None: 

174 cls._instance = super().__new__(cls) 

175 return cls._instance 

176 

177 def __init__(self) -> None: 

178 """Initialize workflow service with Oneiric integration.""" 

179 if not hasattr(self, "_initialized"): 

180 self._engine = BasicWorkflowEngine( 

181 max_concurrent_steps=3, # Conservative concurrency 

182 enable_retry=True, 

183 max_retries=2, 

184 ) 

185 self._initialized = True 

186 

187 @property 

188 def available(self) -> bool: 

189 """Check if workflow service is available.""" 

190 return True # Always available with Oneiric 

191 

192 

193# Singleton instance 

194_workflow_service: FastBlocksWorkflowService | None = None 

195 

196 

197def get_workflow_service() -> FastBlocksWorkflowService: 

198 """Get the singleton FastBlocksWorkflowService instance.""" 

199 global _workflow_service 

200 if _workflow_service is None: 

201 _workflow_service = FastBlocksWorkflowService() 

202 return _workflow_service 

203 

204 

205async def execute_cache_warming( 

206 warm_templates: bool = True, 

207 warm_static: bool = True, 

208 warm_routes: bool = True, 

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

210 """Execute cache warming workflow. 

211 

212 Pre-loads frequently accessed resources into cache to improve performance. 

213 

214 Args: 

215 warm_templates: Pre-cache commonly used templates 

216 warm_static: Pre-cache static file metadata 

217 warm_routes: Pre-cache route definitions 

218 

219 Returns: 

220 Dictionary with workflow results 

221 """ 

222 service = get_workflow_service() 

223 

224 if not service.available: 

225 # Graceful degradation - manual cache warming 

226 return await _manual_cache_warming(warm_templates, warm_static, warm_routes) 

227 

228 # Define workflow steps 

229 steps = [] 

230 

231 if warm_templates: 

232 steps.append( 

233 WorkflowStep( # type: ignore[operator] 

234 step_id="warm_templates", 

235 name="Warm Template Cache", 

236 action="warm_template_cache", 

237 params={}, 

238 retry_on_failure=True, 

239 max_retries=2, 

240 ) 

241 ) 

242 

243 if warm_static: 

244 steps.append( 

245 WorkflowStep( # type: ignore[operator] 

246 step_id="warm_static", 

247 name="Warm Static File Cache", 

248 action="warm_static_cache", 

249 params={}, 

250 retry_on_failure=True, 

251 max_retries=2, 

252 ) 

253 ) 

254 

255 if warm_routes: 

256 steps.append( 

257 WorkflowStep( # type: ignore[operator] 

258 step_id="warm_routes", 

259 name="Warm Route Cache", 

260 action="warm_route_cache", 

261 params={}, 

262 retry_on_failure=True, 

263 max_retries=2, 

264 ) 

265 ) 

266 

267 # Create workflow definition 

268 workflow = WorkflowDefinition( # type: ignore[operator] 

269 workflow_id="cache-warming", 

270 name="Cache Warming Workflow", 

271 description="Pre-load frequently accessed resources into cache", 

272 steps=steps, 

273 max_execution_time=300, # 5 minutes max 

274 ) 

275 

276 # Execute workflow 

277 result = await service._engine.execute( 

278 workflow, 

279 context={ 

280 "warm_templates": warm_templates, 

281 "warm_static": warm_static, 

282 "warm_routes": warm_routes, 

283 }, 

284 action_handlers={ 

285 "warm_template_cache": _warm_template_cache, 

286 "warm_static_cache": _warm_static_cache, 

287 "warm_route_cache": _warm_route_cache, 

288 }, 

289 ) 

290 

291 return { 

292 "workflow_id": workflow.workflow_id, 

293 "state": result.state.value if hasattr(result.state, "value") else result.state, 

294 "completed_at": datetime.now().isoformat(), 

295 "steps_completed": len( 

296 [s for s in result.step_results.values() if s.state == "completed"] 

297 ), 

298 "steps_failed": len( 

299 [s for s in result.step_results.values() if s.state == "failed"] 

300 ), 

301 "errors": [s.error for s in result.step_results.values() if s.error], 

302 } 

303 

304 

305async def execute_template_cleanup( 

306 remove_stale: bool = True, 

307 optimize_storage: bool = True, 

308 cleanup_cache: bool = True, 

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

310 """Execute template cleanup workflow. 

311 

312 Removes stale templates, optimizes storage, and cleans up cache. 

313 

314 Args: 

315 remove_stale: Remove templates not accessed in 30+ days 

316 optimize_storage: Compress and optimize template storage 

317 cleanup_cache: Clear unused template cache entries 

318 

319 Returns: 

320 Dictionary with workflow results 

321 """ 

322 service = get_workflow_service() 

323 

324 if not service.available: 

325 # Graceful degradation - manual cleanup 

326 return await _manual_template_cleanup( 

327 remove_stale, optimize_storage, cleanup_cache 

328 ) 

329 

330 # Define workflow steps with dependencies 

331 steps = [] 

332 

333 if cleanup_cache: 

334 steps.append( 

335 WorkflowStep( # type: ignore[operator] 

336 step_id="cleanup_cache", 

337 name="Cleanup Template Cache", 

338 action="cleanup_template_cache", 

339 params={}, 

340 retry_on_failure=False, 

341 ) 

342 ) 

343 

344 if remove_stale: 

345 steps.append( 

346 WorkflowStep( # type: ignore[operator] 

347 step_id="remove_stale", 

348 name="Remove Stale Templates", 

349 action="remove_stale_templates", 

350 params={"days_threshold": 30}, 

351 depends_on=["cleanup_cache"] if cleanup_cache else [], 

352 retry_on_failure=False, 

353 ) 

354 ) 

355 

356 if optimize_storage: 

357 steps.append( 

358 WorkflowStep( # type: ignore[operator] 

359 step_id="optimize_storage", 

360 name="Optimize Template Storage", 

361 action="optimize_template_storage", 

362 params={}, 

363 depends_on=["remove_stale"] if remove_stale else [], 

364 retry_on_failure=True, 

365 max_retries=2, 

366 ) 

367 ) 

368 

369 # Create workflow definition 

370 workflow = WorkflowDefinition( # type: ignore[operator] 

371 workflow_id="template-cleanup", 

372 name="Template Cleanup Workflow", 

373 description="Remove stale templates and optimize storage", 

374 steps=steps, 

375 max_execution_time=600, # 10 minutes max 

376 ) 

377 

378 # Execute workflow 

379 result = await service._engine.execute( 

380 workflow, 

381 context={ 

382 "remove_stale": remove_stale, 

383 "optimize_storage": optimize_storage, 

384 "cleanup_cache": cleanup_cache, 

385 }, 

386 action_handlers={ 

387 "cleanup_template_cache": _cleanup_template_cache, 

388 "remove_stale_templates": _remove_stale_templates, 

389 "optimize_template_storage": _optimize_template_storage, 

390 }, 

391 ) 

392 

393 return { 

394 "workflow_id": workflow.workflow_id, 

395 "state": result.state.value if hasattr(result.state, "value") else result.state, 

396 "completed_at": datetime.now().isoformat(), 

397 "steps_completed": len( 

398 [s for s in result.step_results.values() if s.state == "completed"] 

399 ), 

400 "steps_failed": len( 

401 [s for s in result.step_results.values() if s.state == "failed"] 

402 ), 

403 "errors": [s.error for s in result.step_results.values() if s.error], 

404 } 

405 

406 

407async def execute_performance_optimization( 

408 optimize_queries: bool = True, 

409 rebuild_indexes: bool = True, 

410 cleanup_sessions: bool = True, 

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

412 """Execute performance optimization workflow. 

413 

414 Optimizes database queries, rebuilds indexes, and cleans up sessions. 

415 

416 Args: 

417 optimize_queries: Analyze and optimize slow queries 

418 rebuild_indexes: Rebuild database indexes for optimal performance 

419 cleanup_sessions: Clean up expired sessions 

420 

421 Returns: 

422 Dictionary with workflow results 

423 """ 

424 service = get_workflow_service() 

425 

426 if not service.available: 

427 # Graceful degradation - manual optimization 

428 return await _manual_performance_optimization( 

429 optimize_queries, rebuild_indexes, cleanup_sessions 

430 ) 

431 

432 # Define workflow steps 

433 steps = [] 

434 

435 if cleanup_sessions: 

436 steps.append( 

437 WorkflowStep( # type: ignore[operator] 

438 step_id="cleanup_sessions", 

439 name="Cleanup Expired Sessions", 

440 action="cleanup_expired_sessions", 

441 params={"expiry_hours": 24}, 

442 retry_on_failure=False, 

443 ) 

444 ) 

445 

446 if optimize_queries: 

447 steps.append( 

448 WorkflowStep( # type: ignore[operator] 

449 step_id="optimize_queries", 

450 name="Optimize Database Queries", 

451 action="optimize_database_queries", 

452 params={}, 

453 retry_on_failure=True, 

454 max_retries=2, 

455 ) 

456 ) 

457 

458 if rebuild_indexes: 

459 steps.append( 

460 WorkflowStep( # type: ignore[operator] 

461 step_id="rebuild_indexes", 

462 name="Rebuild Database Indexes", 

463 action="rebuild_database_indexes", 

464 params={}, 

465 depends_on=["optimize_queries"] if optimize_queries else [], 

466 retry_on_failure=True, 

467 max_retries=1, 

468 ) 

469 ) 

470 

471 # Create workflow definition 

472 workflow = WorkflowDefinition( # type: ignore[operator] 

473 workflow_id="performance-optimization", 

474 name="Performance Optimization Workflow", 

475 description="Optimize database and application performance", 

476 steps=steps, 

477 max_execution_time=900, # 15 minutes max 

478 ) 

479 

480 # Execute workflow 

481 result = await service._engine.execute( 

482 workflow, 

483 context={ 

484 "optimize_queries": optimize_queries, 

485 "rebuild_indexes": rebuild_indexes, 

486 "cleanup_sessions": cleanup_sessions, 

487 }, 

488 action_handlers={ 

489 "cleanup_expired_sessions": _cleanup_expired_sessions, 

490 "optimize_database_queries": _optimize_database_queries, 

491 "rebuild_database_indexes": _rebuild_database_indexes, 

492 }, 

493 ) 

494 

495 return { 

496 "workflow_id": workflow.workflow_id, 

497 "state": result.state.value if hasattr(result.state, "value") else result.state, 

498 "completed_at": datetime.now().isoformat(), 

499 "steps_completed": len( 

500 [s for s in result.step_results.values() if s.state == "completed"] 

501 ), 

502 "steps_failed": len( 

503 [s for s in result.step_results.values() if s.state == "failed"] 

504 ), 

505 "errors": [s.error for s in result.step_results.values() if s.error], 

506 } 

507 

508 

509# Action handler implementations 

510 

511 

512async def _warm_template_cache( 

513 context: dict[str, t.Any], params: dict[str, t.Any] 

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

515 """Warm template cache by pre-loading commonly used templates.""" 

516 with suppress(Exception): 

517 from .actions.gather import gather 

518 

519 # Gather all templates 

520 templates_result = await gather.templates() 

521 

522 if templates_result and hasattr(templates_result, "templates"): 

523 cached_count = 0 

524 # Pre-cache template metadata (not full rendering) 

525 cache = await depends.resolve("fastblocks", "cache") 

526 if cache: 

527 for template_name in list(templates_result.templates.keys())[ 

528 :50 

529 ]: # Limit to top 50 

530 cache_key = f"template:metadata:{template_name}" 

531 await cache.set( 

532 cache_key, 

533 { 

534 "name": template_name, 

535 "warmed_at": datetime.now().isoformat(), 

536 }, 

537 ttl=3600, 

538 ) 

539 cached_count += 1 

540 

541 return {"templates_warmed": cached_count, "status": "completed"} 

542 

543 return {"templates_warmed": 0, "status": "skipped"} 

544 

545 

546async def _warm_static_cache( 

547 context: dict[str, t.Any], params: dict[str, t.Any] 

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

549 """Warm static file cache by pre-loading metadata.""" 

550 # Static file warming would depend on static file adapter 

551 return {"static_files_warmed": 0, "status": "skipped"} 

552 

553 

554async def _warm_route_cache( 

555 context: dict[str, t.Any], params: dict[str, t.Any] 

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

557 """Warm route cache by pre-loading route definitions.""" 

558 with suppress(Exception): 

559 from .actions.gather import gather 

560 

561 # Gather all routes 

562 routes_result = await gather.routes() 

563 

564 if routes_result and hasattr(routes_result, "routes"): 

565 cached_count = len(routes_result.routes) 

566 return {"routes_warmed": cached_count, "status": "completed"} 

567 

568 return {"routes_warmed": 0, "status": "skipped"} 

569 

570 

571async def _cleanup_template_cache( 

572 context: dict[str, t.Any], params: dict[str, t.Any] 

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

574 """Clean up unused template cache entries.""" 

575 with suppress(Exception): 

576 cache = await depends.resolve("fastblocks", "cache") 

577 if cache and hasattr(cache, "clear_pattern"): 

578 # Clear stale template cache entries 

579 await cache.clear_pattern("template:*") 

580 return {"cache_cleared": True, "status": "completed"} 

581 

582 return {"cache_cleared": False, "status": "skipped"} 

583 

584 

585async def _remove_stale_templates( 

586 context: dict[str, t.Any], params: dict[str, t.Any] 

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

588 """Remove templates not accessed in X days.""" 

589 days_threshold = params.get("days_threshold", 30) 

590 

591 # In production, would check template access logs 

592 # For now, just return placeholder 

593 return { 

594 "templates_removed": 0, 

595 "days_threshold": days_threshold, 

596 "status": "completed", 

597 } 

598 

599 

600async def _optimize_template_storage( 

601 context: dict[str, t.Any], params: dict[str, t.Any] 

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

603 """Optimize template storage (compress, deduplicate).""" 

604 # In production, would compress/optimize template files 

605 return {"storage_optimized": False, "status": "skipped"} 

606 

607 

608async def _cleanup_expired_sessions( 

609 context: dict[str, t.Any], params: dict[str, t.Any] 

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

611 """Clean up expired sessions.""" 

612 expiry_hours = params.get("expiry_hours", 24) 

613 

614 # In production, would clean up session storage 

615 return { 

616 "sessions_cleaned": 0, 

617 "expiry_hours": expiry_hours, 

618 "status": "completed", 

619 } 

620 

621 

622async def _optimize_database_queries( 

623 context: dict[str, t.Any], params: dict[str, t.Any] 

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

625 """Analyze and optimize slow database queries.""" 

626 # In production, would analyze query logs and optimize 

627 return {"queries_optimized": 0, "status": "skipped"} 

628 

629 

630async def _rebuild_database_indexes( 

631 context: dict[str, t.Any], params: dict[str, t.Any] 

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

633 """Rebuild database indexes for optimal performance.""" 

634 # In production, would rebuild database indexes 

635 return {"indexes_rebuilt": 0, "status": "skipped"} 

636 

637 

638# Manual fallback implementations (when ACB Workflows unavailable) 

639 

640 

641async def _manual_cache_warming( 

642 warm_templates: bool, warm_static: bool, warm_routes: bool 

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

644 """Manual cache warming without workflow orchestration.""" 

645 results = {} 

646 

647 if warm_templates: 

648 result = await _warm_template_cache({}, {}) 

649 results["templates"] = result 

650 

651 if warm_static: 

652 result = await _warm_static_cache({}, {}) 

653 results["static"] = result 

654 

655 if warm_routes: 

656 result = await _warm_route_cache({}, {}) 

657 results["routes"] = result 

658 

659 return { 

660 "workflow_id": "cache-warming", 

661 "state": "completed", 

662 "completed_at": datetime.now().isoformat(), 

663 "results": results, 

664 "mode": "manual", 

665 } 

666 

667 

668async def _manual_template_cleanup( 

669 remove_stale: bool, optimize_storage: bool, cleanup_cache: bool 

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

671 """Manual template cleanup without workflow orchestration.""" 

672 results = {} 

673 

674 if cleanup_cache: 

675 result = await _cleanup_template_cache({}, {}) 

676 results["cache_cleanup"] = result 

677 

678 if remove_stale: 

679 result = await _remove_stale_templates({}, {"days_threshold": 30}) 

680 results["stale_removal"] = result 

681 

682 if optimize_storage: 

683 result = await _optimize_template_storage({}, {}) 

684 results["storage_optimization"] = result 

685 

686 return { 

687 "workflow_id": "template-cleanup", 

688 "state": "completed", 

689 "completed_at": datetime.now().isoformat(), 

690 "results": results, 

691 "mode": "manual", 

692 } 

693 

694 

695async def _manual_performance_optimization( 

696 optimize_queries: bool, rebuild_indexes: bool, cleanup_sessions: bool 

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

698 """Manual performance optimization without workflow orchestration.""" 

699 results = {} 

700 

701 if cleanup_sessions: 

702 result = await _cleanup_expired_sessions({}, {"expiry_hours": 24}) 

703 results["session_cleanup"] = result 

704 

705 if optimize_queries: 

706 result = await _optimize_database_queries({}, {}) 

707 results["query_optimization"] = result 

708 

709 if rebuild_indexes: 

710 result = await _rebuild_database_indexes({}, {}) 

711 results["index_rebuild"] = result 

712 

713 return { 

714 "workflow_id": "performance-optimization", 

715 "state": "completed", 

716 "completed_at": datetime.now().isoformat(), 

717 "results": results, 

718 "mode": "manual", 

719 } 

720 

721 

722async def register_fastblocks_workflows() -> bool: 

723 """Register FastBlocks workflows with ACB. 

724 

725 Returns: 

726 True if registration successful, False otherwise 

727 """ 

728 if not acb_workflows_available: 

729 return False 

730 

731 try: 

732 # Initialize workflow service 

733 workflow_service = get_workflow_service() 

734 

735 # Register with depends 

736 depends.set("fastblocks_workflows", workflow_service) 

737 

738 return workflow_service.available 

739 

740 except Exception: 

741 return False 

742 

743 

744__all__ = [ 

745 "FastBlocksWorkflowService", 

746 "get_workflow_service", 

747 "execute_cache_warming", 

748 "execute_template_cleanup", 

749 "execute_performance_optimization", 

750 "register_fastblocks_workflows", 

751 "oneiric_workflows_available", 

752]