[tor-commits] [stem/master] Implement a basic version of a synchronous wrapper of the controller
atagar at torproject.org
atagar at torproject.org
Thu Jul 16 01:28:59 UTC 2020
commit 7ba32adba08b83c85f7ec9b76db144e960798b79
Author: Illia Volochii <illia.volochii at gmail.com>
Date: Thu Apr 23 20:35:54 2020 +0300
Implement a basic version of a synchronous wrapper of the controller
---
stem/control.py | 37 +++++++++++++++++++++++++++++++++++++
1 file changed, 37 insertions(+)
diff --git a/stem/control.py b/stem/control.py
index cc5c9bd7..e264e4b5 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -3883,6 +3883,43 @@ class AsyncController(BaseController):
return (set_events, failed_events)
+class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
+ def __init__(self, control_socket: 'stem.socket.ControlSocket', is_authenticated: bool = False) -> None:
+ self._asyncio_loop = asyncio.get_event_loop()
+
+ self._asyncio_thread = threading.Thread(target=self._asyncio_loop.run_forever, name='asyncio')
+ self._asyncio_thread.setDaemon(True)
+ self._asyncio_thread.start()
+
+ self._async_controller = AsyncController(control_socket, is_authenticated)
+ self._socket = self._async_controller._socket
+
+ def _execute_async_method(self, method_name: str, *args: Any, **kwargs: Any) -> Any:
+ return asyncio.run_coroutine_threadsafe(
+ getattr(self._async_controller, method_name)(*args, **kwargs),
+ self._asyncio_loop,
+ ).result()
+
+ def msg(self, message: str) -> stem.response.ControlMessage:
+ return self._execute_async_method('msg', message)
+
+ def connect(self) -> None:
+ self._execute_async_method('connect')
+
+ def close(self) -> None:
+ self._execute_async_method('close')
+ self._asyncio_loop.call_soon_threadsafe(self._asyncio_loop.stop)
+ if self._asyncio_thread.is_alive():
+ self._asyncio_thread.join()
+ self._asyncio_loop.close()
+
+ def __enter__(self) -> 'stem.control.Controller':
+ return self
+
+ def __exit__(self, exit_type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> None:
+ self.close()
+
+
def _parse_circ_path(path: str) -> Sequence[Tuple[str, str]]:
"""
Parses a circuit path as a list of **(fingerprint, nickname)** tuples. Tor
More information about the tor-commits
mailing list