Spaces:
Paused
Paused
File size: 6,745 Bytes
8d1819a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
import asyncio
from dataclasses import dataclass
import threading
from concurrent.futures import Future
from typing import Any, Callable, Optional, Coroutine, TypeVar, Awaitable
T = TypeVar("T")
class EventLoopThread:
_instances = {}
_lock = threading.Lock()
def __init__(self, thread_name: str = "Background") -> None:
"""Initialize the event loop thread."""
self.thread_name = thread_name
self._start()
def __new__(cls, thread_name: str = "Background"):
with cls._lock:
if thread_name not in cls._instances:
instance = super(EventLoopThread, cls).__new__(cls)
cls._instances[thread_name] = instance
return cls._instances[thread_name]
def _start(self):
if not hasattr(self, "loop") or not self.loop:
self.loop = asyncio.new_event_loop()
if not hasattr(self, "thread") or not self.thread:
self.thread = threading.Thread(
target=self._run_event_loop, daemon=True, name=self.thread_name
)
self.thread.start()
def _run_event_loop(self):
if not self.loop:
raise RuntimeError("Event loop is not initialized")
asyncio.set_event_loop(self.loop)
self.loop.run_forever()
def terminate(self):
if self.loop and self.loop.is_running():
self.loop.stop()
self.loop = None
self.thread = None
def run_coroutine(self, coro):
self._start()
if not self.loop:
raise RuntimeError("Event loop is not initialized")
return asyncio.run_coroutine_threadsafe(coro, self.loop)
@dataclass
class ChildTask:
task: "DeferredTask"
terminate_thread: bool
class DeferredTask:
def __init__(
self,
thread_name: str = "Background",
):
self.event_loop_thread = EventLoopThread(thread_name)
self._future: Optional[Future] = None
self.children: list[ChildTask] = []
def start_task(
self, func: Callable[..., Coroutine[Any, Any, Any]], *args: Any, **kwargs: Any
):
self.func = func
self.args = args
self.kwargs = kwargs
self._start_task()
return self
def __del__(self):
self.kill()
def _start_task(self):
self._future = self.event_loop_thread.run_coroutine(self._run())
async def _run(self):
return await self.func(*self.args, **self.kwargs)
def is_ready(self) -> bool:
return self._future.done() if self._future else False
def result_sync(self, timeout: Optional[float] = None) -> Any:
if not self._future:
raise RuntimeError("Task hasn't been started")
try:
return self._future.result(timeout)
except TimeoutError:
raise TimeoutError(
"The task did not complete within the specified timeout."
)
async def result(self, timeout: Optional[float] = None) -> Any:
if not self._future:
raise RuntimeError("Task hasn't been started")
loop = asyncio.get_running_loop()
def _get_result():
try:
result = self._future.result(timeout) # type: ignore
# self.kill()
return result
except TimeoutError:
raise TimeoutError(
"The task did not complete within the specified timeout."
)
return await loop.run_in_executor(None, _get_result)
def kill(self, terminate_thread: bool = False) -> None:
"""Kill the task and optionally terminate its thread."""
self.kill_children()
if self._future and not self._future.done():
self._future.cancel()
if (
terminate_thread
and self.event_loop_thread.loop
and self.event_loop_thread.loop.is_running()
):
def cleanup():
tasks = [
t
for t in asyncio.all_tasks(self.event_loop_thread.loop)
if t is not asyncio.current_task(self.event_loop_thread.loop)
]
for task in tasks:
task.cancel()
try:
# Give tasks a chance to cleanup
if self.event_loop_thread.loop:
self.event_loop_thread.loop.run_until_complete(
asyncio.gather(task, return_exceptions=True)
)
except Exception:
pass # Ignore cleanup errors
self.event_loop_thread.loop.call_soon_threadsafe(cleanup)
self.event_loop_thread.terminate()
def kill_children(self) -> None:
for child in self.children:
child.task.kill(terminate_thread=child.terminate_thread)
self.children = []
def is_alive(self) -> bool:
return self._future and not self._future.done() # type: ignore
def restart(self, terminate_thread: bool = False) -> None:
self.kill(terminate_thread=terminate_thread)
self._start_task()
def add_child_task(
self, task: "DeferredTask", terminate_thread: bool = False
) -> None:
self.children.append(ChildTask(task, terminate_thread))
async def _execute_in_task_context(
self, func: Callable[..., T], *args, **kwargs
) -> T:
"""Execute a function in the task's context and return its result."""
result = func(*args, **kwargs)
if asyncio.iscoroutine(result):
return await result
return result
def execute_inside(self, func: Callable[..., T], *args, **kwargs) -> Awaitable[T]:
if not self.event_loop_thread.loop:
raise RuntimeError("Event loop is not initialized")
future: Future = Future()
async def wrapped():
if not self.event_loop_thread.loop:
raise RuntimeError("Event loop is not initialized")
try:
result = await self._execute_in_task_context(func, *args, **kwargs)
# Keep awaiting until we get a concrete value
while isinstance(result, Awaitable):
result = await result
self.event_loop_thread.loop.call_soon_threadsafe(
future.set_result, result
)
except Exception as e:
self.event_loop_thread.loop.call_soon_threadsafe(
future.set_exception, e
)
asyncio.run_coroutine_threadsafe(wrapped(), self.event_loop_thread.loop)
return asyncio.wrap_future(future)
|