Coverage for fastblocks / _events_integration.py: 43%

248 statements  

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

1"""Oneiric Events system integration for FastBlocks. 

2 

3This module provides FastBlocks components with an event-driven architecture, 

4enabling reactive updates, cache invalidation, and admin action tracking. 

5 

6Author: lesleslie <les@wedgwoodwebworks.com> 

7Created: 2025-10-01 

8""" 

9 

10import operator 

11import typing as t 

12from contextlib import suppress 

13from dataclasses import dataclass 

14from uuid import UUID 

15 

16# Oneiric imports for dependency injection 

17from oneiric.core.resolution import Resolver 

18from fastblocks.adapters.oneiric_helper import register_candidate 

19 

20# Custom Oneiric-compatible events system 

21depends = Resolver() 

22 

23# Event system availability 

24oneiric_events_available = True 

25 

26 

27# Custom Oneiric-compatible Event System 

28class EventPriority: 

29 """Event priority levels.""" 

30 

31 LOW = 1 

32 NORMAL = 2 

33 HIGH = 3 

34 CRITICAL = 4 

35 

36 

37class EventHandlerResult: 

38 """Result of event handling.""" 

39 

40 def __init__( 

41 self, 

42 success: bool, 

43 message: str, 

44 error: str | None = None, 

45 data: dict[str, t.Any] | None = None, 

46 ): 

47 self.success = success 

48 self.message = message 

49 self.error = error 

50 self.data = data or {} 

51 

52 

53class EventSubscription: 

54 """Event subscription.""" 

55 

56 def __init__(self, event_type: str, handler: t.Any): 

57 self.event_type = event_type 

58 self.handler = handler 

59 

60 

61class Event: 

62 """Event object.""" 

63 

64 def __init__( 

65 self, 

66 event_type: str, 

67 source: str, 

68 payload: dict[str, t.Any], 

69 priority: EventPriority, 

70 ): 

71 self.event_type = event_type 

72 self.source = source 

73 self.payload = payload 

74 self.priority = priority 

75 

76 

77class EventPublisher: 

78 """Event publisher for Oneiric-compatible event system.""" 

79 

80 def __init__(self) -> None: 

81 self.subscriptions: dict[str, list[EventSubscription]] = {} 

82 

83 async def publish(self, event: Event) -> bool: 

84 """Publish an event to all subscribers.""" 

85 try: 

86 handlers = self.subscriptions.get(event.event_type, []) 

87 

88 for subscription in handlers: 

89 await subscription.handler.handle(event) 

90 

91 return True 

92 except Exception: 

93 return False 

94 

95 async def subscribe(self, subscription: EventSubscription) -> bool: 

96 """Subscribe to an event type.""" 

97 try: 

98 if subscription.event_type not in self.subscriptions: 

99 self.subscriptions[subscription.event_type] = [] 

100 

101 self.subscriptions[subscription.event_type].append(subscription) 

102 return True 

103 except Exception: 

104 return False 

105 

106 

107def create_event( 

108 event_type: str, source: str, payload: dict[str, t.Any], priority: EventPriority 

109) -> Event: 

110 """Create an event.""" 

111 return Event(event_type, source, payload, priority) 

112 

113 

114# FastBlocks Event Types 

115class FastBlocksEventType: 

116 """Event types emitted by FastBlocks components.""" 

117 

118 # Cache events 

119 CACHE_INVALIDATED = "fastblocks.cache.invalidated" 

120 CACHE_CLEARED = "fastblocks.cache.cleared" 

121 

122 # Template events 

123 TEMPLATE_RENDERED = "fastblocks.template.rendered" 

124 TEMPLATE_ERROR = "fastblocks.template.error" 

125 

126 # HTMX events (server-sent updates) 

127 HTMX_REFRESH = "fastblocks.htmx.refresh" 

128 HTMX_REDIRECT = "fastblocks.htmx.redirect" 

129 HTMX_TRIGGER = "fastblocks.htmx.trigger" 

130 

131 # Admin events 

