Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/task_manager.py: 0%

163 statements  

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

1import asyncio 

2import logging 

3import time 

4import typing as t 

5from contextlib import asynccontextmanager, suppress 

6from dataclasses import dataclass 

7 

8from rich.console import Console 

9 

10console = Console() 

11logger = logging.getLogger(__name__) 

12 

13 

14@dataclass 

15class TaskInfo: 

16 task_id: str 

17 task: asyncio.Task 

18 created_at: float 

19 description: str = "" 

20 timeout_seconds: float | None = None 

21 

22 

23class AsyncTaskManager: 

24 def __init__(self, max_concurrent_tasks: int = 10) -> None: 

25 self.max_concurrent_tasks = max_concurrent_tasks 

26 self._tasks: dict[str, TaskInfo] = {} 

27 self._task_semaphore = asyncio.Semaphore(max_concurrent_tasks) 

28 self._cleanup_task: asyncio.Task | None = None 

29 self._running = False 

30 self._lock = asyncio.Lock() 

31 

32 async def start(self) -> None: 

33 self._running = True 

34 self._cleanup_task = asyncio.create_task(self._cleanup_loop()) 

35 try: 

36 console.print( 

37 f"[green]🎯 Task Manager started (max {self.max_concurrent_tasks} concurrent)[ / green]", 

38 ) 

39 except (ValueError, OSError): 

40 import logging 

41 

42 logging.info( 

43 f"Task Manager started (max {self.max_concurrent_tasks} concurrent) ", 

44 ) 

45 

46 async def stop(self) -> None: 

47 self._running = False 

48 

49 if self._cleanup_task: 

50 self._cleanup_task.cancel() 

51 with suppress(asyncio.CancelledError): 

52 await self._cleanup_task 

53 

54 await self._cancel_all_tasks() 

55 try: 

56 console.print("[yellow]🎯 Task Manager stopped[ / yellow]") 

57 except (ValueError, OSError): 

58 import logging 

59 

60 logging.info("Task Manager stopped") 

61 

62 async def create_task( 

63 self, 

64 coro: t.Coroutine, 

65 task_id: str, 

66 description: str = "", 

67 timeout_seconds: float | None = None, 

68 ) -> asyncio.Task: 

69 async with self._lock: 

70 if task_id in self._tasks: 

71 msg = f"Task {task_id} already exists" 

72 raise ValueError(msg) 

73 

74 if len(self._tasks) >= self.max_concurrent_tasks: 

75 msg = f"Maximum concurrent tasks ({self.max_concurrent_tasks}) reached" 

76 raise RuntimeError( 

77 msg, 

78 ) 

79 

80 if timeout_seconds: 

81 coro = asyncio.wait_for(coro, timeout=timeout_seconds) 

82 

83 task = asyncio.create_task(self._wrap_task(coro, task_id)) 

84 

85 task_info = TaskInfo( 

86 task_id=task_id, 

87 task=task, 

88 created_at=time.time(), 

89 description=description, 

90 timeout_seconds=timeout_seconds, 

91 ) 

92 

93 async with self._lock: 

94 self._tasks[task_id] = task_info 

95 

96 logger.info(f"Created task {task_id}: {description}") 

97 from contextlib import suppress 

98 

99 with suppress(ValueError, OSError): 

100 console.print(f"[blue]🚀 Task {task_id} created: {description}[ / blue]") 

101 return task 

102 

103 async def _wrap_task(self, coro: t.Coroutine, task_id: str) -> t.Any: 

104 try: 

105 async with self._task_semaphore: 

106 result = await coro 

107 logger.info(f"Task {task_id} completed successfully") 

108 return result 

109 except asyncio.CancelledError: 

110 logger.info(f"Task {task_id} was cancelled") 

111 raise 

112 except Exception as e: 

113 logger.exception(f"Task {task_id} failed: {e}") 

114 from contextlib import suppress 

115 

116 with suppress(ValueError, OSError): 

117 console.print(f"[red]❌ Task {task_id} failed: {e}[ / red]") 

118 raise 

119 finally: 

120 async with self._lock: 

121 if task_id in self._tasks: 

122 del self._tasks[task_id] 

123 

124 async def cancel_task(self, task_id: str) -> bool: 

125 async with self._lock: 

126 task_info = self._tasks.get(task_id) 

127 if not task_info: 

128 return False 

129 

130 task_info.task.cancel() 

