pyserve3 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyserve/__init__.py ADDED
@@ -0,0 +1,128 @@
1
+ """
2
+ Unify socket server implementations using session-based model
3
+ """
4
+ from ssl import SSLContext
5
+ from typing import Any, Dict, Optional, Tuple, Type
6
+
7
+ from .abc import (
8
+ Address, AsyncSession, RawAddr, SessFactory, Session, UdpWriter, Writer)
9
+ from .client import AbstractClient, TcpAsyncClient, UdpAsyncClient
10
+ from .threading import TcpThreadServer, UdpThreadServer
11
+ from .transport import TcpAsyncServer, TcpSession, UdpAsyncServer, UdpSession
12
+
13
+ #** Variables **#
14
+ __all__ = [
15
+ 'listen_udp_async',
16
+ 'listen_tcp_async',
17
+ 'listen_udp_threaded',
18
+ 'listen_tcp_threaded',
19
+
20
+ 'Address',
21
+ 'RawAddr',
22
+ 'Session',
23
+ 'AsyncSession',
24
+ 'SessFactory',
25
+ 'UdpWriter',
26
+ 'Writer',
27
+
28
+ 'AbstractClient',
29
+ 'TcpAsyncClient',
30
+ 'UdpAsyncClient',
31
+
32
+ 'UdpThreadServer',
33
+ 'TcpThreadServer',
34
+ 'UdpAsyncServer',
35
+ 'TcpAsyncServer',
36
+ ]
37
+
38
+ #** Functions **#
39
+
40
+ async def listen_udp_async(
41
+ address: RawAddr,
42
+ factory: Type[UdpSession],
43
+ args: Tuple[Any, ...] = (),
44
+ kwargs: Dict[str, Any] = {},
45
+ interface: Optional[str] = None,
46
+ reuse_port: bool = False,
47
+ allow_broadcast: bool = False,
48
+ ) -> None:
49
+ """
50
+ """
51
+ async with UdpAsyncServer(
52
+ address=address,
53
+ factory=SessFactory(factory, *args, **kwargs),
54
+ interface=interface,
55
+ reuse_port=reuse_port,
56
+ allow_broadcast=allow_broadcast,
57
+ ) as server:
58
+ await server.serve_forever()
59
+
60
+ async def listen_tcp_async(
61
+ address: RawAddr,
62
+ factory: Type[TcpSession],
63
+ args: Tuple[Any, ...] = (),
64
+ kwargs: Dict[str, Any] = {},
65
+ interface: Optional[str] = None,
66
+ reuse_port: bool = False,
67
+ backlog: int = 100,
68
+ ssl: Optional[SSLContext] = None,
69
+ timeout: Optional[int] = None,
70
+ ) -> None:
71
+ """
72
+ """
73
+ async with TcpAsyncServer(
74
+ address=address,
75
+ factory=SessFactory(factory, *args, **kwargs),
76
+ interface=interface,
77
+ reuse_port=reuse_port,
78
+ backlog=backlog,
79
+ ssl=ssl,
80
+ timeout=timeout,
81
+ ) as server:
82
+ await server.serve_forever()
83
+
84
+ def listen_udp_threaded(
85
+ address: RawAddr,
86
+ factory: Type[Session[UdpWriter]],
87
+ args: Tuple[Any, ...] = (),
88
+ kwargs: Dict[str, Any] = {},
89
+ interface: Optional[str] = None,
90
+ reuse_port: bool = False,
91
+ allow_broadcast: bool = False,
92
+ blocksize: int = 8192
93
+ ) -> None:
94
+ """
95
+ """
96
+ with UdpThreadServer(
97
+ address=address,
98
+ factory=SessFactory(factory, *args, **kwargs),
99
+ interface=interface,
100
+ blocksize=blocksize,
101
+ reuse_port=reuse_port,
102
+ allow_broadcast=allow_broadcast,
103
+ ) as server:
104
+ server.serve_forever()
105
+
106
+ def listen_tcp_threaded(
107
+ address: RawAddr,
108
+ factory: Type[Session[Writer]],
109
+ args: Tuple[Any, ...] = (),
110
+ kwargs: Dict[str, Any] = {},
111
+ interface: Optional[str] = None,
112
+ reuse_port: bool = False,
113
+ blocksize: int = 8192,
114
+ ssl: Optional[SSLContext] = None,
115
+ timeout: Optional[int] = None,
116
+ ) -> None:
117
+ """
118
+ """
119
+ with TcpThreadServer(
120
+ address=address,
121
+ factory=SessFactory(factory, *args, **kwargs),
122
+ interface=interface,
123
+ reuse_port=reuse_port,
124
+ blocksize=blocksize,
125
+ ssl=ssl,
126
+ timeout=timeout,
127
+ ) as server:
128
+ server.serve_forever()
pyserve/abc.py ADDED
@@ -0,0 +1,150 @@
1
+ """
2
+ PyServe Common Abstractions
3
+ """
4
+ import socket
5
+ from abc import abstractmethod
6
+ from ssl import SSLContext
7
+ from typing import (
8
+ Callable, ClassVar, Generic, NamedTuple, Optional, Protocol, Tuple,
9
+ TypeVar, Union)
10
+ from typing_extensions import ParamSpec
11
+
12
+ #** Variables **#
13
+ __all__ = [
14
+ 'P',
15
+ 'S',
16
+ 'W',
17
+ 'RawAddr',
18
+ 'AnyAddr',
19
+
20
+ 'modify_socket',
21
+
22
+ 'Address',
23
+ 'SessFactory',
24
+ 'Writer',
25
+ 'UdpWriter',
26
+ 'Session',
27
+ ]
28
+
29
+ P = ParamSpec('P')
30
+ S = TypeVar('S', bound=Union['Session', 'AsyncSession'])
31
+ W = TypeVar('W', bound='BaseWriter', contravariant=True)
32
+ RawAddr = Tuple[str, int]
33
+ AnyAddr = Union[RawAddr, 'Address']
34
+
35
+ #** Functions **#
36
+
37
+ def modify_socket(
38
+ sock: socket.socket,
39
+ timeout: Optional[int],
40
+ interface: Optional[str]
41
+ ) -> socket.socket:
42
+ """
43
+ Modify the socket object with the following options
44
+ """
45
+ if timeout is not None:
46
+ sock.settimeout(timeout)
47
+ if interface is not None:
48
+ iface = interface.encode()
49
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, iface)
50
+ return sock
51
+
52
+ #** Classes **#
53
+
54
+ class Address(NamedTuple):
55
+ host: str
56
+ port: int
57
+
58
+ class SessFactory(Generic[S]):
59
+ __slots__ = ('factory', 'args', 'kwargs', 'is_async')
60
+
61
+ def __init__(self, factory: Callable[P, S], *args: P.args, **kwargs: P.kwargs):
62
+ self.factory = factory
63
+ self.args = args
64
+ self.kwargs = kwargs
65
+ self.is_async = hasattr(self.build(), '_IS_ASYNC')
66
+
67
+ def build(self) -> S:
68
+ return self.factory(*self.args, **self.kwargs)
69
+
70
+ class BaseWriter(Protocol):
71
+
72
+ @abstractmethod
73
+ def using_tls(self) -> bool:
74
+ raise NotImplementedError
75
+
76
+ @abstractmethod
77
+ def close(self):
78
+ raise NotImplementedError
79
+
80
+ @abstractmethod
81
+ def is_closing(self) -> bool:
82
+ raise NotImplementedError
83
+
84
+ class Writer(BaseWriter):
85
+ """
86
+ Abstract socket writer implementation for a single server connection
87
+ """
88
+
89
+ @abstractmethod
90
+ def start_tls(self, context: SSLContext):
91
+ raise NotImplementedError
92
+
93
+ @abstractmethod
94
+ def write(self, data: bytes) -> None:
95
+ raise NotImplementedError
96
+
97
+ class UdpWriter(BaseWriter):
98
+ """
99
+ Abstract socket writer implementation for a single UDP server connection
100
+ """
101
+
102
+ def using_tls(self) -> bool:
103
+ return False
104
+
105
+ @abstractmethod
106
+ def write(self, data: bytes, addr: Optional[AnyAddr] = None) -> None:
107
+ raise NotImplementedError
108
+
109
+ class Session(Protocol[W]):
110
+ """
111
+ Abstract session-manager implementation for single server connection
112
+ """
113
+
114
+ def _datagram_recieved(self, addr: Address, writer: W, data: bytes):
115
+ self.connection_made(addr, writer)
116
+ self.data_received(data)
117
+
118
+ @abstractmethod
119
+ def connection_made(self, addr: Address, writer: W):
120
+ raise NotImplementedError
121
+
122
+ @abstractmethod
123
+ def data_received(self, data: bytes):
124
+ raise NotImplementedError
125
+
126
+ @abstractmethod
127
+ def connection_lost(self, err: Optional[Exception]):
128
+ raise NotImplementedError
129
+
130
+ class AsyncSession(Protocol[W]):
131
+ """
132
+ Abstract async session-manager implementation for single server connection
133
+ """
134
+ _IS_ASYNC: ClassVar[bool] = True
135
+
136
+ async def _datagram_recieved(self, addr: Address, writer: W, data: bytes):
137
+ await self.connection_made(addr, writer)
138
+ await self.data_received(data)
139
+
140
+ @abstractmethod
141
+ async def connection_made(self, addr: Address, writer: W):
142
+ raise NotImplementedError
143
+
144
+ @abstractmethod
145
+ async def data_received(self, data: bytes):
146
+ raise NotImplementedError
147
+
148
+ @abstractmethod
149
+ async def connection_lost(self, err: Optional[Exception]):
150
+ raise NotImplementedError
pyserve/client.py ADDED
@@ -0,0 +1,343 @@
1
+ """
2
+ PyServe Socket Client Utilities
3
+ """
4
+ import socket
5
+ import asyncio
6
+ from abc import abstractmethod
7
+ from ssl import SSLContext, SSLSession
8
+ from typing import Awaitable, Optional, Protocol, Tuple, TypeVar, Union
9
+ from typing_extensions import Self
10
+
11
+ from .abc import RawAddr
12
+
13
+ #** Variables **#
14
+ __all__ = ['AbstractClient', 'TcpAsyncClient', 'UdpAsyncClient']
15
+
16
+ T = TypeVar('T')
17
+ Bytes = Union[bytes, bytearray, memoryview]
18
+ SockPair = Tuple[asyncio.StreamReader, asyncio.StreamWriter]
19
+
20
+ #** Function **#
21
+
22
+ async def backported_start_tls(
23
+ writer: asyncio.StreamWriter,
24
+ sslcontext: SSLContext, *,
25
+ server_hostname: Optional[str] = None,
26
+ ssl_handshake_timeout: Optional[float] = None,
27
+ ssl_shutdown_timeout: Optional[float] = None,
28
+ ):
29
+ """
30
+ Backported StartTLS
31
+
32
+ Method is not available until py3.11 but this library supports py3.8
33
+ Source (https://github.com/python/cpython/blob/3.14/Lib/asyncio/streams.py)
34
+ """
35
+ loop: asyncio.AbstractEventLoop = getattr(writer, '_loop')
36
+ protocol: asyncio.StreamReaderProtocol = getattr(writer, '_protocol')
37
+ transport: asyncio.Transport = getattr(writer, '_transport')
38
+ server_side = getattr(protocol, '_client_connected_cb') is not None
39
+ await writer.drain()
40
+ new_transport = await loop.start_tls(
41
+ transport, protocol, sslcontext,
42
+ server_side=server_side, server_hostname=server_hostname,
43
+ ssl_handshake_timeout=ssl_handshake_timeout,
44
+ ssl_shutdown_timeout=ssl_shutdown_timeout)
45
+ setattr(writer, '_transport', new_transport)
46
+ getattr(protocol, '_replace_transport')(new_transport)
47
+
48
+ #** Classes **#
49
+
50
+ class AbstractClient(Protocol):
51
+ """
52
+ Abstract async socket client
53
+ """
54
+ socket: socket.socket
55
+ timeout: Optional[float]
56
+
57
+ async def __aenter__(self) -> Self:
58
+ return self
59
+
60
+ async def __aexit__(self, *_):
61
+ self.close()
62
+
63
+ async def _wait(self,
64
+ co: Awaitable[T], timeout: Optional[float] = None) -> T:
65
+ """
66
+ Wait until coroutine has completed with timeout control
67
+ """
68
+ inner = co if timeout is None else asyncio.wait_for(co, timeout)
69
+ return await inner
70
+
71
+ def set_timeout(self, timeout: Optional[float] = None) -> None:
72
+ """
73
+ Configure global socket timeout for read/write operations
74
+ """
75
+ self.timeout = timeout
76
+
77
+ def bind_interface(self, interface: bytes) -> None:
78
+ """
79
+ Bind socket to a particular interface
80
+ """
81
+ self.socket.setsockopt(
82
+ socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface)
83
+
84
+ @abstractmethod
85
+ async def connect(self, addr: RawAddr):
86
+ raise NotImplementedError
87
+
88
+ @abstractmethod
89
+ async def recv(self, nbytes: int, timeout: Optional[float] = None) -> bytes:
90
+ raise NotImplementedError
91
+
92
+ @abstractmethod
93
+ async def send(self, data: Bytes, timeout: Optional[float] = None) -> None:
94
+ raise NotImplementedError
95
+
96
+ @abstractmethod
97
+ def close(self):
98
+ raise NotImplementedError
99
+
100
+ class TcpAsyncClient(AbstractClient):
101
+ """
102
+ Simple async TCP client implementation
103
+ """
104
+ __slots__ = ('loop', 'timeout', 'rw', 'force_proto')
105
+
106
+ rw: Optional[SockPair]
107
+
108
+ def __init__(self,
109
+ timeout: Optional[float] = None, force_proto: bool = True):
110
+ self.loop = asyncio.get_running_loop()
111
+ self.timeout = timeout
112
+ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
113
+ self.rw = None
114
+ self.force_proto = force_proto
115
+ self.socket.setblocking(False)
116
+
117
+ def _socket(self) -> SockPair:
118
+ """
119
+ Retrieve socket reader/writer pair once connected
120
+ """
121
+ if self.rw is None:
122
+ raise ConnectionError('Not connected')
123
+ return self.rw
124
+
125
+ async def wrap_ssl(self,
126
+ ctx: SSLContext,
127
+ server_hostname: Optional[str] = None,
128
+ ) -> None:
129
+ """
130
+ Wrap socket in SSL context and complete handshake
131
+ """
132
+ _, writer = self._socket()
133
+ if hasattr(writer, 'start_tls'):
134
+ await writer.start_tls(
135
+ sslcontext=ctx,
136
+ server_hostname=server_hostname,
137
+ ssl_handshake_timeout=self.timeout,
138
+ )
139
+ else:
140
+ await backported_start_tls(
141
+ writer=writer,
142
+ sslcontext=ctx,
143
+ server_hostname=server_hostname,
144
+ ssl_handshake_timeout=self.timeout,
145
+ )
146
+
147
+ async def connect(self, addr: RawAddr):
148
+ """
149
+ Connect to the TCP server at the specified address
150
+ """
151
+ if self.rw is not None:
152
+ raise ConnectionError('Already connected')
153
+ await self.loop.sock_connect(self.socket, addr)
154
+ self.rw = await asyncio.open_connection(
155
+ sock=self.socket)
156
+
157
+ async def recv(self, nbytes: int, timeout: Optional[float] = None) -> bytes:
158
+ """
159
+ Receive a response from the TCP server
160
+ """
161
+ reader, _ = self._socket()
162
+ task = reader.read(nbytes) \
163
+ if self.force_proto else \
164
+ self.loop.sock_recv(self.socket, nbytes)
165
+ return await self._wait(task, timeout or self.timeout)
166
+
167
+ async def send(self, data: Bytes, timeout: Optional[float] = None) -> None:
168
+ """
169
+ Send data to the TCP server
170
+ """
171
+ if self.force_proto:
172
+ _, writer = self._socket()
173
+ writer.write(data)
174
+ else:
175
+ task = self.loop.sock_sendall(self.socket, data)
176
+ await self._wait(task, timeout or self.timeout)
177
+
178
+ def close(self):
179
+ """
180
+ Close socket connection and client
181
+ """
182
+ if self.rw is None:
183
+ return
184
+ _, writer = self.rw
185
+ writer.close()
186
+ self.socket.close()
187
+ self.rw = None
188
+
189
+ class UdpAsyncClient(AbstractClient):
190
+ """
191
+ Simple async UDP client implementation
192
+ """
193
+ __slots__ = ('loop', 'socket', 'timeout', '_addr', '_dgram')
194
+
195
+ def __init__(self,
196
+ timeout: Optional[float] = None, force_proto: bool = True):
197
+ self.loop = asyncio.get_running_loop()
198
+ self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
199
+ self.timeout = timeout
200
+ self.socket.setblocking(False)
201
+ self._addr = None
202
+ self._dgram = None \
203
+ if hasattr(self.loop, 'sock_recvfrom') and not force_proto else \
204
+ _UdpClientBackport(self.loop, self.socket)
205
+
206
+ def _getaddr(self, addr: Optional[RawAddr]) -> RawAddr:
207
+ """
208
+ Retrieve the address of the UDP server or raise an error
209
+ """
210
+ addr = addr or self._addr
211
+ if addr is not None:
212
+ return addr
213
+ raise RuntimeError(f'UDP socket is not connected. No address')
214
+
215
+ async def connect(self, addr: RawAddr) -> None:
216
+ """
217
+ Configure a default address for UDP client to use
218
+ """
219
+ self._addr = addr
220
+
221
+ async def send(self, data: Bytes, timeout: Optional[float] = None) -> None:
222
+ """
223
+ Send data to default UDP server configured with `connect`
224
+ """
225
+ await self.sendto(data, timeout=timeout)
226
+
227
+ async def recv(self, nbytes: int, timeout: Optional[float] = None) -> bytes:
228
+ """
229
+ Receive data from UDP server at the address configured with `connect`
230
+ """
231
+ expected = self._getaddr(None)
232
+ data, addr = await self.recvfrom(nbytes, timeout=timeout)
233
+ if addr is not None and addr != expected:
234
+ raise RuntimeError(f'Unexpected response from address {addr}')
235
+ return data
236
+
237
+ async def recvfrom(self,
238
+ nbytes: int, timeout: Optional[float] = None) -> Tuple[bytes, RawAddr]:
239
+ """
240
+ Wait for an inbound message over UDP socket connection
241
+ """
242
+ task = self.loop.sock_recvfrom(self.socket, nbytes) \
243
+ if self._dgram is None else \
244
+ self._dgram.recvfrom()
245
+ return await self._wait(task, timeout or self.timeout)
246
+
247
+ async def sendto(self,
248
+ data: Bytes,
249
+ addr: Optional[RawAddr] = None,
250
+ timeout: Optional[float] = None,
251
+ ) -> None:
252
+ """
253
+ Send a message over the UDP socket with the given bytes and address
254
+ """
255
+ addr = self._getaddr(addr)
256
+ task = self.loop.sock_sendto(self.socket, data, addr) \
257
+ if self._dgram is None else \
258
+ self._dgram.sendto(data, addr)
259
+ await self._wait(task, timeout or self.timeout)
260
+
261
+ def close(self):
262
+ """
263
+ Close the client connection to server
264
+ """
265
+ if self.socket._closed:
266
+ return
267
+ self.socket.close()
268
+ if self._dgram is not None:
269
+ self._dgram.close()
270
+
271
+ class _UdpClientBackport:
272
+ """
273
+ UDP client backported support system.
274
+
275
+ `loop.sock_sendto` and `loop.sock_recvfrom` were not introduced until py3.11
276
+ and so this method uses the old `asyncio.create_datagram_endpoint` method
277
+ to handle socket interactions safely and asyncly.
278
+ """
279
+ __slots__ = ('loop', 'socket', 'tport', 'proto')
280
+
281
+ socket: socket.socket
282
+ tport: Optional[asyncio.DatagramTransport]
283
+ proto: Optional['_UdpProtocol']
284
+
285
+ def __init__(self, loop: asyncio.AbstractEventLoop, socket: socket.socket):
286
+ self.loop = loop
287
+ self.socket = socket
288
+ self.tport = None
289
+ self.proto = None
290
+
291
+ async def _connect(self) -> Tuple[asyncio.DatagramTransport, '_UdpProtocol']:
292
+ """
293
+ Establish UDP datagram endpoint used to send and receive data
294
+ """
295
+ if self.tport is None or self.proto is None:
296
+ self.tport, self.proto = await self.loop.create_datagram_endpoint(
297
+ _UdpProtocol, sock=self.socket)
298
+ return (self.tport, self.proto)
299
+
300
+ async def recvfrom(self) -> Tuple[bytes, RawAddr]:
301
+ """
302
+ Wait for message to be passed over datagram protocol queue
303
+ """
304
+ _, protocol = await self._connect()
305
+ message = await protocol.queue.get()
306
+ if isinstance(message, Exception):
307
+ raise message
308
+ return message
309
+
310
+ async def sendto(self, data: Bytes, addr: RawAddr) -> None:
311
+ """
312
+ Send message via datagram transport
313
+ """
314
+ transport, _ = await self._connect()
315
+ transport.sendto(data, addr)
316
+
317
+ def close(self):
318
+ """
319
+ Close transport and protocol
320
+ """
321
+ if self.tport is not None:
322
+ self.tport.close()
323
+
324
+ class _UdpProtocol(asyncio.DatagramProtocol):
325
+ """
326
+ DatagramProtocol implementation used for _UdpClientBackport
327
+ """
328
+ __slots__ = ('queue', 'closed', )
329
+
330
+ def __init__(self):
331
+ self.queue = asyncio.Queue()
332
+ self.closed = asyncio.Event()
333
+
334
+ def datagram_received(self, data: bytes, addr: RawAddr) -> None:
335
+ self.queue.put_nowait((data, addr))
336
+
337
+ def error_received(self, exc: Exception) -> None:
338
+ self.queue.put_nowait(exc)
339
+
340
+ def connection_lost(self, exc: Optional[Exception]) -> None:
341
+ self.closed.set()
342
+ if exc is not None:
343
+ self.queue.put_nowait(exc)
@@ -0,0 +1,38 @@
1
+ """
2
+ PyServe UnitTests
3
+ """
4
+ from typing import Optional, Union
5
+
6
+ from ..abc import Address, AsyncSession, Session, UdpWriter, Writer
7
+
8
+ #** Variables **#
9
+ __all__ = ['TransportTests', 'ThreadingTests', 'UtilTests']
10
+
11
+ #** Classes **#
12
+
13
+ class EchoSession(Session):
14
+ def connection_made(self, addr: Address, writer: Union[Writer, UdpWriter]):
15
+ self.addr = addr
16
+ self.writer = writer
17
+ def data_received(self, data: bytes):
18
+ self.writer.write(data)
19
+ if data == b'bye':
20
+ self.writer.close()
21
+ def connection_lost(self, err: Optional[Exception]):
22
+ pass
23
+
24
+ class AsyncEchoSession(AsyncSession):
25
+ async def connection_made(self, addr: Address, writer: Writer):
26
+ self.addr = addr
27
+ self.writer = writer
28
+ async def data_received(self, data: bytes):
29
+ self.writer.write(data)
30
+ if data == b'bye':
31
+ self.writer.close()
32
+ async def connection_lost(self, err: Optional[Exception]):
33
+ pass
34
+
35
+ #** Imports **#
36
+ from .transport import TransportTests
37
+ from .threading import ThreadingTests
38
+ from .utils import UtilTests