|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import warnings |
| 5 | +from queue import Queue |
| 6 | +from threading import Thread |
| 7 | +from typing import TYPE_CHECKING, NamedTuple |
| 8 | + |
| 9 | +from .kaleido import Kaleido |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from typing import Any |
| 13 | + |
| 14 | + |
| 15 | +class Task(NamedTuple): |
| 16 | + fn: str |
| 17 | + args: Any |
| 18 | + kwargs: Any |
| 19 | + |
| 20 | + |
| 21 | +class _BadFunctionName(BaseException): |
| 22 | + """For use when programmed poorly.""" |
| 23 | + |
| 24 | + |
| 25 | +class GlobalKaleidoServer: |
| 26 | + _instance = None |
| 27 | + |
| 28 | + async def _server(self, *args, **kwargs): |
| 29 | + async with Kaleido(*args, **kwargs) as k: # multiple processor? Enable GPU? |
| 30 | + while True: |
| 31 | + task = self._task_queue.get() # thread dies if main thread dies |
| 32 | + if task is None: |
| 33 | + self._task_queue.task_done() |
| 34 | + return |
| 35 | + if not hasattr(k, task.fn): |
| 36 | + raise _BadFunctionName(f"Kaleido has no attribute {task.fn}") |
| 37 | + try: |
| 38 | + self._return_queue.put( |
| 39 | + await getattr(k, task.fn)(*task.args, **task.kwargs), |
| 40 | + ) |
| 41 | + except Exception as e: # noqa: BLE001 |
| 42 | + self._return_queue.put(e) |
| 43 | + |
| 44 | + self._task_queue.task_done() |
| 45 | + |
| 46 | + def __new__(cls): |
| 47 | + # Create the singleton on first instantiation |
| 48 | + if cls._instance is None: |
| 49 | + cls._instance = super().__new__(cls) |
| 50 | + cls._instance._initialized = False # noqa: SLF001 |
| 51 | + return cls._instance |
| 52 | + |
| 53 | + def is_running(self): |
| 54 | + return self._initialized |
| 55 | + |
| 56 | + def open(self, *args, **kwargs): |
| 57 | + """Initialize the singleton with three values.""" |
| 58 | + if self.is_running(): |
| 59 | + warnings.warn( |
| 60 | + "Server already open.", |
| 61 | + RuntimeWarning, |
| 62 | + stacklevel=2, |
| 63 | + ) |
| 64 | + return |
| 65 | + coroutine = self._server(*args, **kwargs) |
| 66 | + self._thread: Thread = Thread(target=asyncio.run, args=(coroutine,)) |
| 67 | + self._task_queue: Queue[Task | None] = Queue() |
| 68 | + self._return_queue: Queue[Any] = Queue() |
| 69 | + self._thread.start() |
| 70 | + self._initialized = True |
| 71 | + |
| 72 | + def close(self): |
| 73 | + """Reset the singleton back to an uninitialized state.""" |
| 74 | + if not self.is_running(): |
| 75 | + warnings.warn( |
| 76 | + "Server already closed.", |
| 77 | + RuntimeWarning, |
| 78 | + stacklevel=2, |
| 79 | + ) |
| 80 | + return |
| 81 | + self._task_queue.put(None) |
| 82 | + self._thread.join() |
| 83 | + del self._thread |
| 84 | + del self._task_queue |
| 85 | + del self._return_queue |
| 86 | + self._initialized = False |
| 87 | + |
| 88 | + def call_function(self, cmd: str, *args, **kwargs): |
| 89 | + if not self._is_running(): |
| 90 | + raise RuntimeError("Can't call function on stopped server.") |
| 91 | + if kwargs.pop("kopts"): |
| 92 | + warnings.warn( |
| 93 | + "The kopts argument is ignored if using a server.", |
| 94 | + UserWarning, |
| 95 | + stacklevel=3, |
| 96 | + ) |
| 97 | + self._task_queue.put(Task(cmd, args, kwargs)) |
| 98 | + self._task_queue.join() |
| 99 | + res = self._return_queue.get() |
| 100 | + if isinstance(res, BaseException): |
| 101 | + raise res |
| 102 | + else: |
| 103 | + return res |
| 104 | + |
| 105 | + |
| 106 | +def oneshot_async_run(func, args: tuple[Any, ...], kwargs: dict): |
| 107 | + q: Queue[Any] = Queue(maxsize=1) |
| 108 | + |
| 109 | + def run(func, q, *args, **kwargs): |
| 110 | + # func is a closure |
| 111 | + try: |
| 112 | + q.put(asyncio.run(func(*args, **kwargs))) |
| 113 | + except BaseException as e: # noqa: BLE001 |
| 114 | + q.put(e) |
| 115 | + |
| 116 | + t = Thread(target=run, args=(func, q, *args), kwargs=kwargs) |
| 117 | + t.start() |
| 118 | + t.join() |
| 119 | + res = q.get() |
| 120 | + if isinstance(res, BaseException): |
| 121 | + raise res |
| 122 | + else: |
| 123 | + return res |
0 commit comments