blissrpc 2.0.0__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.
blissrpc/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """
2
+ pythonic RPC implementation using simple rpc with msgpack.
3
+
4
+ Server example::
5
+
6
+ from blissrpc.server import Server
7
+
8
+ class Car:
9
+ '''A silly car. This doc should show up in the client'''
10
+
11
+ wheels = 4
12
+
13
+ def __init__(self, color, horsepower):
14
+ self.horsepower = horsepower
15
+ self.__position = 0
16
+
17
+ @property
18
+ def position(self):
19
+ '''this doc should show up in the client too'''
20
+ return self.__position
21
+
22
+ @staticmethod
23
+ def horsepower_to_watts(horsepower):
24
+ '''so should this'''
25
+ return horsepower * 735.499
26
+
27
+ @property
28
+ def watts(self):
29
+ '''also this one'''
30
+ return self.horsepower_to_watts(self.horsepower)
31
+
32
+ def move(self, value, relative=False):
33
+ '''needless to say this one as well'''
34
+ if relative:
35
+ self.__position += value
36
+ else:
37
+ self.__position = value
38
+
39
+ car = Car('yellow', 120)
40
+ server = Server(car)
41
+ server.bind('tcp://0:8989')
42
+ server.run()
43
+
44
+
45
+ Client::
46
+
47
+ from blissrpc.client import Client
48
+
49
+ car = Client('tcp://localhost:8989')
50
+
51
+ assert car.__doc__
52
+ assert type(car).__name__ == 'Car'
53
+ assert car.position == 0
54
+ assert car.horsepower == 120.0
55
+ assert car.horsepower_to_watts(1) == 735.499
56
+ assert car.watts == 120 * 735.499
57
+ car.move(12)
58
+ assert car.position == 12
59
+ car.move(10, relative=True)
60
+ assert car.position == 22
61
+
62
+ """
blissrpc/address.py ADDED
@@ -0,0 +1,53 @@
1
+ # This file is part of the bliss project
2
+ #
3
+ # Copyright (c) Beamline Control Unit, ESRF
4
+ # Distributed under the GNU LGPLv3. See LICENSE for more info.
5
+
6
+ import typing
7
+ from typing_extensions import TypedDict
8
+ import urllib.parse
9
+
10
+
11
+ class TcpAddress(TypedDict):
12
+ protocol: typing.Literal["tcp"]
13
+ host: str
14
+ port: int
15
+
16
+
17
+ class UdsAddress(TypedDict):
18
+ protocol: typing.Literal["uds"]
19
+ path: str
20
+
21
+
22
+ def parse_address(address: str) -> TcpAddress | UdsAddress:
23
+ """
24
+ Parse the client/server address.
25
+
26
+ Raises:
27
+ ValueError: when the address is not valid
28
+ """
29
+ url = urllib.parse.urlsplit(address)
30
+
31
+ if url.scheme == "tcp":
32
+ if url.path != "":
33
+ raise ValueError("Cannot manage this kind of url (%r)" % address)
34
+ host, port_str = url.netloc.split(":", 2)
35
+ port = int(port_str)
36
+ return dict(protocol="tcp", host=host, port=port)
37
+
38
+ elif url.scheme == "uds":
39
+ if url.netloc != "":
40
+ import socket
41
+
42
+ host = socket.gethostname()
43
+ if url.netloc != host:
44
+ raise ValueError(
45
+ f"Address '{address}' unusable from this host '{host}'"
46
+ )
47
+ return dict(protocol="uds", path=url.path)
48
+
49
+ elif url.scheme in ("inproc", "ipc"):
50
+ path = f"{url.netloc}{url.path}"
51
+ return dict(protocol="uds", path=path)
52
+
53
+ raise ValueError("Cannot manage this kind of url (%r)" % address)
File without changes
@@ -0,0 +1,294 @@
1
+ # This file is part of the bliss project
2
+ #
3
+ # Copyright (c) Beamline Control Unit, ESRF
4
+ # Distributed under the GNU LGPLv3. See LICENSE for more info.
5
+
6
+ import asyncio
7
+ import logging
8
+ import typing
9
+ from typing import Any
10
+ from collections.abc import Sequence
11
+ from typing_extensions import override, Buffer
12
+
13
+ from ..exceptions import RpcConnectionError, RpcProtocolError
14
+ from ..protocol import MessageType, Metadata
15
+ from .transport import ClientSocket
16
+ from ..address import parse_address
17
+ from ..options import Options
18
+ from ..base.base_client import BaseClient, ClientProtocol, NotificationCallback
19
+ from .protocol_adapter import ProtocolAdapter, WriteTransportWithWriter
20
+
21
+
22
+ _logger = logging.getLogger(__name__)
23
+
24
+
25
+ class WaitQueue:
26
+ def __init__(self, cnt: "Client", req_id: int):
27
+ self._cnt = cnt
28
+ self._event = asyncio.Event()
29
+ self._values: tuple[Any, BaseException | None] | None = None
30
+ self._req_id = req_id
31
+
32
+ def __enter__(self):
33
+ self._cnt._queues[self._req_id] = self
34
+ return self
35
+
36
+ def __exit__(self, *args):
37
+ del self._cnt._queues[self._req_id]
38
+
39
+ async def get(
40
+ self, timeout: float | None = None
41
+ ) -> tuple[Any, BaseException | None]:
42
+ await asyncio.wait_for(self._event.wait(), timeout=timeout)
43
+ assert self._values is not None
44
+ return self._values
45
+
46
+ def put(self, values: tuple[Any, BaseException | None]):
47
+ self._values = values
48
+ self._event.set()
49
+
50
+
51
+ class Client(BaseClient):
52
+ """
53
+ Create a python client to a remote object exposed at this `address`.
54
+
55
+ Arguments:
56
+ address: Address of the remote object
57
+ timeout: Timeout for the initial connection
58
+ """
59
+
60
+ def __init__(self, address: str, timeout=3.0, options: Options | None = None):
61
+ self._options = options or Options()
62
+ self._conn_factory = self._create_connection_factory(address)
63
+ self._lock = asyncio.Semaphore()
64
+ self._address = address
65
+ self._queues = dict[int, WaitQueue]()
66
+ self._timeout = timeout
67
+
68
+ self._notification_callbacks: dict[str, list[NotificationCallback]] = {}
69
+
70
+ self._transport: WriteTransportWithWriter | None = None
71
+ self._aio_protocol: ProtocolAdapter[ClientProtocol] | None = None
72
+ self._protocol: ClientProtocol | None = None
73
+
74
+ @property
75
+ def address(self) -> str:
76
+ return self._address
77
+
78
+ def _create_connection_factory(self, address: str) -> ClientSocket:
79
+ """Return the transport layer from an address."""
80
+ result = parse_address(address)
81
+ if result["protocol"] == "tcp":
82
+ from .transport_tcp import TcpClientSocket
83
+
84
+ return TcpClientSocket(result["host"], result["port"])
85
+ elif result["protocol"] == "uds":
86
+ from .transport_unix import UnixClientSocket
87
+
88
+ return UnixClientSocket(result["path"])
89
+ raise ValueError(f"Invalid address '{address}'")
90
+
91
+ def connect_notification(self, signal: str, callback: NotificationCallback):
92
+ cbs = self._notification_callbacks.setdefault(signal, [])
93
+ cbs.append(callback)
94
+
95
+ def disconnect_notification(self, signal: str, callback: NotificationCallback):
96
+ cbs = self._notification_callbacks[signal]
97
+ cbs.remove(callback)
98
+
99
+ async def connect(self):
100
+ """
101
+ Initialize the connection to the server.
102
+
103
+ Return when the connection is effective.
104
+
105
+ Raises:
106
+ RpcConnectionError: Error at the connection.
107
+ RpcProtocolError: If the protocol is not valid.
108
+ This exception derive from `RpcConnectionError`.
109
+ """
110
+ options = self._options
111
+
112
+ if self._transport is not None:
113
+ return
114
+ try:
115
+ self._transport, protocol = await self._conn_factory.connect_protocol(
116
+ self._protocol_factory
117
+ )
118
+ self._aio_protocol = typing.cast(ProtocolAdapter[ClientProtocol], protocol)
119
+ self._protocol = self._aio_protocol.protocol
120
+ except ConnectionRefusedError:
121
+ raise RpcConnectionError(f"Connection to {self._address} refused")
122
+
123
+ if options.enable_initial_connect:
124
+ try:
125
+ msg = await self.send_message(
126
+ MessageType.CONNECT, (), {}, timeout=options.connect_timeout
127
+ )
128
+ except asyncio.TimeoutError:
129
+ # This could not answer because the message was invalid and have fail
130
+ # at decoding or invalid and not dispatched at the right place.
131
+ try:
132
+ self.close()
133
+ except Exception:
134
+ # It's a clean up, ignore the exception
135
+ pass
136
+ raise RpcProtocolError(
137
+ "Timeout maybe because invalid protocol. Connection closed"
138
+ )
139
+ except Exception:
140
+ # It is suppsoed to be the very first message send by the client.
141
+ # In case of a connection to a wrong service, it could then raise
142
+ # any error including message which is not msgpack valid.
143
+ raise RpcProtocolError("Invalid protocol. Connection closed")
144
+
145
+ self._protocol.parse_connect_result(msg)
146
+
147
+ def _protocol_factory(self) -> asyncio.BufferedProtocol:
148
+ client_protocol = ClientProtocol(client=self, options=self._options)
149
+ sp = ProtocolAdapter[ClientProtocol](client_protocol)
150
+ return sp
151
+
152
+ async def get_class(self) -> type[Any] | None:
153
+ """
154
+ Get the class of the remote object.
155
+ """
156
+ return await self.send_message(MessageType.GET_CLASS, (), {})
157
+
158
+ async def get_metadata(self) -> Metadata:
159
+ """
160
+ Get the metadata of the remote object.
161
+ """
162
+ return await self.send_message(MessageType.INTROSPECT, (), {})
163
+
164
+ async def call(self, meth_name: str, *args, **kwargs) -> Any:
165
+ """
166
+ Call this `meth_name` method on the remote object.
167
+
168
+ Return the data returned from the remote call.
169
+ """
170
+ return await self.send_message(MessageType.CALL, (meth_name, *args), kwargs)
171
+
172
+ async def get_attr(self, attr_name: str) -> Any:
173
+ """
174
+ Get the value of the `attr_name` attribute/property from the remote object.
175
+ """
176
+ return await self.send_message(MessageType.GETATTR, (attr_name,), {})
177
+
178
+ async def set_attr(self, attr_name: str, value: Any):
179
+ """
180
+ Set the value of the `attr_name` attribute/property from the remote object.
181
+ """
182
+ return await self.send_message(MessageType.SETATTR, (attr_name, value), {})
183
+
184
+ async def del_attr(self, attr_name: str):
185
+ """
186
+ Delete the `attr_name` attribute/property of the remote object.
187
+ """
188
+ return await self.send_message(MessageType.DELATTR, (attr_name,), {})
189
+
190
+ async def send_message(
191
+ self,
192
+ code: MessageType,
193
+ args: Sequence[Any],
194
+ kwargs: dict[Any, Any],
195
+ retry_on_disconnect=True,
196
+ timeout: float | None = None,
197
+ ) -> Any:
198
+ """
199
+ Low level to send a message to the remote object.
200
+
201
+ Arguments:
202
+ code: Kind of request
203
+ args: Arguments
204
+ kwargs: Keyword arguments
205
+ """
206
+ _logger.debug(
207
+ "rpc client (%s): '%s' args=%s kwargs=%s", self._address, code, args, kwargs
208
+ )
209
+
210
+ if self._protocol is None:
211
+ await self.connect()
212
+
213
+ assert self._protocol is not None
214
+
215
+ req_id = self._protocol.new_req_id()
216
+ with WaitQueue(self, req_id) as w:
217
+ self._protocol.send_message(req_id, code, args, kwargs)
218
+ while True:
219
+ value, error = await w.get(timeout=timeout)
220
+
221
+ if error:
222
+ # FIXME: checking the traceback is an approximation
223
+ # It would be better to know it was a raised exception
224
+ # from the server msg
225
+ if isinstance(error, RpcConnectionError):
226
+ if retry_on_disconnect:
227
+ # try again once
228
+ await self.connect()
229
+ return await self.send_message(
230
+ code, args, kwargs, retry_on_disconnect=False
231
+ )
232
+ raise error
233
+ return value
234
+
235
+ @override
236
+ def _connection_made(self):
237
+ pass
238
+
239
+ @override
240
+ def _connection_lost(self):
241
+ for _, wq in self._queues.items():
242
+ wq.put((None, RpcConnectionError(f"Disconnected from {self._address}")))
243
+
244
+ @override
245
+ def _received_result(self, req_id: int, result: Any, error: BaseException | None):
246
+ wq = self._queues.get(req_id)
247
+ if wq:
248
+ wq.put((result, error))
249
+
250
+ @override
251
+ def _received_notification(self, signal: str, value: Any):
252
+ """
253
+ Receive a notification from the server.
254
+ """
255
+ cbs = self._notification_callbacks.get(signal)
256
+ if cbs:
257
+ for cb in cbs:
258
+ try:
259
+ cb(signal, value)
260
+ except Exception:
261
+ _logger.error(
262
+ "Error while handling signal %s from %s",
263
+ signal,
264
+ self._address,
265
+ exc_info=True,
266
+ )
267
+
268
+ @override
269
+ def _send_data(
270
+ self,
271
+ iter_data: typing.Generator[Buffer, None, None],
272
+ ):
273
+ transport = self._transport
274
+ if transport is None:
275
+ # Skip if the transport was closed
276
+ return
277
+
278
+ async def _send_data():
279
+ async with self._lock:
280
+ writer = transport.stream_writer
281
+ for data in iter_data:
282
+ if transport.is_closing():
283
+ return
284
+ writer.write(data) # type: ignore[arg-type]
285
+ await writer.drain()
286
+
287
+ asyncio.create_task(_send_data(), name="blissrpc-send-data")
288
+
289
+ def close(self):
290
+ if self._transport is not None:
291
+ self._transport.close()
292
+ self._transport = None
293
+ self._aio_protocol = None
294
+ self._protocol = None
@@ -0,0 +1,79 @@
1
+ # This file is part of the bliss project
2
+ #
3
+ # Copyright (c) Beamline Control Unit, ESRF
4
+ # Distributed under the GNU LGPLv3. See LICENSE for more info.
5
+
6
+ import abc
7
+ import asyncio
8
+ from asyncio.streams import FlowControlMixin
9
+ import typing
10
+
11
+ from typing_extensions import override
12
+ from ..base.base_protocol import BufferedProtocol, Transport
13
+
14
+
15
+ BUF = typing.TypeVar("BUF", bound=BufferedProtocol)
16
+
17
+
18
+ class WriteTransportWithWriter(Transport):
19
+ @property
20
+ @abc.abstractmethod
21
+ def stream_writer(self) -> asyncio.StreamWriter:
22
+ ...
23
+
24
+
25
+ class ProtocolAdapter(typing.Generic[BUF], asyncio.BufferedProtocol, FlowControlMixin):
26
+ """
27
+ Adapt the asyncio protocol to our agnostic protocol.
28
+
29
+ Inherite from FlowControlMixin to feature `drain` helper.
30
+ """
31
+
32
+ def __init__(self, protocol: BUF):
33
+ asyncio.BufferedProtocol.__init__(self)
34
+ FlowControlMixin.__init__(self)
35
+ self._protocol = protocol
36
+ self._writer: asyncio.StreamWriter | None = None
37
+
38
+ @property
39
+ def protocol(self) -> BUF:
40
+ return self._protocol
41
+
42
+ @property
43
+ def writer(self) -> asyncio.StreamWriter:
44
+ writer = self._writer
45
+ assert writer is not None
46
+ return writer
47
+
48
+ @override
49
+ def connection_made(self, transport):
50
+ asyncio.BufferedProtocol.connection_made(self, transport)
51
+ loop = asyncio.get_running_loop()
52
+ self._writer = asyncio.StreamWriter(
53
+ transport,
54
+ self,
55
+ None,
56
+ loop,
57
+ )
58
+ # Here we give a transport containing the extra writer.
59
+ # In the future it would be better to fully remove the
60
+ # transport from the protocol
61
+ transport.stream_writer = self._writer
62
+ self._protocol.connection_made(transport)
63
+
64
+ @override
65
+ def connection_lost(self, exc: Exception | None):
66
+ self._protocol.connection_lost(exc)
67
+ FlowControlMixin.connection_lost(self, exc)
68
+
69
+ @override
70
+ def get_buffer(self, sizehint):
71
+ return self._protocol.get_buffer(sizehint)
72
+
73
+ @override
74
+ def buffer_updated(self, nbytes: int):
75
+ self._protocol.buffer_updated(nbytes)
76
+
77
+ @override
78
+ def eof_received(self):
79
+ return self._protocol.eof_received()
@@ -0,0 +1,175 @@
1
+ # This file is part of the bliss project
2
+ #
3
+ # Copyright (c) Beamline Control Unit, ESRF
4
+ # Distributed under the GNU LGPLv3. See LICENSE for more info.
5
+
6
+ import time
7
+ import asyncio
8
+
9
+ from ..protocol import Metadata, MemberMetadata
10
+ from .client import Client
11
+
12
+
13
+ SPECIAL_METHODS = {
14
+ "__abstractmethods__",
15
+ "__new__",
16
+ "__init__",
17
+ "__del__",
18
+ "__class__",
19
+ "__dict__",
20
+ "__sizeof__",
21
+ "__weakref__",
22
+ "__metaclass__",
23
+ "__subclasshook__",
24
+ "__getattr__",
25
+ "__setattr__",
26
+ "__delattr__",
27
+ "__getattribute__",
28
+ "__instancecheck__",
29
+ "__subclasscheck__",
30
+ "__reduce__",
31
+ "__reduce_ex__",
32
+ "__getstate__",
33
+ "__setstate__",
34
+ "__slots__",
35
+ "__eq__",
36
+ "__ne__",
37
+ "__hash__",
38
+ }
39
+
40
+
41
+ class ProxyClient:
42
+ """
43
+ Create a python proxy to a remote object exposed at this `address`.
44
+
45
+ Arguments:
46
+ address: Address of the remote object
47
+ timeout: Timeout for the initial connection
48
+ """
49
+
50
+ def __init__(self, address: str, timeout=3.0):
51
+ self.__client = Client(address=address, timeout=timeout)
52
+ self.__metadata: Metadata | None = None
53
+ self.__connector = asyncio.create_task(
54
+ asyncio.wait_for(self.__connect(), timeout=timeout), name="blissrpc-connect"
55
+ )
56
+ self._rpc_connection = self.__client
57
+
58
+ @classmethod
59
+ async def create(cls, address: str, timeout=3.0) -> "ProxyClient":
60
+ """
61
+ Alternative constructor, without active wait
62
+ """
63
+ proxy = cls(address=address, timeout=timeout)
64
+ await proxy._ProxyClient__connector
65
+ return proxy
66
+
67
+ async def __connect(self):
68
+ await self.__client.connect()
69
+ self.__metadata = await self.__client.get_metadata()
70
+
71
+ def __active_wait_metadata(self) -> Metadata:
72
+ # Here we have to have an active wait infortunatly...
73
+ while self.__metadata is None:
74
+ time.sleep(0.1)
75
+ return self.__metadata
76
+
77
+ def __create_async_method(self, member: MemberMetadata):
78
+ name = member["name"]
79
+ doc = member["doc"]
80
+
81
+ async def method(*args, **kwargs):
82
+ return await self.__client.call(name, *args, **kwargs)
83
+
84
+ method.__name__ = name
85
+ method.__doc__ = doc
86
+ return method
87
+
88
+ def __create_async_property_getter(self, member: MemberMetadata):
89
+ name = member["name"]
90
+ doc = member["doc"]
91
+
92
+ async def aget():
93
+ return await self.__client.get_attr(name)
94
+
95
+ def fget():
96
+ return aget()
97
+
98
+ fget.__name__ = name
99
+ fget.__doc__ = doc
100
+ return fget
101
+
102
+ def __create_async_property(self, member: MemberMetadata):
103
+ """
104
+ This is not working
105
+ """
106
+ name = member["name"]
107
+ doc = member["doc"]
108
+
109
+ async def fget(self):
110
+ return await self.__client.get_attr(name)
111
+
112
+ async def fset(self, value):
113
+ return await self.__client.set_attr(name, value)
114
+
115
+ async def fdel(self):
116
+ return await self.__client.del_attr(name)
117
+
118
+ class AsyncPropertyDescriptor:
119
+ def __init__(self, name):
120
+ self.name = name
121
+
122
+ def __get__(self, instance, owner):
123
+ if instance is None:
124
+ return self
125
+ return fget(instance)
126
+
127
+ def __set__(self, instance, value):
128
+ """
129
+ This can't work because the following is syntactelly incorrect.
130
+
131
+ .. code-block::
132
+
133
+ await obj.attr = 10
134
+ """
135
+ return fset(instance, value)
136
+
137
+ def __delete__(self, instance):
138
+ """
139
+ This can't work because the following is syntactelly incorrect.
140
+
141
+ .. code-block::
142
+
143
+ await del obj.attr
144
+ """
145
+ return fdel(instance)
146
+
147
+ # return AsyncPropertyDescriptor(name)
148
+
149
+ # return PropertyDescriptor()
150
+
151
+ # return property(fget=fget, fset=fset, fdel=fdel, doc=doc)
152
+
153
+ return property(fget=fget, doc=doc)
154
+
155
+ def __getattr__(self, name: str):
156
+ metadata = self.__active_wait_metadata()
157
+ if name in SPECIAL_METHODS:
158
+ raise AttributeError(f"Unsupported attribute '{name}'")
159
+ member = metadata["members"].get(name)
160
+ if member is None:
161
+ raise AttributeError(f"Unsupported attribute '{name}'")
162
+
163
+ mtype = member["type"]
164
+ if mtype == "method":
165
+ attr = self.__create_async_method(member)
166
+ # cache it
167
+ setattr(self, name, attr)
168
+ elif mtype == "attribute":
169
+ attr = self.__create_async_property_getter(member)()
170
+ # elif mtype == "staticmethod":
171
+ # elif mtype == "classmethod":
172
+ else:
173
+ raise AttributeError(f"Unsupported member type '{mtype}'")
174
+
175
+ return attr