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
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""Resource lifecycle management protocols.
3Defines protocols and interfaces for comprehensive resource management
4patterns throughout the crackerjack codebase.
5"""
7import typing as t
8from abc import ABC, abstractmethod
9from types import TracebackType
11if t.TYPE_CHECKING:
12 import asyncio
13 from pathlib import Path
16class AsyncCleanupProtocol(t.Protocol):
17 """Protocol for resources that support async cleanup."""
19 async def cleanup(self) -> None:
20 """Clean up the resource asynchronously."""
21 ...
24class SyncCleanupProtocol(t.Protocol):
25 """Protocol for resources that support synchronous cleanup."""
27 def cleanup(self) -> None:
28 """Clean up the resource synchronously."""
29 ...
32class ResourceLifecycleProtocol(t.Protocol):
33 """Protocol for resources with full lifecycle management."""
35 async def initialize(self) -> None:
36 """Initialize the resource."""
37 ...
39 async def cleanup(self) -> None:
40 """Clean up the resource."""
41 ...
43 def is_initialized(self) -> bool:
44 """Check if the resource is initialized."""
45 ...
47 def is_closed(self) -> bool:
48 """Check if the resource is closed."""
49 ...
52class AsyncContextProtocol(t.Protocol):
53 """Protocol for async context managers."""
55 async def __aenter__(self) -> t.Self:
56 """Enter async context."""
57 ...
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 ...
69class ResourceManagerProtocol(t.Protocol):
70 """Protocol for resource managers."""
72 def register_resource(self, resource: AsyncCleanupProtocol) -> None:
73 """Register a resource for management."""
74 ...
76 def register_cleanup_callback(
77 self, callback: t.Callable[[], t.Awaitable[None]]
78 ) -> None:
79 """Register a cleanup callback."""
80 ...
82 async def cleanup_all(self) -> None:
83 """Clean up all managed resources."""
84 ...
87class FileResourceProtocol(t.Protocol):
88 """Protocol for file-based resources."""
90 @property
91 def path(self) -> "Path":
92 """Get the file path."""
93 ...
95 def exists(self) -> bool:
96 """Check if the file exists."""
97 ...
99 async def cleanup(self) -> None:
100 """Clean up the file resource."""
101 ...
104class ProcessResourceProtocol(t.Protocol):
105 """Protocol for process-based resources."""
107 @property
108 def pid(self) -> int:
109 """Get the process ID."""
110 ...
112 def is_running(self) -> bool:
113 """Check if the process is running."""
114 ...
116 async def cleanup(self) -> None:
117 """Clean up the process resource."""
118 ...
121class TaskResourceProtocol(t.Protocol):
122 """Protocol for asyncio task resources."""
124 @property
125 def task(self) -> "asyncio.Task":
126 """Get the asyncio task."""
127 ...
129 def is_done(self) -> bool:
130 """Check if the task is done."""
131 ...
133 def is_cancelled(self) -> bool:
134 """Check if the task is cancelled."""
135 ...
137 async def cleanup(self) -> None:
138 """Clean up the task resource."""
139 ...
142class NetworkResourceProtocol(t.Protocol):
143 """Protocol for network-based resources."""
145 @property
146 def is_connected(self) -> bool:
147 """Check if the resource is connected."""
148 ...
150 async def disconnect(self) -> None:
151 """Disconnect the resource."""
152 ...
154 async def cleanup(self) -> None:
155 """Clean up the network resource."""
156 ...
159class CacheResourceProtocol(t.Protocol):
160 """Protocol for cache-based resources."""
162 def clear(self) -> None:
163 """Clear the cache."""
164 ...
166 def get_size(self) -> int:
167 """Get the cache size."""
168 ...
170 async def cleanup(self) -> None:
171 """Clean up the cache resource."""
172 ...
175# Abstract base classes for resource implementations
176class AbstractManagedResource(ABC):
177 """Abstract base class for managed resources."""
179 def __init__(self) -> None:
180 self._initialized = False
181 self._closed = False
183 @abstractmethod
184 async def _do_initialize(self) -> None:
185 """Perform resource initialization. Override in subclasses."""
186 pass
188 @abstractmethod
189 async def _do_cleanup(self) -> None:
190 """Perform resource cleanup. Override in subclasses."""
191 pass
193 async def initialize(self) -> None:
194 """Initialize the resource if not already initialized."""
195 if self._initialized:
196 return
198 try:
199 await self._do_initialize()
200 self._initialized = True
201 except Exception:
202 self._closed = True
203 raise
205 async def cleanup(self) -> None:
206 """Clean up the resource if not already closed."""
207 if self._closed:
208 return
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
217 logging.getLogger(__name__).warning(
218 f"Error during cleanup of {self.__class__.__name__}", exc_info=True
219 )
221 def is_initialized(self) -> bool:
222 """Check if the resource is initialized."""
223 return self._initialized
225 def is_closed(self) -> bool:
226 """Check if the resource is closed."""
227 return self._closed
229 async def __aenter__(self) -> t.Self:
230 """Enter async context and initialize."""
231 await self.initialize()
232 return self
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()
244class AbstractFileResource(AbstractManagedResource):
245 """Abstract base class for file-based resources."""
247 def __init__(self, path: "Path") -> None:
248 super().__init__()
249 self._path = path
251 @property
252 def path(self) -> "Path":
253 """Get the file path."""
254 return self._path
256 def exists(self) -> bool:
257 """Check if the file exists."""
258 return self._path.exists()
261class AbstractProcessResource(AbstractManagedResource):
262 """Abstract base class for process-based resources."""
264 def __init__(self, pid: int) -> None:
265 super().__init__()
266 self._pid = pid
268 @property
269 def pid(self) -> int:
270 """Get the process ID."""
271 return self._pid
273 def is_running(self) -> bool:
274 """Check if the process is running."""
275 try:
276 import os
278 os.kill(self._pid, 0)
279 return True
280 except (OSError, ProcessLookupError):
281 return False
284class AbstractTaskResource(AbstractManagedResource):
285 """Abstract base class for asyncio task resources."""
287 def __init__(self, task: "asyncio.Task") -> None:
288 super().__init__()
289 self._task = task
291 @property
292 def task(self) -> "asyncio.Task":
293 """Get the asyncio task."""
294 return self._task
296 def is_done(self) -> bool:
297 """Check if the task is done."""
298 return self._task.done()
300 def is_cancelled(self) -> bool:
301 """Check if the task is cancelled."""
302 return self._task.cancelled()
305class AbstractNetworkResource(AbstractManagedResource):
306 """Abstract base class for network-based resources."""
308 def __init__(self) -> None:
309 super().__init__()
310 self._connected = False
312 @property
313 def is_connected(self) -> bool:
314 """Check if the resource is connected."""
315 return self._connected and not self._closed
317 async def disconnect(self) -> None:
318 """Disconnect the resource."""
319 if self._connected:
320 self._connected = False
321 await self._do_disconnect()
323 @abstractmethod
324 async def _do_disconnect(self) -> None:
325 """Perform disconnection. Override in subclasses."""
326 pass
328 async def _do_cleanup(self) -> None:
329 """Cleanup includes disconnection."""
330 await self.disconnect()
333# Resource lifecycle decorators
334def with_resource_cleanup(resource_attr: str):
335 """Decorator to ensure resource cleanup on method exit."""
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()
346 return wrapper
348 return decorator
351def ensure_initialized(resource_attr: str):
352 """Decorator to ensure resource is initialized before method execution."""
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)
361 return wrapper
363 return decorator
366# Resource health monitoring protocols
367class HealthCheckProtocol(t.Protocol):
368 """Protocol for health checking resources."""
370 async def health_check(self) -> dict[str, t.Any]:
371 """Perform health check and return status."""
372 ...
374 def is_healthy(self) -> bool:
375 """Quick health check."""
376 ...
379class MonitorableResourceProtocol(t.Protocol):
380 """Protocol for resources that can be monitored."""
382 def get_metrics(self) -> dict[str, t.Any]:
383 """Get resource metrics."""
384 ...
386 def get_status(self) -> str:
387 """Get resource status string."""
388 ...
390 async def health_check(self) -> dict[str, t.Any]:
391 """Perform health check."""
392 ...
395# Resource factory protocols
396class ResourceFactoryProtocol(t.Protocol):
397 """Protocol for resource factories."""
399 async def create_resource(self, **kwargs) -> AsyncCleanupProtocol:
400 """Create a new resource instance."""
401 ...
403 def get_resource_type(self) -> str:
404 """Get the resource type name."""
405 ...
408class PooledResourceProtocol(t.Protocol):
409 """Protocol for pooled resources."""
411 async def acquire(self) -> AsyncCleanupProtocol:
412 """Acquire a resource from the pool."""
413 ...
415 async def release(self, resource: AsyncCleanupProtocol) -> None:
416 """Release a resource back to the pool."""
417 ...
419 def get_pool_size(self) -> int:
420 """Get current pool size."""
421 ...
423 def get_active_count(self) -> int:
424 """Get count of active resources."""
425 ...
428# Error handling protocols
429class ResourceErrorProtocol(t.Protocol):
430 """Protocol for resource error handling."""
432 def handle_error(self, error: Exception) -> bool:
433 """Handle resource error. Return True if error was handled."""
434 ...
436 def should_retry(self, error: Exception) -> bool:
437 """Check if operation should be retried on this error."""
438 ...
440 def get_retry_delay(self, attempt: int) -> float:
441 """Get delay before retry attempt."""
442 ...
445class FallbackResourceProtocol(t.Protocol):
446 """Protocol for resources with fallback capabilities."""
448 async def get_fallback(self) -> AsyncCleanupProtocol | None:
449 """Get fallback resource if primary fails."""
450 ...
452 def has_fallback(self) -> bool:
453 """Check if fallback is available."""
454 ...