Coverage for fastblocks / adapters / templates / _events_wrapper.py: 71%

90 statements  

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

1"""Event tracking wrapper for template rendering operations. 

2 

3This module provides decorators and wrappers to integrate ACB Events 

4with template rendering, tracking performance metrics automatically. 

5 

6Author: lesleslie <les@wedgwoodwebworks.com> 

7Created: 2025-10-01 

8""" 

9 

10import functools 

11import sys 

12import time 

13import typing as t 

14from contextlib import suppress 

15 

16# Oneiric imports 

17from oneiric.core.resolution import Resolver 

18 

19# Oneiric resolver for dependency injection 

20depends = Resolver() 

21 

22 

23def track_template_render( 

24 func: t.Callable[..., t.Awaitable[t.Any]], 

25) -> t.Callable[..., t.Awaitable[t.Any]]: 

26 """Decorator to track template rendering performance. 

27 

28 Publishes template render events with performance metrics. 

29 Gracefully degrades if events integration unavailable. 

30 

31 Usage: 

32 @track_template_render 

33 async def render_template(self, template_name, context): 

34 ... 

35 """ 

36 

37 @functools.wraps(func) 

38 async def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any: 

39 # Extract arguments 

40 template_name = _extract_template_name(args, kwargs) 

41 context = _extract_context(args, kwargs) 

42 

43 # Track render time 

44 start_time = time.perf_counter() 

45 

46 try: 

47 # Call the original function 

48 result = await func(*args, **kwargs) 

49 

50 # Calculate and publish success metrics 

51 render_time_ms = (time.perf_counter() - start_time) * 1000 

52 await _publish_render_event( 

53 template_name=template_name, 

54 render_time_ms=render_time_ms, 

55 context=context, 

56 error=None, 

57 ) 

58 

59 return result 

60 

61 except Exception as e: 

62 # Calculate and publish error metrics 

63 render_time_ms = (time.perf_counter() - start_time) * 1000 

64 await _publish_render_event( 

65 template_name=template_name, 

66 render_time_ms=render_time_ms, 

67 context=context, 

68 error=str(e), 

69 ) 

70 raise 

71 

72 return wrapper 

73 

74 

75def _extract_template_name( 

76 args: tuple[t.Any, ...], kwargs: dict[str, t.Any] 

77) -> str | None: 

78 """Extract template name from function arguments.""" 

79 # Check kwargs first (more explicit) 

80 for key in ("template", "name"): 

81 if key in kwargs: 

82 template_name: str | None = kwargs[key] 

83 return template_name 

84 

85 # Check positional args 

86 if len(args) > 2 and isinstance(args[2], str): 

87 return args[2] 

88 

89 return None 

90 

91 

92def _extract_context( 

93 args: tuple[t.Any, ...], kwargs: dict[str, t.Any] 

94) -> dict[str, t.Any] | None: 

95 """Extract context dictionary from function arguments.""" 

96 # Check kwargs first 

97 if "context" in kwargs and isinstance(kwargs["context"], dict): 

98 return kwargs["context"] 

99 

100 # Check positional args 

101 if len(args) > 3 and isinstance(args[3], dict): 

102 return args[3] 

103 

104 return None 

105 

106 

107async def _publish_render_event( 

108 template_name: str | None, 

109 render_time_ms: float, 

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

111 error: str | None, 

112) -> None: 

113 """Publish template render event with metrics.""" 

114 if not template_name: 

115 return 

116 

117 context_size = sys.getsizeof(context) if context else 0 

118 cache_hit = render_time_ms < 5.0 if not error else False 

119 

120 with suppress(Exception): 

121 from ..._events_integration import get_event_publisher 

122 

123 publisher = get_event_publisher() 

124 if publisher: 

125 await publisher.publish_template_render( 

126 template_name=template_name, 

127 render_time_ms=render_time_ms, 

128 cache_hit=cache_hit, 

129 context_size=context_size, 

130 fragment_count=0, # TODO: Extract from result 

131 error=error, 

132 ) 

133 

134 

135async def publish_cache_invalidation( 

136 cache_key: str, 

137 reason: str = "manual", 

138 invalidated_by: str | None = None, 

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

140) -> bool: 

141 """Publish cache invalidation event. 

142 

143 Helper function for cache operations to broadcast invalidation events. 

144 

145 Args: 

146 cache_key: The cache key being invalidated 

147 reason: Reason for invalidation (e.g., "content_updated", "manual") 

148 invalidated_by: User/system that triggered invalidation 

149 affected_templates: List of template names affected by this invalidation 

150 

151 Returns: 

152 True if event published successfully, False otherwise 

153 """ 