132 ADMIN_ACTION = "fastblocks.admin.action" 

133 ADMIN_LOGIN = "fastblocks.admin.login" 

134 ADMIN_LOGOUT = "fastblocks.admin.logout" 

135 

136 # Route events 

137 ROUTE_REGISTERED = "fastblocks.route.registered" 

138 ROUTE_ACCESSED = "fastblocks.route.accessed" 

139 

140 

141@dataclass 

142class CacheInvalidationPayload: 

143 """Payload for cache invalidation events.""" 

144 

145 cache_key: str 

146 reason: str 

147 invalidated_by: str | None = None 

148 affected_templates: list[str] | None = None 

149 

150 

151@dataclass 

152class TemplateRenderPayload: 

153 """Payload for template render events.""" 

154 

155 template_name: str 

156 render_time_ms: float 

157 cache_hit: bool 

158 context_size: int 

159 fragment_count: int 

160 error: str | None = None 

161 

162 

163@dataclass 

164class HtmxUpdatePayload: 

165 """Payload for HTMX update events.""" 

166 

167 update_type: str # "refresh", "redirect", "trigger" 

168 target: str | None = None # CSS selector or URL 

169 swap_method: str | None = None # "innerHTML", "outerHTML", etc. 

170 trigger_name: str | None = None 

171 trigger_data: dict[str, t.Any] | None = None 

172 

173 

174@dataclass 

175class AdminActionPayload: 

176 """Payload for admin action events.""" 

177 

178 action_type: str # "create", "update", "delete", "login", "logout" 

179 user_id: str 

180 resource_type: str | None = None 

181 resource_id: str | None = None 

182 changes: dict[str, t.Any] | None = None 

183 ip_address: str | None = None 

184 

185 

186class CacheInvalidationHandler: 

187 """Handler for cache invalidation events.""" 

188 

189 def __init__(self, cache: t.Any | None = None) -> None: 

190 self.cache = cache 

191 

192 async def handle(self, event: Event) -> t.Any: 

193 """Handle cache invalidation event.""" 

194 if not acb_events_available: 

195 return None 

196 

197 try: 

198 payload = CacheInvalidationPayload(**event.payload) 

199 

200 # Invalidate the cache key 

201 if self.cache: 

202 await self.cache.delete(payload.cache_key) 

203 

204 # Also invalidate related template caches if specified 

205 if payload.affected_templates: 

206 for template_name in payload.affected_templates: 

207 template_key = f"template:{template_name}" 

208 await self.cache.delete(template_key) 

209 

210 return EventHandlerResult( 

211 success=True, 

212 message=f"Invalidated cache key: {payload.cache_key}", 

213 ) 

214 

215 except Exception as e: 

216 return EventHandlerResult( 

217 success=False, 

218 error=str(e), 

219 message=f"Failed to invalidate cache: {e}", 

220 ) 

221 

222 

223class TemplateRenderHandler: 

224 """Handler for template render events - collects performance metrics.""" 

225 

226 def __init__(self) -> None: 

227 self.metrics: dict[str, list[TemplateRenderPayload]] = {} 

228 

229 async def handle(self, event: Event) -> t.Any: 

230 """Handle template render event.""" 

231 if not acb_events_available: 

232 return None 

233 

234 try: 

235 payload = TemplateRenderPayload(**event.payload) 

236 

237 # Store metrics for performance analysis 

238 if payload.template_name not in self.metrics: 

239 self.metrics[payload.template_name] = [] 

240 

241 self.metrics[payload.template_name].append(payload) 

242 

243 # Keep only last 100 renders per template 

244 if len(self.metrics[payload.template_name]) > 100: 

245 self.metrics[payload.template_name] = self.metrics[ 

246 payload.template_name 

247 ][-100:] 

248 

249 return EventHandlerResult( 

250 success=True, 

251 message=f"Recorded render metrics for {payload.template_name}", 

252 ) 

253 

254 except Exception as e: 

