Debian Codegraph @

wyoming/client.py

raw
1 import asyncio
2 from abc import ABC
3 from pathlib import Path
4 from typing import Optional, Union
5 from urllib.parse import urlparse
6
7 from .event import (
8 Event,
9 async_get_stdin,
10 async_get_stdout,
11 async_read_event,
12 async_write_event,
13 )
14
15
16 class AsyncClient(ABC):
17 """Base class for Wyoming async client."""
18
19 def __init__(self) -> None:
20 self._reader: Optional[asyncio.StreamReader] = None
21 self._writer: Optional[asyncio.StreamWriter] = None
22
23 async def read_event(self) -> Optional[Event]:
24 assert self._reader is not None
25 return await async_read_event(self._reader)
26
27 async def write_event(self, event: Event) -> None:
28 assert self._writer is not None
29 await async_write_event(event, self._writer)
30
31 async def connect(self) -> None:
32 pass
33
34 async def __aenter__(self):
35 await self.connect()
36 return self
37
38 async def disconnect(self) -> None:
39 pass
40
41 async def __aexit__(self, exc_type, exc_value, traceback):
42 await self.disconnect()
43
44 @staticmethod
45 def from_uri(uri: str) -> "AsyncClient":
46 result = urlparse(uri)
47
48 if result.scheme == "unix":
49 return AsyncUnixClient(result.path)
50
51 if result.scheme == "tcp":
52 if (result.hostname is None) or (result.port is None):
53 raise ValueError("A port must be specified when using a 'tcp://' URI")
54
55 return AsyncTcpClient(result.hostname, result.port)
56
57 if result.scheme == "stdio":
58 return AsyncStdioClient()
59
60 raise ValueError("Only 'stdio://', 'unix://', or 'tcp://' are supported")
61
62
63 class AsyncTcpClient(AsyncClient):
64 """TCP Wyoming client."""
65
66 def __init__(self, host: str, port: int) -> None:
67 super().__init__()
68
69 self.host = host
70 self.port = port
71
72 async def connect(self) -> None:
73 self._reader, self._writer = await asyncio.open_connection(
74 host=self.host,
75 port=self.port,
76 )
77
78 async def disconnect(self) -> None:
79 writer = self._writer
80 self._reader = None
81 self._writer = None
82
83 if writer is not None:
84 writer.close()
85 await writer.wait_closed()
86
87
88 class AsyncUnixClient(AsyncClient):
89 """Unix domain socket Wyoming client."""
90
91 def __init__(self, socket_path: Union[str, Path]) -> None:
92 super().__init__()
93
94 self.socket_path = Path(socket_path)
95
96 async def connect(self) -> None:
97 self._reader, self._writer = await asyncio.open_unix_connection(
98 path=self.socket_path
99 )
100
101 async def disconnect(self) -> None:
102 writer = self._writer
103 self._reader = None
104 self._writer = None
105
106 if writer is not None:
107 writer.close()
108 await writer.wait_closed()
109
110
111 class AsyncStdioClient(AsyncClient):
112 """Standard output Wyoming client."""
113
114 def __init__(self) -> None:
115 super().__init__()
116
117 self._reader: Optional[asyncio.StreamReader] = None
118 self._writer: Optional[asyncio.StreamWriter] = None
119
120 async def read_event(self) -> Optional[Event]:
121 if self._reader is None:
122 self._reader = await async_get_stdin()
123
124 assert self._reader is not None
125 return await async_read_event(self._reader)
126
127 async def write_event(self, event: Event) -> None:
128 if self._writer is None:
129 self._writer = await async_get_stdout()
130
131 assert self._writer is not None
132 await async_write_event(event, self._writer)