codecraftai-python-rpc 1.3.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.
- ccai/rpc/__init__.py +33 -0
- ccai/rpc/aspects.py +145 -0
- ccai/rpc/core/__init__.py +0 -0
- ccai/rpc/core/dispatch/__init__.py +0 -0
- ccai/rpc/core/dispatch/context.py +115 -0
- ccai/rpc/core/dispatch/lanes.py +77 -0
- ccai/rpc/core/flattenable.py +30 -0
- ccai/rpc/core/futures.py +168 -0
- ccai/rpc/core/leases.py +35 -0
- ccai/rpc/core/looper.py +107 -0
- ccai/rpc/core/looperpool.py +136 -0
- ccai/rpc/core/looperqueue.py +103 -0
- ccai/rpc/core/observability/__init__.py +10 -0
- ccai/rpc/core/observability/metrics.py +26 -0
- ccai/rpc/core/observability/state.py +51 -0
- ccai/rpc/core/protocol/__init__.py +16 -0
- ccai/rpc/core/protocol/constants.py +64 -0
- ccai/rpc/core/protocol/header.py +66 -0
- ccai/rpc/core/protocol/messages.py +265 -0
- ccai/rpc/core/proxy/__init__.py +0 -0
- ccai/rpc/core/proxy/cache.py +48 -0
- ccai/rpc/core/proxy/handlers.py +101 -0
- ccai/rpc/core/proxy/remoteproxy.py +251 -0
- ccai/rpc/core/proxy/table.py +207 -0
- ccai/rpc/core/proxy/wrappers.py +127 -0
- ccai/rpc/core/serialization/__init__.py +13 -0
- ccai/rpc/core/serialization/codec.py +371 -0
- ccai/rpc/core/serialization/placeholder.py +25 -0
- ccai/rpc/core/serialization/registry.py +85 -0
- ccai/rpc/core/serialization/tags.py +39 -0
- ccai/rpc/core/session/__init__.py +9 -0
- ccai/rpc/core/session/base.py +698 -0
- ccai/rpc/core/session/client.py +58 -0
- ccai/rpc/core/session/dispatch.py +124 -0
- ccai/rpc/core/session/heartbeat.py +96 -0
- ccai/rpc/core/session/server.py +68 -0
- ccai/rpc/core/transport/__init__.py +10 -0
- ccai/rpc/core/transport/base.py +91 -0
- ccai/rpc/core/transport/faults.py +81 -0
- ccai/rpc/core/transport/inprocess.py +22 -0
- ccai/rpc/core/transport/socketio.py +139 -0
- ccai/rpc/endpoints.py +44 -0
- ccai/rpc/errors.py +100 -0
- ccai/rpc/py.typed +0 -0
- ccai/rpc/rpcsocketclient.py +126 -0
- ccai/rpc/rpcsocketserver.py +226 -0
- ccai/rpc/security/__init__.py +10 -0
- ccai/rpc/security/auth.py +34 -0
- ccai/rpc/security/tls.py +53 -0
- codecraftai_python_rpc-1.3.0.dist-info/METADATA +105 -0
- codecraftai_python_rpc-1.3.0.dist-info/RECORD +53 -0
- codecraftai_python_rpc-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_python_rpc-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: messages
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The Message base class, the (type, code) registry and one class per request, reply and exception.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__author__ = "Myron Walker"
|
|
10
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
11
|
+
__credits__ = []
|
|
12
|
+
|
|
13
|
+
from typing import ClassVar, Dict, Optional, Tuple, Type
|
|
14
|
+
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from ccai.rpc.errors import ProtocolError
|
|
18
|
+
from ccai.rpc.core.protocol.constants import HEADER_SIZE, PROTOCOL_VERSION, ExceptionCode, MessageType, ReplyCode, RequestCode
|
|
19
|
+
from ccai.rpc.core.protocol.header import MessageHeader
|
|
20
|
+
from ccai.rpc.core.serialization import decode, encode
|
|
21
|
+
|
|
22
|
+
REGISTRY: Dict[Tuple[MessageType, int], Type["Message"]] = {}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Message:
|
|
26
|
+
"""
|
|
27
|
+
Base of every message. Subclasses declare ``mtype``, ``mcode`` and ``fields``; the payload is the
|
|
28
|
+
tuple of field values encoded by the serialization codec.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
mtype: ClassVar[MessageType]
|
|
32
|
+
mcode: ClassVar[int]
|
|
33
|
+
fields: ClassVar[Tuple[str, ...]] = ()
|
|
34
|
+
|
|
35
|
+
def __init__(self, *args, correlation_id: Optional[uuid.UUID] = None, version: int = PROTOCOL_VERSION, **kwargs) -> None:
|
|
36
|
+
if len(args) > len(self.fields):
|
|
37
|
+
raise TypeError("{} takes at most {} positional field values".format(type(self).__name__, len(self.fields)))
|
|
38
|
+
values = dict(zip(self.fields, args))
|
|
39
|
+
for name, value in kwargs.items():
|
|
40
|
+
if name not in self.fields:
|
|
41
|
+
raise TypeError("{} has no field '{}'".format(type(self).__name__, name))
|
|
42
|
+
values[name] = value
|
|
43
|
+
for name in self.fields:
|
|
44
|
+
setattr(self, name, values.get(name, self.default_for(name)))
|
|
45
|
+
self.correlation_id = correlation_id if correlation_id is not None else uuid.uuid4()
|
|
46
|
+
self.version = version
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def default_for(cls, name: str):
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
def field_values(self) -> tuple:
|
|
54
|
+
return tuple(getattr(self, name) for name in self.fields)
|
|
55
|
+
|
|
56
|
+
def pack(self, ref_encoder=None, known_lookup=None) -> bytes:
|
|
57
|
+
payload = encode(self.field_values(), ref_encoder=ref_encoder, known_lookup=known_lookup) if self.fields else b""
|
|
58
|
+
header = MessageHeader(self.version, self.mtype, int(self.mcode), self.correlation_id, len(payload))
|
|
59
|
+
return header.pack() + payload
|
|
60
|
+
|
|
61
|
+
@classmethod
|
|
62
|
+
def unpack(cls, data: bytes, resolver=None) -> "Message":
|
|
63
|
+
header = MessageHeader.unpack(data)
|
|
64
|
+
if header.payload_length != len(data) - HEADER_SIZE:
|
|
65
|
+
raise ProtocolError("header announces {} payload bytes but {} are present".format(header.payload_length, len(data) - HEADER_SIZE))
|
|
66
|
+
klass = REGISTRY.get((header.mtype, header.mcode))
|
|
67
|
+
if klass is None:
|
|
68
|
+
raise ProtocolError("unknown message type/code {}/{}".format(header.mtype.name, header.mcode))
|
|
69
|
+
payload = data[HEADER_SIZE:]
|
|
70
|
+
if klass.fields:
|
|
71
|
+
values = decode(payload, resolver=resolver)
|
|
72
|
+
if not isinstance(values, tuple) or len(values) != len(klass.fields):
|
|
73
|
+
raise ProtocolError("payload of {} does not match its {} fields".format(klass.__name__, len(klass.fields)))
|
|
74
|
+
kwargs = dict(zip(klass.fields, values))
|
|
75
|
+
else:
|
|
76
|
+
kwargs = {}
|
|
77
|
+
return klass(correlation_id=header.correlation_id, version=header.version, **kwargs)
|
|
78
|
+
|
|
79
|
+
def __eq__(self, other) -> bool:
|
|
80
|
+
return type(self) is type(other) and self.correlation_id == other.correlation_id and self.field_values() == other.field_values()
|
|
81
|
+
|
|
82
|
+
def __hash__(self) -> int:
|
|
83
|
+
return hash((type(self), self.correlation_id))
|
|
84
|
+
|
|
85
|
+
def __repr__(self) -> str:
|
|
86
|
+
pairs = ", ".join("{}={!r}".format(name, getattr(self, name)) for name in self.fields)
|
|
87
|
+
return "{}({})".format(type(self).__name__, pairs)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def message(mtype: MessageType, mcode: int):
|
|
91
|
+
def register(klass):
|
|
92
|
+
klass.mtype = mtype
|
|
93
|
+
klass.mcode = mcode
|
|
94
|
+
REGISTRY[(mtype, int(mcode))] = klass
|
|
95
|
+
return klass
|
|
96
|
+
return register
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------- requests
|
|
100
|
+
|
|
101
|
+
@message(MessageType.REQUEST, RequestCode.HELLO)
|
|
102
|
+
class RequestHello(Message):
|
|
103
|
+
fields = ("version_min", "version_max", "session_id", "credential", "context")
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def default_for(cls, name):
|
|
107
|
+
return {"version_min": PROTOCOL_VERSION, "version_max": PROTOCOL_VERSION, "credential": b"", "context": {}}.get(name)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@message(MessageType.REQUEST, RequestCode.PING)
|
|
111
|
+
class RequestPing(Message):
|
|
112
|
+
fields = ()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@message(MessageType.REQUEST, RequestCode.CLOSE)
|
|
116
|
+
class RequestClose(Message):
|
|
117
|
+
fields = ()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@message(MessageType.REQUEST, RequestCode.GETSERVICE)
|
|
121
|
+
class RequestGetService(Message):
|
|
122
|
+
fields = ()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@message(MessageType.REQUEST, RequestCode.GETATTR)
|
|
126
|
+
class RequestGetAttr(Message):
|
|
127
|
+
fields = ("target_ref", "name", "deadline", "context")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@message(MessageType.REQUEST, RequestCode.SETATTR)
|
|
131
|
+
class RequestSetAttr(Message):
|
|
132
|
+
fields = ("target_ref", "name", "value", "deadline", "context")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@message(MessageType.REQUEST, RequestCode.DELATTR)
|
|
136
|
+
class RequestDelAttr(Message):
|
|
137
|
+
fields = ("target_ref", "name", "deadline", "context")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@message(MessageType.REQUEST, RequestCode.CALL)
|
|
141
|
+
class RequestCall(Message):
|
|
142
|
+
fields = ("target_ref", "callable_name", "args", "kwargs", "deadline", "context", "notify")
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def default_for(cls, name):
|
|
146
|
+
return {"args": (), "kwargs": {}, "notify": False}.get(name)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@message(MessageType.REQUEST, RequestCode.RELEASE)
|
|
150
|
+
class RequestRelease(Message):
|
|
151
|
+
fields = ("ref_id",)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@message(MessageType.REQUEST, RequestCode.RENEW)
|
|
155
|
+
class RequestRenew(Message):
|
|
156
|
+
fields = ("ref_ids",)
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def default_for(cls, name):
|
|
160
|
+
return () if name == "ref_ids" else None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@message(MessageType.REQUEST, RequestCode.CANCEL)
|
|
164
|
+
class RequestCancel(Message):
|
|
165
|
+
fields = ("target_correlation_id",)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@message(MessageType.REQUEST, RequestCode.PROGRESS)
|
|
169
|
+
class RequestProgress(Message):
|
|
170
|
+
fields = ("target_correlation_id", "fraction", "message", "details")
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def default_for(cls, name):
|
|
174
|
+
return {} if name == "details" else None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---------------------------------------------------------------------------- replies
|
|
178
|
+
|
|
179
|
+
@message(MessageType.REPLY, ReplyCode.HELLO)
|
|
180
|
+
class ReplyHello(Message):
|
|
181
|
+
fields = ("chosen_version", "session_id", "lease_duration", "heartbeat_interval")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@message(MessageType.REPLY, ReplyCode.PING)
|
|
185
|
+
class ReplyPing(Message):
|
|
186
|
+
fields = ()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@message(MessageType.REPLY, ReplyCode.CLOSE)
|
|
190
|
+
class ReplyClose(Message):
|
|
191
|
+
fields = ()
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@message(MessageType.REPLY, ReplyCode.GETSERVICE)
|
|
195
|
+
class ReplyGetService(Message):
|
|
196
|
+
fields = ("value",)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@message(MessageType.REPLY, ReplyCode.GETATTR)
|
|
200
|
+
class ReplyGetAttr(Message):
|
|
201
|
+
fields = ("value",)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@message(MessageType.REPLY, ReplyCode.SETATTR)
|
|
205
|
+
class ReplySetAttr(Message):
|
|
206
|
+
fields = ()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@message(MessageType.REPLY, ReplyCode.DELATTR)
|
|
210
|
+
class ReplyDelAttr(Message):
|
|
211
|
+
fields = ()
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@message(MessageType.REPLY, ReplyCode.CALL)
|
|
215
|
+
class ReplyCall(Message):
|
|
216
|
+
fields = ("value",)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@message(MessageType.REPLY, ReplyCode.RELEASE)
|
|
220
|
+
class ReplyRelease(Message):
|
|
221
|
+
fields = ()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@message(MessageType.REPLY, ReplyCode.RENEW)
|
|
225
|
+
class ReplyRenew(Message):
|
|
226
|
+
fields = ("unknown",)
|
|
227
|
+
|
|
228
|
+
@classmethod
|
|
229
|
+
def default_for(cls, name):
|
|
230
|
+
return () if name == "unknown" else None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
@message(MessageType.REPLY, ReplyCode.CANCEL)
|
|
234
|
+
class ReplyCancel(Message):
|
|
235
|
+
fields = ()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@message(MessageType.REPLY, ReplyCode.PROGRESS)
|
|
239
|
+
class ReplyProgress(Message):
|
|
240
|
+
fields = ()
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ---------------------------------------------------------------------------- exceptions
|
|
244
|
+
|
|
245
|
+
@message(MessageType.EXCEPTION, 0)
|
|
246
|
+
class ExceptionMessage(Message):
|
|
247
|
+
fields = ("code", "type_name", "message", "traceback_text", "value")
|
|
248
|
+
|
|
249
|
+
@classmethod
|
|
250
|
+
def default_for(cls, name):
|
|
251
|
+
return {"code": int(ExceptionCode.REMOTE_EXCEPTION), "type_name": "", "message": "", "traceback_text": ""}.get(name)
|
|
252
|
+
|
|
253
|
+
@classmethod
|
|
254
|
+
def from_exception(cls, exc: BaseException, code: ExceptionCode = ExceptionCode.REMOTE_EXCEPTION,
|
|
255
|
+
correlation_id: Optional[uuid.UUID] = None) -> "ExceptionMessage":
|
|
256
|
+
import traceback as _tb
|
|
257
|
+
klass = type(exc)
|
|
258
|
+
tb = getattr(exc, "remote_traceback", None) or ("".join(_tb.format_exception(klass, exc, exc.__traceback__)) if exc.__traceback__ else "")
|
|
259
|
+
return cls(code=int(code), type_name="{}.{}".format(klass.__module__, klass.__qualname__), message=str(exc),
|
|
260
|
+
traceback_text=tb, value=exc, correlation_id=correlation_id)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
REPLY_FOR_REQUEST: Dict[int, Type[Message]] = {
|
|
264
|
+
int(RequestCode[name]): REGISTRY[(MessageType.REPLY, int(ReplyCode[name]))] for name in RequestCode.__members__
|
|
265
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: cache
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The holder-side proxy cache: one proxy per reference id per session, released when collected.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__author__ = "Myron Walker"
|
|
10
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
11
|
+
__credits__ = []
|
|
12
|
+
|
|
13
|
+
from typing import Dict, List
|
|
14
|
+
|
|
15
|
+
import threading
|
|
16
|
+
import uuid
|
|
17
|
+
import weakref
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ProxyCache:
|
|
21
|
+
|
|
22
|
+
def __init__(self) -> None:
|
|
23
|
+
self._lock = threading.Lock()
|
|
24
|
+
self._proxies: Dict[uuid.UUID, "weakref.ReferenceType"] = {}
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
def get(self, ref_id: uuid.UUID):
|
|
28
|
+
with self._lock:
|
|
29
|
+
ref = self._proxies.get(ref_id)
|
|
30
|
+
return ref() if ref is not None else None
|
|
31
|
+
|
|
32
|
+
def put(self, ref_id: uuid.UUID, proxy) -> None:
|
|
33
|
+
with self._lock:
|
|
34
|
+
self._proxies[ref_id] = weakref.ref(proxy)
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
def forget(self, ref_id: uuid.UUID) -> None:
|
|
38
|
+
with self._lock:
|
|
39
|
+
self._proxies.pop(ref_id, None)
|
|
40
|
+
return
|
|
41
|
+
|
|
42
|
+
def live_ids(self) -> List[uuid.UUID]:
|
|
43
|
+
with self._lock:
|
|
44
|
+
return [ref_id for ref_id, ref in self._proxies.items() if ref() is not None]
|
|
45
|
+
|
|
46
|
+
def live_proxies(self) -> list:
|
|
47
|
+
with self._lock:
|
|
48
|
+
return [ref() for ref in self._proxies.values() if ref() is not None]
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: handlers
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Owner-side handlers for get-service, attribute access and calls, with the attribute policy.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__author__ = "Myron Walker"
|
|
10
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
11
|
+
__credits__ = []
|
|
12
|
+
|
|
13
|
+
from ccai.rpc.errors import UnknownReferenceError
|
|
14
|
+
from ccai.rpc.core.protocol.constants import RequestCode
|
|
15
|
+
from ccai.rpc.core.protocol.messages import ReplyCall, ReplyDelAttr, ReplyGetAttr, ReplyGetService, ReplySetAttr
|
|
16
|
+
from ccai.rpc.core.proxy.remoteproxy import FORWARDED_DUNDERS
|
|
17
|
+
from ccai.rpc.core.proxy.table import ROOT_REFERENCE_ID
|
|
18
|
+
from ccai.rpc.core.proxy.wrappers import ByRef, EXPOSE_PRIVATE_MARKER, MUTABLE_SERVICE_MARKER, RemoteMethodDescriptor, is_by_ref_type
|
|
19
|
+
|
|
20
|
+
import inspect
|
|
21
|
+
from ccai.rpc.core.serialization.registry import flattenable_tag_for
|
|
22
|
+
|
|
23
|
+
_BY_VALUE_TYPES = (type(None), bool, int, float, str, bytes, list, tuple, dict, set, frozenset)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _check_attribute(obj, name: str, write: bool, ref_id) -> None:
|
|
27
|
+
if name.startswith("_") and name not in FORWARDED_DUNDERS and not getattr(type(obj), EXPOSE_PRIVATE_MARKER, False):
|
|
28
|
+
raise AttributeError("remote access to private attribute '{}' of {} is refused".format(name, type(obj).__name__))
|
|
29
|
+
if write and ref_id == ROOT_REFERENCE_ID and not getattr(type(obj), MUTABLE_SERVICE_MARKER, False):
|
|
30
|
+
raise AttributeError("remote writes to the root service object are refused; decorate the service with @mutable_service to allow them")
|
|
31
|
+
return
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _outbound(value):
|
|
35
|
+
"""
|
|
36
|
+
Values that cannot go by value are handed out by reference, so a returned object becomes a proxy.
|
|
37
|
+
"""
|
|
38
|
+
import datetime, enum, uuid
|
|
39
|
+
if isinstance(value, _BY_VALUE_TYPES + (datetime.datetime, datetime.date, datetime.timedelta, uuid.UUID, enum.Enum, BaseException)):
|
|
40
|
+
return value
|
|
41
|
+
if flattenable_tag_for(type(value)) is not None or isinstance(value, ByRef) or is_by_ref_type(value):
|
|
42
|
+
return value
|
|
43
|
+
from ccai.rpc.core.proxy.remoteproxy import RemoteProxy
|
|
44
|
+
if isinstance(value, RemoteProxy):
|
|
45
|
+
return value
|
|
46
|
+
return ByRef(value)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def handle_get_service(session, message, context):
|
|
50
|
+
if not session.table.has_root():
|
|
51
|
+
raise UnknownReferenceError("this session serves no root object")
|
|
52
|
+
return ReplyGetService(value=ByRef(session.table.resolve(ROOT_REFERENCE_ID)))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def handle_get_attr(session, message, context):
|
|
56
|
+
obj = session.table.resolve(message.target_ref, session.peer_session_id)
|
|
57
|
+
_check_attribute(obj, message.name, False, message.target_ref)
|
|
58
|
+
value = getattr(obj, message.name)
|
|
59
|
+
if inspect.ismethod(value) or inspect.isbuiltin(value) or (inspect.isfunction(value) and not hasattr(value, "flatten")):
|
|
60
|
+
return ReplyGetAttr(value=RemoteMethodDescriptor(message.name))
|
|
61
|
+
return ReplyGetAttr(value=_outbound(value))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def handle_set_attr(session, message, context):
|
|
65
|
+
obj = session.table.resolve(message.target_ref, session.peer_session_id)
|
|
66
|
+
_check_attribute(obj, message.name, True, message.target_ref)
|
|
67
|
+
setattr(obj, message.name, message.value)
|
|
68
|
+
return ReplySetAttr()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def handle_del_attr(session, message, context):
|
|
72
|
+
obj = session.table.resolve(message.target_ref, session.peer_session_id)
|
|
73
|
+
_check_attribute(obj, message.name, True, message.target_ref)
|
|
74
|
+
delattr(obj, message.name)
|
|
75
|
+
return ReplyDelAttr()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def handle_call(session, message, context):
|
|
79
|
+
obj = session.table.resolve(message.target_ref, session.peer_session_id)
|
|
80
|
+
name = message.callable_name
|
|
81
|
+
args = tuple(message.args or ())
|
|
82
|
+
kwargs = dict(message.kwargs or {})
|
|
83
|
+
if name == "__call__":
|
|
84
|
+
result = obj(*args, **kwargs)
|
|
85
|
+
elif name == "__rpc_iter__":
|
|
86
|
+
result = list(iter(obj))
|
|
87
|
+
else:
|
|
88
|
+
_check_attribute(obj, name, False, message.target_ref)
|
|
89
|
+
result = getattr(obj, name)(*args, **kwargs)
|
|
90
|
+
if message.notify:
|
|
91
|
+
return None
|
|
92
|
+
return ReplyCall(value=_outbound(result))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def install(session) -> None:
|
|
96
|
+
session.register_handler(RequestCode.GETSERVICE, handle_get_service)
|
|
97
|
+
session.register_handler(RequestCode.GETATTR, handle_get_attr)
|
|
98
|
+
session.register_handler(RequestCode.SETATTR, handle_set_attr)
|
|
99
|
+
session.register_handler(RequestCode.DELATTR, handle_del_attr)
|
|
100
|
+
session.register_handler(RequestCode.CALL, handle_call)
|
|
101
|
+
return
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: remoteproxy
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: RemoteProxy, the holder-side stand-in that forwards attribute access and calls to the owner.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__author__ = "Myron Walker"
|
|
10
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
11
|
+
__credits__ = []
|
|
12
|
+
|
|
13
|
+
from typing import Optional
|
|
14
|
+
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from ccai.rpc.errors import SessionClosedError
|
|
18
|
+
from ccai.rpc.core.protocol.messages import RequestCall, RequestDelAttr, RequestGetAttr, RequestSetAttr
|
|
19
|
+
from ccai.rpc.core.proxy.wrappers import ONEWAY_MARKER, RemoteMethodDescriptor
|
|
20
|
+
|
|
21
|
+
_OWN = ("_session", "_ref_id", "_owner_session_id", "_type_name", "_protocol", "_aspects", "_closed", "_is_view", "_expired", "_base", "_methods")
|
|
22
|
+
FORWARDED_DUNDERS = ("__len__", "__contains__", "__getitem__", "__setitem__", "__delitem__", "__enter__", "__exit__", "__call__", "__rpc_iter__")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _RemoteMethod:
|
|
26
|
+
"""
|
|
27
|
+
A bound remote callable. Calling it is exactly one round trip.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
__slots__ = ("_proxy", "_name")
|
|
31
|
+
|
|
32
|
+
def __init__(self, proxy: "RemoteProxy", name: str) -> None:
|
|
33
|
+
self._proxy = proxy
|
|
34
|
+
self._name = name
|
|
35
|
+
return
|
|
36
|
+
|
|
37
|
+
def __call__(self, *args, **kwargs):
|
|
38
|
+
if self._proxy._protocol is not None:
|
|
39
|
+
attr = getattr(self._proxy._protocol, self._name, None)
|
|
40
|
+
if attr is not None and getattr(attr, ONEWAY_MARKER, False):
|
|
41
|
+
self._proxy.rpc_notify(self._name, *args, **kwargs)
|
|
42
|
+
return None
|
|
43
|
+
return self._proxy._call(self._name, args, kwargs)
|
|
44
|
+
|
|
45
|
+
def rpc_notify(self, *args, **kwargs) -> None:
|
|
46
|
+
self._proxy.rpc_notify(self._name, *args, **kwargs)
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
def rpc_call_async(self, *args, **kwargs):
|
|
50
|
+
return self._proxy.rpc_call_async(self._name, *args, **kwargs)
|
|
51
|
+
|
|
52
|
+
def __repr__(self) -> str:
|
|
53
|
+
return "<remote method {}.{} via {}>".format(self._proxy._type_name, self._name, self._proxy._ref_id)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RemoteProxy:
|
|
57
|
+
"""
|
|
58
|
+
Forwards attribute get, set, delete and calls to the owning session as protocol requests. Its own
|
|
59
|
+
state is reachable through ``rpc_``-prefixed names so it cannot collide with the target's attributes.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
__slots__ = _OWN + ("__weakref__",)
|
|
63
|
+
__rpc_proxy__ = True
|
|
64
|
+
|
|
65
|
+
def __init__(self, session, ref_id: uuid.UUID, owner_session_id: uuid.UUID, type_name: str,
|
|
66
|
+
protocol: Optional[type] = None, aspects=None, is_view: bool = False, base: Optional["RemoteProxy"] = None) -> None:
|
|
67
|
+
object.__setattr__(self, "_session", session)
|
|
68
|
+
object.__setattr__(self, "_ref_id", ref_id)
|
|
69
|
+
object.__setattr__(self, "_owner_session_id", owner_session_id)
|
|
70
|
+
object.__setattr__(self, "_type_name", type_name)
|
|
71
|
+
object.__setattr__(self, "_protocol", protocol)
|
|
72
|
+
object.__setattr__(self, "_aspects", aspects)
|
|
73
|
+
object.__setattr__(self, "_closed", False)
|
|
74
|
+
object.__setattr__(self, "_is_view", is_view)
|
|
75
|
+
object.__setattr__(self, "_expired", False)
|
|
76
|
+
object.__setattr__(self, "_base", base) # a view keeps its base alive so the reference is not released under it
|
|
77
|
+
object.__setattr__(self, "_methods", {})
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
# ------------------------------------------------------------------ own surface
|
|
81
|
+
@property
|
|
82
|
+
def rpc_reference_id(self) -> uuid.UUID:
|
|
83
|
+
return self._ref_id
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def rpc_remote_type_name(self) -> str:
|
|
87
|
+
return self._type_name
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def rpc_session(self):
|
|
91
|
+
return self._session
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def rpc_owner_session_id(self) -> uuid.UUID:
|
|
95
|
+
return self._owner_session_id
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def rpc_closed(self) -> bool:
|
|
99
|
+
return self._closed
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def rpc_expired(self) -> bool:
|
|
103
|
+
return self._expired
|
|
104
|
+
|
|
105
|
+
def rpc_mark_closed(self) -> None:
|
|
106
|
+
object.__setattr__(self, "_closed", True)
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
def rpc_mark_expired(self) -> None:
|
|
110
|
+
object.__setattr__(self, "_expired", True)
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
def rpc_release(self) -> None:
|
|
114
|
+
"""
|
|
115
|
+
Releases the reference on the owner now rather than waiting for garbage collection.
|
|
116
|
+
"""
|
|
117
|
+
if not self._closed and not self._is_view:
|
|
118
|
+
self._session.release_reference(self._ref_id)
|
|
119
|
+
object.__setattr__(self, "_closed", True)
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
def rpc_with_aspects(self, aspects) -> "RemoteProxy":
|
|
123
|
+
return RemoteProxy(self._session, self._ref_id, self._owner_session_id, self._type_name, self._protocol, aspects, is_view=True, base=self._base or self)
|
|
124
|
+
|
|
125
|
+
def rpc_with_protocol(self, protocol: Optional[type]) -> "RemoteProxy":
|
|
126
|
+
return RemoteProxy(self._session, self._ref_id, self._owner_session_id, self._type_name, protocol, self._aspects, is_view=True, base=self._base or self)
|
|
127
|
+
|
|
128
|
+
def rpc_notify(self, name: str, *args, **kwargs) -> None:
|
|
129
|
+
self._check_usable()
|
|
130
|
+
self._session.send_notification(RequestCall(target_ref=self._ref_id, callable_name=name, args=tuple(args), kwargs=dict(kwargs),
|
|
131
|
+
deadline=None, context=self._session.request_context(), notify=True))
|
|
132
|
+
return
|
|
133
|
+
|
|
134
|
+
def rpc_call_async(self, name: str, *args, **kwargs):
|
|
135
|
+
self._check_usable()
|
|
136
|
+
aspects = self._session.resolve_aspects(self._aspects)
|
|
137
|
+
message = RequestCall(target_ref=self._ref_id, callable_name=name, args=tuple(args), kwargs=dict(kwargs),
|
|
138
|
+
deadline=aspects.completion_timeout, context=self._session.request_context())
|
|
139
|
+
return self._session.send_request_async(message, timeout=aspects.completion_timeout, unwrap=True)
|
|
140
|
+
|
|
141
|
+
# ------------------------------------------------------------------ forwarding
|
|
142
|
+
def _check_usable(self) -> None:
|
|
143
|
+
if self._base is not None and (self._base._closed or self._base._expired):
|
|
144
|
+
object.__setattr__(self, "_closed", self._base._closed)
|
|
145
|
+
object.__setattr__(self, "_expired", self._base._expired)
|
|
146
|
+
if self._closed or not self._session.is_running:
|
|
147
|
+
raise SessionClosedError("proxy for {} ({}) is no longer usable: the session is closed".format(self._type_name, self._ref_id))
|
|
148
|
+
if self._expired:
|
|
149
|
+
from ccai.rpc.errors import LeaseExpiredError
|
|
150
|
+
raise LeaseExpiredError("proxy for {} ({}) expired: the owner no longer holds the reference".format(self._type_name, self._ref_id))
|
|
151
|
+
return
|
|
152
|
+
|
|
153
|
+
def _request(self, message):
|
|
154
|
+
self._check_usable()
|
|
155
|
+
aspects = self._session.resolve_aspects(self._aspects)
|
|
156
|
+
message.deadline = aspects.completion_timeout
|
|
157
|
+
message.context = self._session.request_context()
|
|
158
|
+
return self._session.send_request(message, timeout=aspects.completion_timeout)
|
|
159
|
+
|
|
160
|
+
def _call(self, name: str, args: tuple, kwargs: dict):
|
|
161
|
+
reply = self._request(RequestCall(target_ref=self._ref_id, callable_name=name, args=tuple(args), kwargs=dict(kwargs)))
|
|
162
|
+
return reply.value
|
|
163
|
+
|
|
164
|
+
def _protocol_declares(self, name: str) -> bool:
|
|
165
|
+
if self._protocol is None:
|
|
166
|
+
return False
|
|
167
|
+
if hasattr(self._protocol, name):
|
|
168
|
+
return True
|
|
169
|
+
for klass in getattr(self._protocol, "__mro__", ()):
|
|
170
|
+
if name in getattr(klass, "__annotations__", {}):
|
|
171
|
+
return True
|
|
172
|
+
return False
|
|
173
|
+
|
|
174
|
+
def __getattr__(self, name: str):
|
|
175
|
+
if name.startswith("rpc_") or name in _OWN:
|
|
176
|
+
raise AttributeError(name)
|
|
177
|
+
if name.startswith("__") and name.endswith("__"):
|
|
178
|
+
raise AttributeError(name)
|
|
179
|
+
cached = self._methods.get(name)
|
|
180
|
+
if cached is not None:
|
|
181
|
+
return cached
|
|
182
|
+
if self._protocol is not None:
|
|
183
|
+
if not self._protocol_declares(name):
|
|
184
|
+
raise AttributeError("'{}' is not declared by the service protocol {}".format(name, self._protocol.__name__))
|
|
185
|
+
if callable(getattr(self._protocol, name, None)):
|
|
186
|
+
method = _RemoteMethod(self, name)
|
|
187
|
+
self._methods[name] = method
|
|
188
|
+
return method
|
|
189
|
+
reply = self._request(RequestGetAttr(target_ref=self._ref_id, name=name))
|
|
190
|
+
value = reply.value
|
|
191
|
+
if isinstance(value, RemoteMethodDescriptor):
|
|
192
|
+
method = _RemoteMethod(self, value.name)
|
|
193
|
+
self._methods[name] = method
|
|
194
|
+
return method
|
|
195
|
+
if isinstance(value, RemoteProxy) and self._aspects is not None:
|
|
196
|
+
value = value.rpc_with_aspects(self._aspects)
|
|
197
|
+
return value
|
|
198
|
+
|
|
199
|
+
def __setattr__(self, name: str, value) -> None:
|
|
200
|
+
if name in _OWN:
|
|
201
|
+
object.__setattr__(self, name, value)
|
|
202
|
+
return
|
|
203
|
+
self._request(RequestSetAttr(target_ref=self._ref_id, name=name, value=value))
|
|
204
|
+
return
|
|
205
|
+
|
|
206
|
+
def __delattr__(self, name: str) -> None:
|
|
207
|
+
self._request(RequestDelAttr(target_ref=self._ref_id, name=name))
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
def __call__(self, *args, **kwargs):
|
|
211
|
+
return self._call("__call__", args, kwargs)
|
|
212
|
+
|
|
213
|
+
def __len__(self) -> int:
|
|
214
|
+
return self._call("__len__", (), {})
|
|
215
|
+
|
|
216
|
+
def __iter__(self):
|
|
217
|
+
return iter(self._call("__rpc_iter__", (), {}))
|
|
218
|
+
|
|
219
|
+
def __contains__(self, item) -> bool:
|
|
220
|
+
return self._call("__contains__", (item,), {})
|
|
221
|
+
|
|
222
|
+
def __getitem__(self, key):
|
|
223
|
+
return self._call("__getitem__", (key,), {})
|
|
224
|
+
|
|
225
|
+
def __setitem__(self, key, value) -> None:
|
|
226
|
+
self._call("__setitem__", (key, value), {})
|
|
227
|
+
return
|
|
228
|
+
|
|
229
|
+
def __delitem__(self, key) -> None:
|
|
230
|
+
self._call("__delitem__", (key,), {})
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
def __enter__(self):
|
|
234
|
+
self._call("__enter__", (), {})
|
|
235
|
+
return self
|
|
236
|
+
|
|
237
|
+
def __exit__(self, exc_type, exc, tb):
|
|
238
|
+
return self._call("__exit__", (None, None, None), {})
|
|
239
|
+
|
|
240
|
+
def __bool__(self) -> bool:
|
|
241
|
+
return True
|
|
242
|
+
|
|
243
|
+
def __eq__(self, other) -> bool:
|
|
244
|
+
return isinstance(other, RemoteProxy) and other._ref_id == self._ref_id and other._owner_session_id == self._owner_session_id
|
|
245
|
+
|
|
246
|
+
def __hash__(self) -> int:
|
|
247
|
+
return hash((self._ref_id, self._owner_session_id))
|
|
248
|
+
|
|
249
|
+
def __repr__(self) -> str:
|
|
250
|
+
return "<RemoteProxy {} ref={} owner={}{}>".format(self._type_name, self._ref_id, self._owner_session_id,
|
|
251
|
+
" closed" if self._closed else "")
|