hat.drivers.net
1from hat.drivers.net.common import UnixAddress 2from hat.drivers.net.datagram import (UdpAddress, 3 DatagramAddress, 4 UdpEndpointInfo, 5 UnixEndpointInfo, 6 EndpointInfo, 7 DatagramType, 8 endpoint_info_to_json, 9 create_endpoint, 10 Endpoint) 11from hat.drivers.net.stream import (TcpAddress, 12 StreamAddress, 13 TcpConnectionInfo, 14 UnixConnectionInfo, 15 TcpServerInfo, 16 UnixServerInfo, 17 ConnectionInfo, 18 ServerInfo, 19 StreamType, 20 ConnectionCb, 21 connection_info_to_json, 22 server_info_to_json, 23 connect, 24 listen, 25 Server, 26 Connection) 27 28 29__all__ = ['UnixAddress', 30 'UdpAddress', 31 'DatagramAddress', 32 'UdpEndpointInfo', 33 'UnixEndpointInfo', 34 'EndpointInfo', 35 'DatagramType', 36 'endpoint_info_to_json', 37 'create_endpoint', 38 'Endpoint', 39 'TcpAddress', 40 'StreamAddress', 41 'TcpConnectionInfo', 42 'UnixConnectionInfo', 43 'TcpServerInfo', 44 'UnixServerInfo', 45 'ConnectionInfo', 46 'ServerInfo', 47 'StreamType', 48 'ConnectionCb', 49 'connection_info_to_json', 50 'server_info_to_json', 51 'connect', 52 'listen', 53 'Server', 54 'Connection']
UdpAddress(host, port)
28class UdpEndpointInfo(typing.NamedTuple): 29 name: str | None 30 local_addr: UdpAddress 31 remote_addr: UdpAddress | None
UdpEndpointInfo(name, local_addr, remote_addr)
Create new instance of UdpEndpointInfo(name, local_addr, remote_addr)
34class UnixEndpointInfo(typing.NamedTuple): 35 name: str | None 36 local_addr: common.UnixAddress | None 37 remote_addr: common.UnixAddress | None
UnixEndpointInfo(name, local_addr, remote_addr)
48def endpoint_info_to_json(info: EndpointInfo) -> json.Data: 49 if isinstance(info, UdpEndpointInfo): 50 data = {'name': info.name, 51 'local_addr': {'host': info.local_addr.host, 52 'port': info.local_addr.port}} 53 54 if info.remote_addr is not None: 55 data['remote_addr'] = {'host': info.remote_addr.host, 56 'port': info.remote_addr.port} 57 58 return data 59 60 if isinstance(info, UnixEndpointInfo): 61 data = {'name': info.name} 62 63 if info.local_addr is not None: 64 data['local_addr'] = str(info.local_addr) 65 66 if info.remote_addr is not None: 67 data['remote_addr'] = str(info.remote_addr) 68 69 return data 70 71 raise TypeError('unsupported info type')
74async def create_endpoint(datagram_type: DatagramType = DatagramType.UDP, 75 local_addr: DatagramAddress | None = None, 76 remote_addr: DatagramAddress | None = None, 77 *, 78 name: str | None = None, 79 receive_queue_size: int = 0, 80 close_timeout: float | None = 5, 81 **kwargs 82 ) -> 'Endpoint': 83 """Create new UDP or Unix Domain Socket endpoint 84 85 Argument `name` defines endpoint name available in property `info`. 86 87 Argument `close_timeout` defines maximum time in seconds that closing 88 of endpoint can take. 89 90 Additional arguments are passed directly to 91 `asyncio.AbstractEventLoop.create_datagram_endpoint`. 92 93 """ 94 loop = asyncio.get_running_loop() 95 96 create_protocol = functools.partial(_Protocol, datagram_type, name, 97 receive_queue_size, close_timeout) 98 family = _get_address_family(datagram_type) 99 100 if isinstance(local_addr, common.UnixAddress): 101 local_addr = str(local_addr) 102 103 if isinstance(remote_addr, common.UnixAddress): 104 remote_addr = str(remote_addr) 105 106 _, protocol = await loop.create_datagram_endpoint(create_protocol, 107 local_addr, 108 remote_addr, 109 family=family, 110 **kwargs) 111 112 try: 113 return _create_endpoint(protocol) 114 115 except Exception: 116 await aio.uncancellable(protocol.async_close()) 117 raise
Create new UDP or Unix Domain Socket endpoint
Argument name defines endpoint name available in property info.
Argument close_timeout defines maximum time in seconds that closing
of endpoint can take.
Additional arguments are passed directly to
asyncio.AbstractEventLoop.create_datagram_endpoint.
135class Endpoint(aio.Resource): 136 """UDP or Unix Domain Socket endpoint""" 137 138 @property 139 def async_group(self) -> aio.Group: 140 """Async group""" 141 return self._async_group 142 143 @property 144 def info(self) -> EndpointInfo: 145 """Endpoint info""" 146 return self._protocol.info 147 148 @property 149 def empty(self) -> bool: 150 """Is receive queue empty""" 151 return self._protocol.empty 152 153 def send(self, 154 data: util.Bytes, 155 remote_addr: DatagramAddress | None = None): 156 """Send datagram 157 158 If `remote_addr` is not set, `remote_addr` passed to `create` is used. 159 160 """ 161 if not self.is_open: 162 raise ConnectionError() 163 164 self._protocol.send(data, remote_addr) 165 166 async def receive(self) -> tuple[util.Bytes, DatagramAddress | None]: 167 """Receive datagram""" 168 return await self._protocol.receive()
UDP or Unix Domain Socket endpoint
138 @property 139 def async_group(self) -> aio.Group: 140 """Async group""" 141 return self._async_group
Async group
143 @property 144 def info(self) -> EndpointInfo: 145 """Endpoint info""" 146 return self._protocol.info
Endpoint info
148 @property 149 def empty(self) -> bool: 150 """Is receive queue empty""" 151 return self._protocol.empty
Is receive queue empty
153 def send(self, 154 data: util.Bytes, 155 remote_addr: DatagramAddress | None = None): 156 """Send datagram 157 158 If `remote_addr` is not set, `remote_addr` passed to `create` is used. 159 160 """ 161 if not self.is_open: 162 raise ConnectionError() 163 164 self._protocol.send(data, remote_addr)
Send datagram
If remote_addr is not set, remote_addr passed to create is used.
166 async def receive(self) -> tuple[util.Bytes, DatagramAddress | None]: 167 """Receive datagram""" 168 return await self._protocol.receive()
Receive datagram
TcpAddress(host, port)
32class TcpConnectionInfo(typing.NamedTuple): 33 name: str | None 34 local_addr: TcpAddress 35 remote_addr: TcpAddress
TcpConnectionInfo(name, local_addr, remote_addr)
Create new instance of TcpConnectionInfo(name, local_addr, remote_addr)
UnixConnectionInfo(name, addr)
TcpServerInfo(name, addresses)
Create new instance of TcpServerInfo(name, addresses)
48class UnixServerInfo(typing.NamedTuple): 49 name: str | None 50 addresses: list[common.UnixAddress]
UnixServerInfo(name, addresses)
67def connection_info_to_json(info: ConnectionInfo) -> json.Data: 68 if isinstance(info, TcpConnectionInfo): 69 return {'name': info.name, 70 'local_addr': {'host': info.local_addr.host, 71 'port': info.local_addr.port}, 72 'remote_addr': {'host': info.remote_addr.host, 73 'port': info.remote_addr.port}} 74 75 if isinstance(info, UnixConnectionInfo): 76 return {'name': info.name, 77 'addr': str(info.addr)} 78 79 raise TypeError('unsupported info type')
82def server_info_to_json(info: ServerInfo) -> json.Data: 83 if isinstance(info, TcpServerInfo): 84 return {'name': info.name, 85 'addresses': [{'host': addr.host, 86 'port': addr.port} 87 for addr in info.addresses]} 88 89 if isinstance(info, UnixServerInfo): 90 return {'name': info.name, 91 'addresses': [str(addr) for addr in info.addresses]} 92 93 raise TypeError('unsupported info type')
96async def connect(addr: StreamAddress, 97 *, 98 name: str | None = None, 99 input_buffer_limit: int = 64 * 1024, 100 close_timeout: float | None = 30, 101 half_close: bool = False, 102 **kwargs 103 ) -> 'Connection': 104 """Create TCP or Unix Domain Socket connection 105 106 Argument `addr` specifies remote server listening address. 107 108 Argument `name` defines connection name available in property `info`. 109 110 Argument `input_buffer_limit` defines number of bytes in input buffer 111 that will temporary pause data receiving. Once number of bytes 112 drops below `input_buffer_limit`, data receiving is resumed. If this 113 argument is ``0``, data receive pausing is disabled. 114 115 Argument `close_timeout` defines maximum time in seconds that closing 116 of connection can take. 117 118 If `half_close` is ``False``, receiving end of stream from remote peer 119 closes connection. If `half_close` is ``True``, connection remains open 120 for writing after remote peer ends its side of the stream (reading 121 raises `ConnectionError` once all received data is read). 122 123 Additional arguments are passed directly to `asyncio.create_connection` or 124 `asyncio.create_unix_connection`. 125 126 """ 127 loop = asyncio.get_running_loop() 128 stream_type = _get_stream_type(addr) 129 create_protocol = functools.partial(_Protocol, stream_type, None, name, 130 input_buffer_limit, close_timeout, 131 half_close) 132 133 if stream_type == StreamType.TCP: 134 _, protocol = await loop.create_connection(create_protocol, 135 addr.host, addr.port, 136 **kwargs) 137 138 elif stream_type == StreamType.UNIX: 139 _, protocol = await loop.create_unix_connection(create_protocol, addr, 140 **kwargs) 141 142 else: 143 raise ValueError('unsupported stream type') 144 145 try: 146 return _create_connection(protocol) 147 148 except Exception: 149 await aio.uncancellable(protocol.async_close()) 150 raise
Create TCP or Unix Domain Socket connection
Argument addr specifies remote server listening address.
Argument name defines connection name available in property info.
Argument input_buffer_limit defines number of bytes in input buffer
that will temporary pause data receiving. Once number of bytes
drops below input_buffer_limit, data receiving is resumed. If this
argument is 0, data receive pausing is disabled.
Argument close_timeout defines maximum time in seconds that closing
of connection can take.
If half_close is False, receiving end of stream from remote peer
closes connection. If half_close is True, connection remains open
for writing after remote peer ends its side of the stream (reading
raises ConnectionError once all received data is read).
Additional arguments are passed directly to asyncio.create_connection or
asyncio.create_unix_connection.
153async def listen(connection_cb: ConnectionCb, 154 addr: StreamAddress, 155 *, 156 name: str | None = None, 157 bind_connections: bool = False, 158 input_buffer_limit: int = 64 * 1024, 159 close_timeout: float | None = 30, 160 half_close: bool = False, 161 **kwargs 162 ) -> 'Server': 163 """Create listening TCP or Unix Domain Socket server 164 165 Argument `name` defines server name available in property `info`. This 166 name is used for all incoming connections. 167 168 If `bind_connections` is ``True``, closing server will close all open 169 incoming connections. 170 171 Arguments `input_buffer_limit`, `close_timeout` and `half_close` are 172 associated with newly created connections (see `connect`). 173 174 Additional arguments are passed directly to `asyncio.create_server` or 175 `asyncio.create_unix_server`. 176 177 """ 178 server = Server() 179 server._connection_cb = connection_cb 180 server._bind_connections = bind_connections 181 server._stream_type = _get_stream_type(addr) 182 server._async_group = aio.Group() 183 server._log = mlog 184 185 loop = asyncio.get_running_loop() 186 on_connection = functools.partial(server.async_group.spawn, 187 server._on_connection) 188 create_protocol = functools.partial(_Protocol, server._stream_type, 189 on_connection, name, 190 input_buffer_limit, close_timeout, 191 half_close) 192 193 try: 194 if server._stream_type == StreamType.TCP: 195 server._srv = await loop.create_server(create_protocol, 196 addr.host, addr.port, 197 **kwargs) 198 199 elif server._stream_type == StreamType.UNIX: 200 server._srv = await loop.create_unix_server(create_protocol, 201 addr, **kwargs) 202 203 else: 204 raise ValueError('unsupported stream type') 205 206 server.async_group.spawn(aio.call_on_cancel, server._on_close) 207 208 server._info = _get_server_info(server._stream_type, name, server._srv) 209 server._log = _create_server_logger(server._info) 210 211 except BaseException: 212 await aio.uncancellable(server.async_close()) 213 raise 214 215 server._log.debug('listening for incoming connections') 216 217 return server
Create listening TCP or Unix Domain Socket server
Argument name defines server name available in property info. This
name is used for all incoming connections.
If bind_connections is True, closing server will close all open
incoming connections.
Arguments input_buffer_limit, close_timeout and half_close are
associated with newly created connections (see connect).
Additional arguments are passed directly to asyncio.create_server or
asyncio.create_unix_server.
220class Server(aio.Resource): 221 """TCP or Unix Domain Socket listening server 222 223 Closing server will cancel all running `connection_cb` coroutines. 224 225 """ 226 227 @property 228 def async_group(self) -> aio.Group: 229 """Async group""" 230 return self._async_group 231 232 @property 233 def info(self) -> ServerInfo: 234 """Server info""" 235 return self._info 236 237 async def _on_close(self): 238 self._srv.close() 239 240 if self._bind_connections or sys.version_info[:2] < (3, 12): 241 await self._srv.wait_closed() 242 243 async def _on_connection(self, protocol): 244 self._log.debug('new incoming connection') 245 246 try: 247 conn = _create_connection(protocol) 248 249 except Exception as e: 250 self._log.warning('create connection error: %s', e, exc_info=e) 251 252 await aio.uncancellable(protocol.async_close()) 253 return 254 255 try: 256 await aio.call(self._connection_cb, conn) 257 258 if self._bind_connections: 259 await conn.wait_closing() 260 261 else: 262 conn = None 263 264 except Exception as e: 265 self._log.warning('connection callback error: %s', e, exc_info=e) 266 267 finally: 268 if conn: 269 await aio.uncancellable(conn.async_close())
TCP or Unix Domain Socket listening server
Closing server will cancel all running connection_cb coroutines.
227 @property 228 def async_group(self) -> aio.Group: 229 """Async group""" 230 return self._async_group
Async group
287class Connection(aio.Resource): 288 """TCP or Unix Domain Socket connection""" 289 290 @property 291 def async_group(self) -> aio.Group: 292 """Async group""" 293 return self._async_group 294 295 @property 296 def info(self) -> ConnectionInfo: 297 """Connection info""" 298 return self._protocol.info 299 300 @property 301 def ssl_object(self) -> ssl.SSLObject | ssl.SSLSocket | None: 302 """SSL Object""" 303 return self._protocol.ssl_object 304 305 async def write(self, data: util.Bytes): 306 """Write data 307 308 This coroutine will wait until `data` can be added to output buffer. 309 310 """ 311 if not self.is_open: 312 raise ConnectionError() 313 314 await self._protocol.write(data) 315 316 async def drain(self): 317 """Wait until it is appropriate to resume writing to the stream 318 319 See `asyncio.StreamWriter.drain`. 320 321 """ 322 await self._protocol.drain() 323 324 async def read(self, n: int = -1) -> util.Bytes: 325 """Read up to `n` bytes 326 327 If EOF is detected and no new bytes are available, `ConnectionError` 328 is raised. 329 330 If ``n < 0``, read all data available in input buffer. 331 332 If input buffer is empty, this coroutine waits until data is available. 333 334 """ 335 return await self._protocol.read(n, False) 336 337 async def readexactly(self, n: int) -> util.Bytes: 338 """Read exactly `n` bytes 339 340 If exact number of bytes could not be read, `ConnectionError` is 341 raised. 342 343 """ 344 return await self._protocol.read(n, True) 345 346 def clear_input_buffer(self) -> int: 347 """Clear input buffer 348 349 Returns number of bytes cleared from buffer. 350 351 """ 352 return self._protocol.clear_input_buffer()
TCP or Unix Domain Socket connection
290 @property 291 def async_group(self) -> aio.Group: 292 """Async group""" 293 return self._async_group
Async group
295 @property 296 def info(self) -> ConnectionInfo: 297 """Connection info""" 298 return self._protocol.info
Connection info
300 @property 301 def ssl_object(self) -> ssl.SSLObject | ssl.SSLSocket | None: 302 """SSL Object""" 303 return self._protocol.ssl_object
SSL Object
305 async def write(self, data: util.Bytes): 306 """Write data 307 308 This coroutine will wait until `data` can be added to output buffer. 309 310 """ 311 if not self.is_open: 312 raise ConnectionError() 313 314 await self._protocol.write(data)
Write data
This coroutine will wait until data can be added to output buffer.
316 async def drain(self): 317 """Wait until it is appropriate to resume writing to the stream 318 319 See `asyncio.StreamWriter.drain`. 320 321 """ 322 await self._protocol.drain()
Wait until it is appropriate to resume writing to the stream
See asyncio.StreamWriter.drain.
324 async def read(self, n: int = -1) -> util.Bytes: 325 """Read up to `n` bytes 326 327 If EOF is detected and no new bytes are available, `ConnectionError` 328 is raised. 329 330 If ``n < 0``, read all data available in input buffer. 331 332 If input buffer is empty, this coroutine waits until data is available. 333 334 """ 335 return await self._protocol.read(n, False)
Read up to n bytes
If EOF is detected and no new bytes are available, ConnectionError
is raised.
If n < 0, read all data available in input buffer.
If input buffer is empty, this coroutine waits until data is available.
337 async def readexactly(self, n: int) -> util.Bytes: 338 """Read exactly `n` bytes 339 340 If exact number of bytes could not be read, `ConnectionError` is 341 raised. 342 343 """ 344 return await self._protocol.read(n, True)
Read exactly n bytes
If exact number of bytes could not be read, ConnectionError is
raised.