255 return EventHandlerResult( 

256 success=False, 

257 error=str(e), 

258 message=f"Failed to record metrics: {e}", 

259 ) 

260 

261 def get_template_stats(self, template_name: str) -> dict[str, t.Any]: 

262 """Get performance statistics for a template.""" 

263 if template_name not in self.metrics: 

264 return {} 

265 

266 renders = self.metrics[template_name] 

267 render_times = [r.render_time_ms for r in renders] 

268 cache_hits = sum(1 for r in renders if r.cache_hit) 

269 

270 return { 

271 "total_renders": len(renders), 

272 "avg_render_time_ms": sum(render_times) / len(render_times), 

273 "min_render_time_ms": min(render_times), 

274 "max_render_time_ms": max(render_times), 

275 "cache_hit_ratio": cache_hits / len(renders), 

276 "recent_errors": [r.error for r in renders[-10:] if r.error], 

277 } 

278 

279 

280class HtmxUpdateHandler: 

281 """Handler for HTMX update events - broadcasts to connected clients.""" 

282 

283 def __init__(self) -> None: 

284 self.active_connections: set[t.Any] = set() # WebSocket connections 

285 

286 async def handle(self, event: Event) -> t.Any: 

287 """Handle HTMX update event.""" 

288 if not acb_events_available: 

289 return None 

290 

291 try: 

292 payload = HtmxUpdatePayload(**event.payload) 

293 

294 # Build HTMX headers for server-sent event 

295 headers = {} 

296 

297 if payload.update_type == "refresh" and payload.target: 

298 headers["HX-Trigger"] = "refresh" 

299 headers["HX-Refresh"] = "true" 

300 

301 elif payload.update_type == "redirect" and payload.target: 

302 headers["HX-Redirect"] = payload.target 

303 

304 elif payload.update_type == "trigger" and payload.trigger_name: 

305 headers["HX-Trigger"] = payload.trigger_name 

306 if payload.trigger_data: 

307 import json 

308 

309 headers["HX-Trigger-Data"] = json.dumps(payload.trigger_data) 

310 

311 # Broadcast to all connected clients 

312 # Note: Actual WebSocket broadcast would happen in route handlers 

313 # This handler just prepares the event data 

314 

315 return EventHandlerResult( 

316 success=True, 

317 message=f"Prepared HTMX {payload.update_type} event", 

318 data={"headers": headers}, 

319 ) 

320 

321 except Exception as e: 

322 return EventHandlerResult( 

323 success=False, 

324 error=str(e), 

325 message=f"Failed to prepare HTMX event: {e}", 

326 ) 

327 

328 

329class AdminActionHandler: 

330 """Handler for admin action events - audit logging.""" 

331 

332 def __init__(self) -> None: 

333 self.audit_log: list[tuple[float, AdminActionPayload]] = [] 

334 

335 async def handle(self, event: Event) -> t.Any: 

336 """Handle admin action event.""" 

337 if not acb_events_available: 

338 return None 

339 

340 try: 

341 import time 

342 

343 payload = AdminActionPayload(**event.payload) 

344 

345 # Store in audit log 

346 self.audit_log.append((time.time(), payload)) 

347 

348 # Keep only last 1000 actions 

349 if len(self.audit_log) > 1000: 

350 self.audit_log = self.audit_log[-1000:] 

351 

352 # In production, this would also: 

353 # - Write to database audit table 

354 # - Send to monitoring/alerting system 

355 # - Trigger security checks for sensitive actions 

356 

357 return EventHandlerResult( 

358 success=True, 

359 message=f"Logged admin action: {payload.action_type}", 

360 ) 

361 

362 except Exception as e: 

363 return EventHandlerResult( 

364 success=False, 

365 error=str(e), 

366 message=f"Failed to log admin action: {e}", 

367 ) 

368 

369 def get_recent_actions(self, limit: int = 50) -> list[dict[str, t.Any]]: 

370 """Get recent admin actions.""" 

371 import time 

372 

373 now = time.time() 

