Coverage for /Users/les/Projects/crackerjack/crackerjack/models/resource_protocols.py: 0%

166 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1"""Resource lifecycle management protocols. 

2 

3Defines protocols and interfaces for comprehensive resource management 

4patterns throughout the crackerjack codebase. 

5""" 

6 

7import typing as t 

8from abc import ABC, abstractmethod 

9from types import TracebackType 

10 

11if t.TYPE_CHECKING: 

12 import asyncio 

13 from pathlib import Path 

14 

15 

16class AsyncCleanupProtocol(t.Protocol): 

17 """Protocol for resources that support async cleanup.""" 

18 

19 async def cleanup(self) -> None: 

20 """Clean up the resource asynchronously.""" 

21 ... 

22 

23 

24class SyncCleanupProtocol(t.Protocol): 

25 """Protocol for resources that support synchronous cleanup.""" 

26 

27 def cleanup(self) -> None: 

28 """Clean up the resource synchronously.""" 

29 ... 

30 

31 

32class ResourceLifecycleProtocol(t.Protocol): 

33 """Protocol for resources with full lifecycle management.""" 

34 

35 async def initialize(self) -> None: 

36 """Initialize the resource.""" 

37 ... 

38 

39 async def cleanup(self) -> None: 

40 """Clean up the resource.""" 

41 ... 

42 

43 def is_initialized(self) -> bool: 

44 """Check if the resource is initialized.""" 

45 ... 

46 

47 def is_closed(self) -> bool: 

48 """Check if the resource is closed.""" 

49 ... 

50 

51 

52class AsyncContextProtocol(t.Protocol): 

53 """Protocol for async context managers.""" 

54 

55 async def __aenter__(self) -> t.Self: 

56 """Enter async context.""" 

57 ... 

58 

59 async def __aexit__( 

60 self, 

61 exc_type: type[BaseException] | None, 

62 exc_val: BaseException | None, 

63 exc_tb: TracebackType | None, 

64 ) -> None: 

65 """Exit async context.""" 

66 ... 

67 

68 

69class ResourceManagerProtocol(t.Protocol): 

70 """Protocol for resource managers.""" 

71 

72 def register_resource(self, resource: AsyncCleanupProtocol) -> None: 

73 """Register a resource for management.""" 

74 ... 

75 

76 def register_cleanup_callback( 

77 self, callback: t.Callable[[], t.Awaitable[None]] 

78 ) -> None: 

79 """Register a cleanup callback.""" 

80 ... 

81 

82 async def cleanup_all(self) -> None: 

83 """Clean up all managed resources.""" 

84 ... 

85 

86 

87class FileResourceProtocol(t.Protocol): 

88 """Protocol for file-based resources.""" 

89 

90 @property 

91 def path(self) -> "Path": 

92 """Get the file path.""" 

93 ... 

94 

95 def exists(self) -> bool: 

96 """Check if the file exists.""" 

97 ... 

98 

99 async def cleanup(self) -> None: 

100 """Clean up the file resource.""" 

101 ... 

102 

103 

104class ProcessResourceProtocol(t.Protocol): 

105 """Protocol for process-based resources.""" 

106 

107 @property 

108 def pid(self) -> int: 

109 """Get the process ID.""" 

110 ... 

111 

112 def is_running(self) -> bool: 

113 """Check if the process is running.""" 

114 ... 

115 

116 async def cleanup(self) -> None: 

117 """Clean up the process resource.""" 

118 ... 

119 

120 

121class TaskResourceProtocol(t.Protocol): 

122 """Protocol for asyncio task resources.""" 

123 

124 @property 

125 def task(self) -> "asyncio.Task": 

126 """Get the asyncio task.""" 

127 ... 

128 

129 def is_done(self) -> bool: 

130 """Check if the task is done.""" 

131 ... 

132 

133 def is_cancelled(self) -> bool: 

134 """Check if the task is cancelled.""" 

135 ... 

136 

137 async def cleanup(self) -> None: 

138 """Clean up the task resource.""" 

139 ... 

140 

141 

142class NetworkResourceProtocol(t.Protocol): 

143 """Protocol for network-based resources.""" 

144 

145 @property 

146 def is_connected(self) -> bool: 

147 """Check if the resource is connected.""" 

148 ... 

149 

150 async def disconnect(self) -> None: 

151 """Disconnect the resource.""" 

152 ... 

153 

154 async def cleanup(self) -> None: 

155 """Clean up the network resource.""" 