131 logger.info(f"Cancelled task {task_id}") 

132 from contextlib import suppress 

133 

134 with suppress(ValueError, OSError): 

135 console.print(f"[yellow]🚫 Task {task_id} cancelled[ / yellow]") 

136 return True 

137 

138 async def get_task_status(self, task_id: str) -> dict[str, t.Any] | None: 

139 async with self._lock: 

140 task_info = self._tasks.get(task_id) 

141 if not task_info: 

142 return None 

143 

144 return { 

145 "task_id": task_id, 

146 "description": task_info.description, 

147 "created_at": task_info.created_at, 

148 "running_time": time.time() - task_info.created_at, 

149 "done": task_info.task.done(), 

150 "cancelled": task_info.task.cancelled(), 

151 "timeout_seconds": task_info.timeout_seconds, 

152 } 

153 

154 async def list_active_tasks(self) -> list[dict[str, t.Any]]: 

155 async with self._lock: 

156 tasks = [] 

157 for task_id, task_info in self._tasks.items(): 

158 task_status = { 

159 "task_id": task_id, 

160 "description": task_info.description, 

161 "created_at": task_info.created_at, 

162 "running_time": time.time() - task_info.created_at, 

163 "done": task_info.task.done(), 

164 "cancelled": task_info.task.cancelled(), 

165 "timeout_seconds": task_info.timeout_seconds, 

166 } 

167 tasks.append(task_status) 

168 return tasks 

169 

170 async def wait_for_task(self, task_id: str, timeout: float | None = None) -> t.Any: 

171 async with self._lock: 

172 task_info = self._tasks.get(task_id) 

173 if not task_info: 

174 msg = f"Task {task_id} not found" 

175 raise ValueError(msg) 

176 

177 try: 

178 if timeout: 

179 return await asyncio.wait_for(task_info.task, timeout=timeout) 

180 return await task_info.task 

181 except TimeoutError: 

182 logger.warning(f"Timeout waiting for task {task_id}") 

183 raise 

184 

185 @asynccontextmanager 

186 async def managed_task( 

187 self, 

188 coro: t.Coroutine, 

189 task_id: str, 

190 description: str = "", 

191 timeout_seconds: float | None = None, 

192 ): 

193 task = await self.create_task(coro, task_id, description, timeout_seconds) 

194 try: 

195 yield task 

196 finally: 

197 if not task.done(): 

198 task.cancel() 

199 with suppress(asyncio.CancelledError): 

200 await task 

201 

202 async def _cancel_all_tasks(self) -> None: 

203 async with self._lock: 

204 tasks_to_cancel = list(self._tasks.values()) 

205 

206 if not tasks_to_cancel: 

207 return 

208 

209 try: 

210 console.print( 

211 f"[yellow]🧹 Cancelling {len(tasks_to_cancel)} running tasks[ / yellow]", 

212 ) 

213 except (ValueError, OSError): 

214 import logging 

215 

216 logging.info(f"Cancelling {len(tasks_to_cancel)} running tasks") 

217 

218 for task_info in tasks_to_cancel: 

219 task_info.task.cancel() 

220 

221 await asyncio.gather( 

222 *[task_info.task for task_info in tasks_to_cancel], 

223 return_exceptions=True, 

224 ) 

225 

226 async with self._lock: 

227 self._tasks.clear() 

228 

229 async def _cleanup_loop(self) -> None: 

230 while self._running: 

231 try: 

232 await self._cleanup_completed_tasks() 

233 await asyncio.sleep(30) 

234 except asyncio.CancelledError: 

235 break 

236 except Exception as e: 

237 logger.exception(f"Error in task cleanup loop: {e}") 

238 await asyncio.sleep(5) 

239 

240 async def _cleanup_completed_tasks(self) -> None: 

241 async with self._lock: 

242 completed_tasks = [] 

243 for task_id, task_info in list(self._tasks.items()): 

244 if task_info.task.done(): 

245 completed_tasks.append(task_id) 

246 del self._tasks[task_id] 

247 

248 if completed_tasks: 

249 logger.info(f"Cleaned up {len(completed_tasks)} completed tasks") 

250 

251 def get_stats(self) -> dict[str, t.Any]: 

252 return { 

253 "running": self._running, 

254 "active_tasks": len(self._tasks), 

255 "max_concurrent_tasks": self.max_concurrent_tasks, 

256 "available_slots": self._task_semaphore._value, 

257 }