374 recent = sorted(self.audit_log, key=operator.itemgetter(0), reverse=True)[ 

375 :limit 

376 ] 

377 

378 return [ 

379 { 

380 "timestamp": timestamp, 

381 "age_seconds": now - timestamp, 

382 "action_type": payload.action_type, 

383 "user_id": payload.user_id, 

384 "resource_type": payload.resource_type, 

385 "resource_id": payload.resource_id, 

386 } 

387 for timestamp, payload in recent 

388 ] 

389 

390 

391class FastBlocksEventPublisher: 

392 """Simplified event publisher for FastBlocks components.""" 

393 

394 _instance: t.ClassVar["FastBlocksEventPublisher | None"] = None 

395 _publisher: EventPublisher | None = None 

396 

397 def __new__(cls) -> "FastBlocksEventPublisher": 

398 """Singleton pattern for event publisher.""" 

399 if cls._instance is None: 

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

401 return cls._instance 

402 

403 def __init__(self, config: t.Any | None = None) -> None: 

404 self.config = config 

405 self.source = "fastblocks" 

406 

407 # Initialize publisher lazily 

408 if self._publisher is None: 

409 with suppress(Exception): 

410 self._publisher = EventPublisher() 

411 

412 async def publish_cache_invalidation( 

413 self, 

414 cache_key: str, 

415 reason: str, 

416 invalidated_by: str | None = None, 

417 affected_templates: list[str] | None = None, 

418 ) -> bool: 

419 """Publish cache invalidation event.""" 

420 if not acb_events_available or self._publisher is None: 

421 return False 

422 

423 try: 

424 event = create_event( 

425 event_type=FastBlocksEventType.CACHE_INVALIDATED, 

426 source=self.source, 

427 payload={ 

428 "cache_key": cache_key, 

429 "reason": reason, 

430 "invalidated_by": invalidated_by, 

431 "affected_templates": affected_templates, 

432 }, 

433 priority=EventPriority.HIGH, 

434 ) 

435 

436 await self._publisher.publish(event) 

437 return True 

438 

439 except Exception: 

440 return False 

441 

442 async def publish_template_render( 

443 self, 

444 template_name: str, 

445 render_time_ms: float, 

446 cache_hit: bool, 

447 context_size: int, 

448 fragment_count: int, 

449 error: str | None = None, 

450 ) -> bool: 

451 """Publish template render event.""" 

452 if not acb_events_available or self._publisher is None: 

453 return False 

454 

455 try: 

456 event_type = ( 

457 FastBlocksEventType.TEMPLATE_ERROR 

458 if error 

459 else FastBlocksEventType.TEMPLATE_RENDERED 

460 ) 

461 

462 event = create_event( 

463 event_type=event_type, 

464 source=self.source, 

465 payload={ 

466 "template_name": template_name, 

467 "render_time_ms": render_time_ms, 

468 "cache_hit": cache_hit, 

469 "context_size": context_size, 

470 "fragment_count": fragment_count, 

471 "error": error, 

472 }, 

473 priority=EventPriority.NORMAL, 

474 ) 

475 

476 await self._publisher.publish(event) 

477 return True 

478 

479 except Exception: 

480 return False 

481 

482 async def publish_htmx_update( 

483 self, 

484 update_type: str, 

485 target: str | None = None, 

486 swap_method: str | None = None, 

487 trigger_name: str | None = None, 

488 trigger_data: dict[str, t.Any] | None = None, 

489 ) -> bool: 

490 """Publish HTMX update event.""" 

491 if not acb_events_available or self._publisher is None: 

492 return False 

493 

494 try: 

495 event = create_event( 

496 event_type=FastBlocksEventType.HTMX_REFRESH, 

497 source=self.source, 

498 payload={ 

499 "update_type": update_type, 

500 "target": target, 

501 "swap_method": swap_method, 

502 "trigger_name": trigger_name, 

503 "trigger_data": trigger_data, 

504 }, 

505 priority=EventPriority.HIGH, 

506 ) 

507 

508 await self._publisher.publish(event) 

509 return True 