154 with suppress(Exception): 

155 from ..._events_integration import get_event_publisher 

156 

157 publisher = get_event_publisher() 

158 if publisher: 

159 return await publisher.publish_cache_invalidation( 

160 cache_key=cache_key, 

161 reason=reason, 

162 invalidated_by=invalidated_by, 

163 affected_templates=affected_templates, 

164 ) 

165 

166 return False 

167 

168 

169async def publish_htmx_refresh( 

170 target: str, 

171 swap_method: str | None = None, 

172) -> bool: 

173 """Publish HTMX refresh event to connected clients. 

174 

175 Args: 

176 target: CSS selector for element to refresh 

177 swap_method: How to swap content ("innerHTML", "outerHTML", etc.) 

178 

179 Returns: 

180 True if event published successfully, False otherwise 

181 """ 

182 with suppress(Exception): 

183 from ..._events_integration import get_event_publisher 

184 

185 publisher = get_event_publisher() 

186 if publisher: 

187 return await publisher.publish_htmx_update( 

188 update_type="refresh", 

189 target=target, 

190 swap_method=swap_method, 

191 ) 

192 

193 return False 

194 

195 

196async def publish_htmx_trigger( 

197 trigger_name: str, 

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

199 target: str | None = None, 

200) -> bool: 

201 """Publish custom HTMX trigger event. 

202 

203 Args: 

204 trigger_name: Name of the custom event 

205 trigger_data: Data to send with the event 

206 target: Optional CSS selector for targeted delivery 

207 

208 Returns: 

209 True if event published successfully, False otherwise 

210 """ 

211 with suppress(Exception): 

212 from ..._events_integration import get_event_publisher 

213 

214 publisher = get_event_publisher() 

215 if publisher: 

216 return await publisher.publish_htmx_update( 

217 update_type="trigger", 

218 trigger_name=trigger_name, 

219 trigger_data=trigger_data, 

220 target=target, 

221 ) 

222 

223 return False 

224 

225 

226async def publish_admin_action( 

227 action_type: str, 

228 user_id: str, 

229 resource_type: str | None = None, 

230 resource_id: str | None = None, 

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

232 ip_address: str | None = None, 

233) -> bool: 

234 """Publish admin action event for audit logging. 

235 

236 Args: 

237 action_type: Type of action ("create", "update", "delete", "login", "logout") 

238 user_id: ID of user performing the action 

239 resource_type: Type of resource being modified 

240 resource_id: ID of specific resource 

241 changes: Dictionary of changes made 

242 ip_address: IP address of the user 

243 

244 Returns: 

245 True if event published successfully, False otherwise 

246 """ 

247 with suppress(Exception): 

248 from ..._events_integration import get_event_publisher 

249 

250 publisher = get_event_publisher() 

251 if publisher: 

252 return await publisher.publish_admin_action( 

253 action_type=action_type, 

254 user_id=user_id, 

255 resource_type=resource_type, 

256 resource_id=resource_id, 

257 changes=changes, 

258 ip_address=ip_address, 

259 ) 

260 

261 return False 

262 

263 

264def get_template_metrics(template_name: str) -> dict[str, t.Any]: 

265 """Get performance metrics for a specific template. 

266 

267 Args: 

268 template_name: Name of the template to get stats for 

269 

270 Returns: 

271 Dictionary with performance statistics or empty dict if unavailable 

272 """ 

273 with suppress(Exception): 

274 # Get the template metrics handler 

275 handler = depends.get_sync("template_metrics") 

276 if handler and hasattr(handler, "get_template_stats"): 

277 stats: dict[str, t.Any] = handler.get_template_stats(template_name) 

278 return stats 

279 

280 return {} 

281 

282 

283def get_recent_admin_actions(limit: int = 50) -> list[dict[str, t.Any]]: 

284 """Get recent admin actions from audit log. 

285 

286 Args: 

287 limit: Maximum number of actions to return 

288 

289 Returns: 

290 List of recent admin actions or empty list if unavailable 

291 """ 

292 with suppress(Exception): 

293 # Get the admin audit handler 

294 handler = depends.get_sync("admin_audit") 

295 if handler and hasattr(handler, "get_recent_actions"): 

296 actions: list[dict[str, t.Any]] = handler.get_recent_actions(limit=limit) 

297 return actions 

298 

299 return [] 

300 

301 

302# Migration indicator 

303_using_oneiric = True