156 ... 

157 

158 

159class CacheResourceProtocol(t.Protocol): 

160 """Protocol for cache-based resources.""" 

161 

162 def clear(self) -> None: 

163 """Clear the cache.""" 

164 ... 

165 

166 def get_size(self) -> int: 

167 """Get the cache size.""" 

168 ... 

169 

170 async def cleanup(self) -> None: 

171 """Clean up the cache resource.""" 

172 ... 

173 

174 

175# Abstract base classes for resource implementations 

176class AbstractManagedResource(ABC): 

177 """Abstract base class for managed resources.""" 

178 

179 def __init__(self) -> None: 

180 self._initialized = False 

181 self._closed = False 

182 

183 @abstractmethod 

184 async def _do_initialize(self) -> None: 

185 """Perform resource initialization. Override in subclasses.""" 

186 pass 

187 

188 @abstractmethod 

189 async def _do_cleanup(self) -> None: 

190 """Perform resource cleanup. Override in subclasses.""" 

191 pass 

192 

193 async def initialize(self) -> None: 

194 """Initialize the resource if not already initialized.""" 

195 if self._initialized: 

196 return 

197 

198 try: 

199 await self._do_initialize() 

200 self._initialized = True 

201 except Exception: 

202 self._closed = True 

203 raise 

204 

205 async def cleanup(self) -> None: 

206 """Clean up the resource if not already closed.""" 

207 if self._closed: 

208 return 

209 

210 self._closed = True 

211 try: 

212 await self._do_cleanup() 

213 except Exception: 

214 # Log but don't re-raise during cleanup 

215 import logging 

216 

217 logging.getLogger(__name__).warning( 

218 f"Error during cleanup of {self.__class__.__name__}", exc_info=True 

219 ) 

220 

221 def is_initialized(self) -> bool: 

222 """Check if the resource is initialized.""" 

223 return self._initialized 

224 

225 def is_closed(self) -> bool: 

226 """Check if the resource is closed.""" 

227 return self._closed 

228 

229 async def __aenter__(self) -> t.Self: 

230 """Enter async context and initialize.""" 

231 await self.initialize() 

232 return self 

233 

234 async def __aexit__( 

235 self, 

236 exc_type: type[BaseException] | None, 

237 exc_val: BaseException | None, 

238 exc_tb: TracebackType | None, 

239 ) -> None: 

240 """Exit async context and cleanup.""" 

241 await self.cleanup() 

242 

243 

244class AbstractFileResource(AbstractManagedResource): 

245 """Abstract base class for file-based resources.""" 

246 

247 def __init__(self, path: "Path") -> None: 

248 super().__init__() 

249 self._path = path 

250 

251 @property 

252 def path(self) -> "Path": 

253 """Get the file path.""" 

254 return self._path 

255 

256 def exists(self) -> bool: 

257 """Check if the file exists.""" 

258 return self._path.exists() 

259 

260 

261class AbstractProcessResource(AbstractManagedResource): 

262 """Abstract base class for process-based resources.""" 

263 

264 def __init__(self, pid: int) -> None: 

265 super().__init__() 

266 self._pid = pid 

267 

268 @property 

269 def pid(self) -> int: 

270 """Get the process ID.""" 

271 return self._pid 

272 

273 def is_running(self) -> bool: 

274 """Check if the process is running.""" 

275 try: 

276 import os 

277 

278 os.kill(self._pid, 0) 

279 return True 

280 except (OSError, ProcessLookupError): 

281 return False 

282 

283 

284class AbstractTaskResource(AbstractManagedResource): 

285 """Abstract base class for asyncio task resources.""" 

286 

287 def __init__(self, task: "asyncio.Task") -> None: 

288 super().__init__() 

289 self._task = task 

290 

291 @property 

292 def task(self) -> "asyncio.Task": 

293 """Get the asyncio task.""" 

294 return self._task 

295 

296 def is_done(self) -> bool: 

297 """Check if the task is done.""" 

298 return self._task.done() 

299 

300 def is_cancelled(self) -> bool: 

301 """Check if the task is cancelled.""" 

302 return self._task.cancelled() 

303 

304 

305class AbstractNetworkResource(AbstractManagedResource): 

306 """Abstract base class for network-based resources.""" 

307 

308 def __init__(self) -> None: 

309 super().__init__() 

310 self._connected = False 

311 

312 @property 

313 def is_connected(self) -> bool: 

314 """Check if the resource is connected.""" 