510 

511 except Exception: 

512 return False 

513 

514 async def publish_admin_action( 

515 self, 

516 action_type: str, 

517 user_id: str, 

518 resource_type: str | None = None, 

519 resource_id: str | None = None, 

520 changes: dict[str, t.Any] | None = None, 

521 ip_address: str | None = None, 

522 ) -> bool: 

523 """Publish admin action event.""" 

524 if not acb_events_available or self._publisher is None: 

525 return False 

526 

527 try: 

528 event = create_event( 

529 event_type=FastBlocksEventType.ADMIN_ACTION, 

530 source=self.source, 

531 payload={ 

532 "action_type": action_type, 

533 "user_id": user_id, 

534 "resource_type": resource_type, 

535 "resource_id": resource_id, 

536 "changes": changes, 

537 "ip_address": ip_address, 

538 }, 

539 priority=EventPriority.CRITICAL, 

540 ) 

541 

542 await self._publisher.publish(event) 

543 return True 

544 

545 except Exception: 

546 return False 

547 

548 

549async def register_fastblocks_event_handlers() -> bool: 

550 """Register all FastBlocks event handlers with Oneiric event system. 

551 

552 Returns: 

553 True if registration successful, False if event system unavailable 

554 """ 

555 try: 

556 publisher = FastBlocksEventPublisher() 

557 

558 if publisher._publisher is None: 

559 return False 

560 

561 # Register event handlers 

562 cache_handler = CacheInvalidationHandler() 

563 template_handler = TemplateRenderHandler() 

564 htmx_handler = HtmxUpdateHandler() 

565 admin_handler = AdminActionHandler() 

566 

567 # Subscribe handlers to their event types 

568 await publisher._publisher.subscribe( 

569 EventSubscription( 

570 event_type=FastBlocksEventType.CACHE_INVALIDATED, 

571 handler=cache_handler, 

572 ) 

573 ) 

574 

575 await publisher._publisher.subscribe( 

576 EventSubscription( 

577 event_type=FastBlocksEventType.TEMPLATE_RENDERED, 

578 handler=template_handler, 

579 ) 

580 ) 

581 

582 await publisher._publisher.subscribe( 

583 EventSubscription( 

584 event_type=FastBlocksEventType.TEMPLATE_ERROR, 

585 handler=template_handler, 

586 ) 

587 ) 

588 

589 await publisher._publisher.subscribe( 

590 EventSubscription( 

591 event_type=FastBlocksEventType.HTMX_REFRESH, 

592 handler=htmx_handler, 

593 ) 

594 ) 

595 

596 await publisher._publisher.subscribe( 

597 EventSubscription( 

598 event_type=FastBlocksEventType.ADMIN_ACTION, 

599 handler=admin_handler, 

600 ) 

601 ) 

602 

603 # Store handlers in depends for retrieval 

604 register_candidate( 

605 depends, 

606 domain="fastblocks", 

607 key="template_handler", 

608 factory=lambda: template_handler, 

609 metadata={ 

610 "class": "TemplateEventHandler", 

611 "module": "fastblocks._events_integration", 

612 }, 

613 ) 

614 register_candidate( 

615 depends, 

616 domain="fastblocks", 

617 key="admin_handler", 

618 factory=lambda: admin_handler, 

619 metadata={ 

620 "class": "AdminEventHandler", 

621 "module": "fastblocks._events_integration", 

622 }, 

623 ) 

624 

625 return True 

626 

627 except Exception: 

628 # Graceful degradation if registration fails 

629 return False 

630 

631 

632def get_event_publisher() -> FastBlocksEventPublisher | None: 

633 """Get the FastBlocks event publisher instance. 

634 

635 Returns: 

636 Event publisher instance 

637 """ 

638 return FastBlocksEventPublisher() 

639 

640 

641# Module metadata for Oneiric compatibility 

642MODULE_ID = UUID("01937d88-0000-7000-8000-000000000002") 

643MODULE_STATUS = "STABLE" # Oneiric-compatible status