315 return self._connected and not self._closed 

316 

317 async def disconnect(self) -> None: 

318 """Disconnect the resource.""" 

319 if self._connected: 

320 self._connected = False 

321 await self._do_disconnect() 

322 

323 @abstractmethod 

324 async def _do_disconnect(self) -> None: 

325 """Perform disconnection. Override in subclasses.""" 

326 pass 

327 

328 async def _do_cleanup(self) -> None: 

329 """Cleanup includes disconnection.""" 

330 await self.disconnect() 

331 

332 

333# Resource lifecycle decorators 

334def with_resource_cleanup(resource_attr: str): 

335 """Decorator to ensure resource cleanup on method exit.""" 

336 

337 def decorator(func: t.Callable[..., t.Awaitable[t.Any]]): 

338 async def wrapper(self, *args, **kwargs): 

339 resource = getattr(self, resource_attr, None) 

340 try: 

341 return await func(self, *args, **kwargs) 

342 finally: 

343 if resource and hasattr(resource, "cleanup"): 

344 await resource.cleanup() 

345 

346 return wrapper 

347 

348 return decorator 

349 

350 

351def ensure_initialized(resource_attr: str): 

352 """Decorator to ensure resource is initialized before method execution.""" 

353 

354 def decorator(func: t.Callable[..., t.Awaitable[t.Any]]): 

355 async def wrapper(self, *args, **kwargs): 

356 resource = getattr(self, resource_attr, None) 

357 if resource and hasattr(resource, "initialize"): 

358 await resource.initialize() 

359 return await func(self, *args, **kwargs) 

360 

361 return wrapper 

362 

363 return decorator 

364 

365 

366# Resource health monitoring protocols 

367class HealthCheckProtocol(t.Protocol): 

368 """Protocol for health checking resources.""" 

369 

370 async def health_check(self) -> dict[str, t.Any]: 

371 """Perform health check and return status.""" 

372 ... 

373 

374 def is_healthy(self) -> bool: 

375 """Quick health check.""" 

376 ... 

377 

378 

379class MonitorableResourceProtocol(t.Protocol): 

380 """Protocol for resources that can be monitored.""" 

381 

382 def get_metrics(self) -> dict[str, t.Any]: 

383 """Get resource metrics.""" 

384 ... 

385 

386 def get_status(self) -> str: 

387 """Get resource status string.""" 

388 ... 

389 

390 async def health_check(self) -> dict[str, t.Any]: 

391 """Perform health check.""" 

392 ... 

393 

394 

395# Resource factory protocols 

396class ResourceFactoryProtocol(t.Protocol): 

397 """Protocol for resource factories.""" 

398 

399 async def create_resource(self, **kwargs) -> AsyncCleanupProtocol: 

400 """Create a new resource instance.""" 

401 ... 

402 

403 def get_resource_type(self) -> str: 

404 """Get the resource type name.""" 

405 ... 

406 

407 

408class PooledResourceProtocol(t.Protocol): 

409 """Protocol for pooled resources.""" 

410 

411 async def acquire(self) -> AsyncCleanupProtocol: 

412 """Acquire a resource from the pool.""" 

413 ... 

414 

415 async def release(self, resource: AsyncCleanupProtocol) -> None: 

416 """Release a resource back to the pool.""" 

417 ... 

418 

419 def get_pool_size(self) -> int: 

420 """Get current pool size.""" 

421 ... 

422 

423 def get_active_count(self) -> int: 

424 """Get count of active resources.""" 

425 ... 

426 

427 

428# Error handling protocols 

429class ResourceErrorProtocol(t.Protocol): 

430 """Protocol for resource error handling.""" 

431 

432 def handle_error(self, error: Exception) -> bool: 

433 """Handle resource error. Return True if error was handled.""" 

434 ... 

435 

436 def should_retry(self, error: Exception) -> bool: 

437 """Check if operation should be retried on this error.""" 

438 ... 

439 

440 def get_retry_delay(self, attempt: int) -> float: 

441 """Get delay before retry attempt.""" 

442 ... 

443 

444 

445class FallbackResourceProtocol(t.Protocol): 

446 """Protocol for resources with fallback capabilities.""" 

447 

448 async def get_fallback(self) -> AsyncCleanupProtocol | None: 

449 """Get fallback resource if primary fails.""" 

450 ... 

451 

452 def has_fallback(self) -> bool: 

453 """Check if fallback is available.""" 

454 ...