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,371 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: codec
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The tagged binary codec: a closed set of by-value types, registered user types, exceptions and
|
|
5
|
+
reference placeholders. No decode path executes code.
|
|
6
|
+
|
|
7
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__author__ = "Myron Walker"
|
|
11
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
12
|
+
__credits__ = []
|
|
13
|
+
|
|
14
|
+
from typing import Callable, Optional
|
|
15
|
+
|
|
16
|
+
import builtins
|
|
17
|
+
import datetime
|
|
18
|
+
import enum
|
|
19
|
+
import struct
|
|
20
|
+
import sys
|
|
21
|
+
import traceback
|
|
22
|
+
import uuid
|
|
23
|
+
|
|
24
|
+
import ccai.errors.exceptions as _ccai_exceptions
|
|
25
|
+
|
|
26
|
+
from ccai.rpc.errors import RemoteError, SerializationError
|
|
27
|
+
from ccai.rpc.core.proxy.wrappers import PROXY_MARKER, ByRef, ByValue, is_by_ref_type
|
|
28
|
+
from ccai.rpc.core.serialization.placeholder import ReferencePlaceholder
|
|
29
|
+
from ccai.rpc.core.serialization.tags import FORMAT_VERSION, MAX_DEPTH, Tag
|
|
30
|
+
from ccai.rpc.core.serialization import registry
|
|
31
|
+
|
|
32
|
+
ReferenceEncoder = Callable[[object], Optional[ReferencePlaceholder]]
|
|
33
|
+
ReferenceResolver = Callable[[ReferencePlaceholder], object]
|
|
34
|
+
|
|
35
|
+
# Exception types are resolved only from modules already loaded in this process; decoding never imports.
|
|
36
|
+
_PRELOADED_EXCEPTION_MODULES = {"builtins": builtins, "ccai.errors.exceptions": _ccai_exceptions}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _write_varint(out: bytearray, value: int) -> None:
|
|
40
|
+
if value < 0:
|
|
41
|
+
raise SerializationError("varint cannot be negative")
|
|
42
|
+
while True:
|
|
43
|
+
byte = value & 0x7F
|
|
44
|
+
value >>= 7
|
|
45
|
+
if value:
|
|
46
|
+
out.append(byte | 0x80)
|
|
47
|
+
else:
|
|
48
|
+
out.append(byte)
|
|
49
|
+
return
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _read_varint(data: bytes, pos: int):
|
|
53
|
+
shift = 0
|
|
54
|
+
result = 0
|
|
55
|
+
while True:
|
|
56
|
+
if pos >= len(data):
|
|
57
|
+
raise SerializationError("truncated varint")
|
|
58
|
+
byte = data[pos]
|
|
59
|
+
pos += 1
|
|
60
|
+
result |= (byte & 0x7F) << shift
|
|
61
|
+
if not (byte & 0x80):
|
|
62
|
+
return result, pos
|
|
63
|
+
shift += 7
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _zigzag(value: int) -> int:
|
|
67
|
+
return (value << 1) if value >= 0 else ((-value << 1) - 1)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _unzigzag(value: int) -> int:
|
|
71
|
+
return (value >> 1) if not (value & 1) else -((value + 1) >> 1)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Encoder:
|
|
75
|
+
|
|
76
|
+
def __init__(self, ref_encoder: Optional[ReferenceEncoder] = None, known_lookup: Optional[ReferenceEncoder] = None) -> None:
|
|
77
|
+
self._ref_encoder = ref_encoder
|
|
78
|
+
self._known_lookup = known_lookup
|
|
79
|
+
self._out = bytearray()
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
def encode(self, value: object) -> bytes:
|
|
83
|
+
self._out = bytearray([FORMAT_VERSION])
|
|
84
|
+
self._encode(value, 0, "value")
|
|
85
|
+
return bytes(self._out)
|
|
86
|
+
|
|
87
|
+
def _tag(self, tag: Tag) -> None:
|
|
88
|
+
self._out.append(int(tag))
|
|
89
|
+
return
|
|
90
|
+
|
|
91
|
+
def _bytes(self, raw: bytes) -> None:
|
|
92
|
+
_write_varint(self._out, len(raw))
|
|
93
|
+
self._out.extend(raw)
|
|
94
|
+
return
|
|
95
|
+
|
|
96
|
+
def _str(self, text: str) -> None:
|
|
97
|
+
self._bytes(text.encode("utf-8"))
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
def _encode(self, value: object, depth: int, path: str) -> None:
|
|
101
|
+
if depth > MAX_DEPTH:
|
|
102
|
+
raise SerializationError("value nesting exceeds the depth limit of {} at {}".format(MAX_DEPTH, path))
|
|
103
|
+
out = self._out
|
|
104
|
+
if value is None:
|
|
105
|
+
self._tag(Tag.NONE)
|
|
106
|
+
elif value is True:
|
|
107
|
+
self._tag(Tag.TRUE)
|
|
108
|
+
elif value is False:
|
|
109
|
+
self._tag(Tag.FALSE)
|
|
110
|
+
elif isinstance(value, int) and not isinstance(value, enum.Enum):
|
|
111
|
+
self._tag(Tag.INT)
|
|
112
|
+
_write_varint(out, _zigzag(value))
|
|
113
|
+
elif isinstance(value, float):
|
|
114
|
+
self._tag(Tag.FLOAT)
|
|
115
|
+
out.extend(struct.pack("!d", value))
|
|
116
|
+
elif isinstance(value, str):
|
|
117
|
+
self._tag(Tag.STR)
|
|
118
|
+
self._str(value)
|
|
119
|
+
elif isinstance(value, (bytes, bytearray, memoryview)):
|
|
120
|
+
self._tag(Tag.BYTES)
|
|
121
|
+
self._bytes(bytes(value))
|
|
122
|
+
elif isinstance(value, ByValue):
|
|
123
|
+
self._encode(value.instance, depth, path)
|
|
124
|
+
elif isinstance(value, ByRef) or is_by_ref_type(value) or getattr(type(value), PROXY_MARKER, False):
|
|
125
|
+
self._reference(value.instance if isinstance(value, ByRef) else value, path)
|
|
126
|
+
elif isinstance(value, enum.Enum):
|
|
127
|
+
tag = registry.enum_tag_for(type(value))
|
|
128
|
+
if tag is None:
|
|
129
|
+
raise SerializationError("enum type '{}' is not registered (at {})".format(type(value).__name__, path))
|
|
130
|
+
self._tag(Tag.ENUM)
|
|
131
|
+
self._str(tag)
|
|
132
|
+
self._str(value.name)
|
|
133
|
+
elif isinstance(value, (list, tuple, set, frozenset)):
|
|
134
|
+
tag = {list: Tag.LIST, tuple: Tag.TUPLE, set: Tag.SET, frozenset: Tag.FROZENSET}[type(value) if type(value) in (list, tuple, set, frozenset) else (list if isinstance(value, list) else tuple if isinstance(value, tuple) else set if isinstance(value, set) else frozenset)]
|
|
135
|
+
self._tag(tag)
|
|
136
|
+
items = list(value)
|
|
137
|
+
_write_varint(out, len(items))
|
|
138
|
+
for index, item in enumerate(items):
|
|
139
|
+
self._encode(item, depth + 1, "{}[{}]".format(path, index))
|
|
140
|
+
elif isinstance(value, dict):
|
|
141
|
+
self._tag(Tag.DICT)
|
|
142
|
+
_write_varint(out, len(value))
|
|
143
|
+
for key, item in value.items():
|
|
144
|
+
if not isinstance(key, str):
|
|
145
|
+
raise SerializationError("dict keys must be str, got {} (at {})".format(type(key).__name__, path))
|
|
146
|
+
self._str(key)
|
|
147
|
+
self._encode(item, depth + 1, "{}.{}".format(path, key))
|
|
148
|
+
elif isinstance(value, datetime.datetime):
|
|
149
|
+
if value.tzinfo is None:
|
|
150
|
+
raise SerializationError("naive datetime values are not allowed on the wire (at {})".format(path))
|
|
151
|
+
self._tag(Tag.DATETIME)
|
|
152
|
+
self._str(value.isoformat())
|
|
153
|
+
elif isinstance(value, datetime.date):
|
|
154
|
+
self._tag(Tag.DATE)
|
|
155
|
+
self._str(value.isoformat())
|
|
156
|
+
elif isinstance(value, datetime.timedelta):
|
|
157
|
+
self._tag(Tag.TIMEDELTA)
|
|
158
|
+
out.extend(struct.pack("!d", value.total_seconds()))
|
|
159
|
+
elif isinstance(value, uuid.UUID):
|
|
160
|
+
self._tag(Tag.UUID)
|
|
161
|
+
out.extend(value.bytes)
|
|
162
|
+
elif isinstance(value, ReferencePlaceholder):
|
|
163
|
+
self._placeholder(value)
|
|
164
|
+
elif isinstance(value, BaseException):
|
|
165
|
+
self._exception(value, depth, path)
|
|
166
|
+
else:
|
|
167
|
+
tag = registry.flattenable_tag_for(type(value))
|
|
168
|
+
if tag is not None:
|
|
169
|
+
self._tag(Tag.FLATTENABLE)
|
|
170
|
+
self._str(tag)
|
|
171
|
+
flat = value.flatten()
|
|
172
|
+
self._encode(flat, depth + 1, "{}<{}>".format(path, tag))
|
|
173
|
+
elif self._known_lookup is not None and self._known_lookup(value) is not None:
|
|
174
|
+
# an object this session already handed out by reference travels as that reference
|
|
175
|
+
self._placeholder(self._known_lookup(value))
|
|
176
|
+
else:
|
|
177
|
+
raise SerializationError(
|
|
178
|
+
"type '{}' cannot be sent by value; wrap it as ByRef or ByValue, or register it (at {})".format(
|
|
179
|
+
type(value).__name__, path))
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
def _reference(self, obj: object, path: str) -> None:
|
|
183
|
+
if self._ref_encoder is None:
|
|
184
|
+
raise SerializationError("a by-reference object cannot be encoded outside a session (at {})".format(path))
|
|
185
|
+
placeholder = self._ref_encoder(obj)
|
|
186
|
+
if placeholder is None:
|
|
187
|
+
raise SerializationError("the session declined to create a reference for '{}' (at {})".format(type(obj).__name__, path))
|
|
188
|
+
self._placeholder(placeholder)
|
|
189
|
+
return
|
|
190
|
+
|
|
191
|
+
def _placeholder(self, placeholder: ReferencePlaceholder) -> None:
|
|
192
|
+
self._tag(Tag.REFERENCE)
|
|
193
|
+
self._out.extend(placeholder.ref_id.bytes)
|
|
194
|
+
self._out.extend(placeholder.session_id.bytes)
|
|
195
|
+
self._str(placeholder.type_name)
|
|
196
|
+
return
|
|
197
|
+
|
|
198
|
+
def _exception(self, exc: BaseException, depth: int, path: str) -> None:
|
|
199
|
+
self._tag(Tag.EXCEPTION)
|
|
200
|
+
cls = type(exc)
|
|
201
|
+
self._str("{}.{}".format(cls.__module__, cls.__qualname__))
|
|
202
|
+
self._str(str(exc))
|
|
203
|
+
try:
|
|
204
|
+
probe = Encoder(self._ref_encoder)
|
|
205
|
+
probe._encode(tuple(exc.args), depth + 1, path + ".args")
|
|
206
|
+
args_bytes = bytes(probe._out)
|
|
207
|
+
except SerializationError:
|
|
208
|
+
args_bytes = b""
|
|
209
|
+
self._bytes(args_bytes)
|
|
210
|
+
tb = getattr(exc, "remote_traceback", None)
|
|
211
|
+
if not tb:
|
|
212
|
+
tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) if exc.__traceback__ else ""
|
|
213
|
+
self._str(tb)
|
|
214
|
+
return
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Decoder:
|
|
218
|
+
|
|
219
|
+
def __init__(self, data: bytes, resolver: Optional[ReferenceResolver] = None) -> None:
|
|
220
|
+
self._data = data
|
|
221
|
+
self._pos = 0
|
|
222
|
+
self._resolver = resolver
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
def decode(self) -> object:
|
|
226
|
+
if len(self._data) == 0:
|
|
227
|
+
raise SerializationError("empty payload")
|
|
228
|
+
version = self._data[0]
|
|
229
|
+
if version != FORMAT_VERSION:
|
|
230
|
+
raise SerializationError("unknown serialization format version {}".format(version))
|
|
231
|
+
self._pos = 1
|
|
232
|
+
value = self._value(0)
|
|
233
|
+
if self._pos != len(self._data):
|
|
234
|
+
raise SerializationError("trailing bytes after value")
|
|
235
|
+
return value
|
|
236
|
+
|
|
237
|
+
def _take(self, count: int) -> bytes:
|
|
238
|
+
if self._pos + count > len(self._data):
|
|
239
|
+
raise SerializationError("truncated payload")
|
|
240
|
+
chunk = self._data[self._pos:self._pos + count]
|
|
241
|
+
self._pos += count
|
|
242
|
+
return chunk
|
|
243
|
+
|
|
244
|
+
def _varint(self) -> int:
|
|
245
|
+
value, self._pos = _read_varint(self._data, self._pos)
|
|
246
|
+
return value
|
|
247
|
+
|
|
248
|
+
def _bytes(self) -> bytes:
|
|
249
|
+
return self._take(self._varint())
|
|
250
|
+
|
|
251
|
+
def _str(self) -> str:
|
|
252
|
+
return self._bytes().decode("utf-8")
|
|
253
|
+
|
|
254
|
+
def _value(self, depth: int) -> object:
|
|
255
|
+
if depth > MAX_DEPTH:
|
|
256
|
+
raise SerializationError("value nesting exceeds the depth limit of {}".format(MAX_DEPTH))
|
|
257
|
+
raw_tag = self._take(1)[0]
|
|
258
|
+
try:
|
|
259
|
+
tag = Tag(raw_tag)
|
|
260
|
+
except ValueError:
|
|
261
|
+
raise SerializationError("unknown value tag {}".format(raw_tag)) from None
|
|
262
|
+
if tag == Tag.NONE:
|
|
263
|
+
return None
|
|
264
|
+
if tag == Tag.TRUE:
|
|
265
|
+
return True
|
|
266
|
+
if tag == Tag.FALSE:
|
|
267
|
+
return False
|
|
268
|
+
if tag == Tag.INT:
|
|
269
|
+
return _unzigzag(self._varint())
|
|
270
|
+
if tag == Tag.FLOAT:
|
|
271
|
+
return struct.unpack("!d", self._take(8))[0]
|
|
272
|
+
if tag == Tag.STR:
|
|
273
|
+
return self._str()
|
|
274
|
+
if tag == Tag.BYTES:
|
|
275
|
+
return self._bytes()
|
|
276
|
+
if tag in (Tag.LIST, Tag.TUPLE, Tag.SET, Tag.FROZENSET):
|
|
277
|
+
count = self._varint()
|
|
278
|
+
items = [self._value(depth + 1) for _ in range(count)]
|
|
279
|
+
return {Tag.LIST: list, Tag.TUPLE: tuple, Tag.SET: set, Tag.FROZENSET: frozenset}[tag](items)
|
|
280
|
+
if tag == Tag.DICT:
|
|
281
|
+
count = self._varint()
|
|
282
|
+
result = {}
|
|
283
|
+
for _ in range(count):
|
|
284
|
+
key = self._str()
|
|
285
|
+
result[key] = self._value(depth + 1)
|
|
286
|
+
return result
|
|
287
|
+
if tag == Tag.DATETIME:
|
|
288
|
+
return datetime.datetime.fromisoformat(self._str())
|
|
289
|
+
if tag == Tag.DATE:
|
|
290
|
+
return datetime.date.fromisoformat(self._str())
|
|
291
|
+
if tag == Tag.TIMEDELTA:
|
|
292
|
+
return datetime.timedelta(seconds=struct.unpack("!d", self._take(8))[0])
|
|
293
|
+
if tag == Tag.UUID:
|
|
294
|
+
return uuid.UUID(bytes=self._take(16))
|
|
295
|
+
if tag == Tag.ENUM:
|
|
296
|
+
enum_tag = self._str()
|
|
297
|
+
member = self._str()
|
|
298
|
+
cls = registry.enum_for_tag(enum_tag)
|
|
299
|
+
if cls is None:
|
|
300
|
+
raise SerializationError("enum tag '{}' is not registered".format(enum_tag))
|
|
301
|
+
return cls[member]
|
|
302
|
+
if tag == Tag.FLATTENABLE:
|
|
303
|
+
flat_tag = self._str()
|
|
304
|
+
cls = registry.flattenable_for_tag(flat_tag)
|
|
305
|
+
if cls is None:
|
|
306
|
+
raise SerializationError("flattenable tag '{}' is not registered".format(flat_tag))
|
|
307
|
+
data = self._value(depth + 1)
|
|
308
|
+
return cls.unflatten(data)
|
|
309
|
+
if tag == Tag.EXCEPTION:
|
|
310
|
+
return self._exception()
|
|
311
|
+
if tag == Tag.REFERENCE:
|
|
312
|
+
ref_id = uuid.UUID(bytes=self._take(16))
|
|
313
|
+
session_id = uuid.UUID(bytes=self._take(16))
|
|
314
|
+
type_name = self._str()
|
|
315
|
+
placeholder = ReferencePlaceholder(ref_id, session_id, type_name)
|
|
316
|
+
if self._resolver is None:
|
|
317
|
+
raise SerializationError("a reference placeholder cannot be decoded without a resolver")
|
|
318
|
+
return self._resolver(placeholder)
|
|
319
|
+
raise SerializationError("unhandled value tag {}".format(tag))
|
|
320
|
+
|
|
321
|
+
def _exception(self) -> BaseException:
|
|
322
|
+
type_name = self._str()
|
|
323
|
+
message = self._str()
|
|
324
|
+
args_bytes = self._bytes()
|
|
325
|
+
tb_text = self._str()
|
|
326
|
+
exc = _build_exception(type_name, message, args_bytes, tb_text, self._resolver)
|
|
327
|
+
return exc
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _resolve_exception_type(type_name: str):
|
|
331
|
+
module_name, _, qualname = type_name.rpartition(".")
|
|
332
|
+
module = _PRELOADED_EXCEPTION_MODULES.get(module_name) or sys.modules.get(module_name)
|
|
333
|
+
if module is None:
|
|
334
|
+
return None
|
|
335
|
+
obj = module
|
|
336
|
+
for part in qualname.split("."):
|
|
337
|
+
obj = getattr(obj, part, None)
|
|
338
|
+
if obj is None:
|
|
339
|
+
return None
|
|
340
|
+
if isinstance(obj, type) and issubclass(obj, BaseException):
|
|
341
|
+
return obj
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _build_exception(type_name: str, message: str, args_bytes: bytes, tb_text: str, resolver) -> BaseException:
|
|
346
|
+
cls = _resolve_exception_type(type_name)
|
|
347
|
+
exc = None
|
|
348
|
+
if cls is not None:
|
|
349
|
+
try:
|
|
350
|
+
exc = cls(message)
|
|
351
|
+
except Exception:
|
|
352
|
+
exc = None
|
|
353
|
+
if exc is None:
|
|
354
|
+
exc = RemoteError(message, remote_type_name=type_name, remote_traceback=tb_text)
|
|
355
|
+
else:
|
|
356
|
+
try:
|
|
357
|
+
exc.remote_traceback = tb_text
|
|
358
|
+
exc.remote_type_name = type_name
|
|
359
|
+
except Exception:
|
|
360
|
+
# Best-effort annotation; some exception types reject new attributes, and the rebuilt
|
|
361
|
+
# exception is still the correct error to surface without the remote details attached.
|
|
362
|
+
pass
|
|
363
|
+
return exc
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def encode(value: object, ref_encoder: Optional[ReferenceEncoder] = None, known_lookup: Optional[ReferenceEncoder] = None) -> bytes:
|
|
367
|
+
return Encoder(ref_encoder, known_lookup).encode(value)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def decode(data: bytes, resolver: Optional[ReferenceResolver] = None) -> object:
|
|
371
|
+
return Decoder(data, resolver).decode()
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: placeholder
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The encoded stand-in for an object passed by reference.
|
|
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 dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class ReferencePlaceholder:
|
|
20
|
+
"""
|
|
21
|
+
Travels in place of a ByRef object: the reference id, the owning session id and the type name.
|
|
22
|
+
"""
|
|
23
|
+
ref_id: uuid.UUID
|
|
24
|
+
session_id: uuid.UUID
|
|
25
|
+
type_name: str
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: registry
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The table of user types the codec may encode: enums, Flattenable classes and dataclasses.
|
|
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, Type
|
|
14
|
+
|
|
15
|
+
import dataclasses
|
|
16
|
+
import enum
|
|
17
|
+
import threading
|
|
18
|
+
|
|
19
|
+
from ccai.rpc.errors import SerializationError
|
|
20
|
+
|
|
21
|
+
_lock = threading.Lock()
|
|
22
|
+
_enums_by_tag: Dict[str, Type[enum.Enum]] = {}
|
|
23
|
+
_enum_tags: Dict[Type[enum.Enum], str] = {}
|
|
24
|
+
_flattenables_by_tag: Dict[str, type] = {}
|
|
25
|
+
_flattenable_tags: Dict[type, str] = {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def register_enum(tag: str, cls: Type[enum.Enum]) -> None:
|
|
29
|
+
if not (isinstance(cls, type) and issubclass(cls, enum.Enum)):
|
|
30
|
+
raise SerializationError("register_enum expects an Enum subclass, got {!r}".format(cls))
|
|
31
|
+
with _lock:
|
|
32
|
+
_enums_by_tag[tag] = cls
|
|
33
|
+
_enum_tags[cls] = tag
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def register_flattenable(tag: str, cls: type) -> None:
|
|
38
|
+
if not (hasattr(cls, "flatten") and hasattr(cls, "unflatten")):
|
|
39
|
+
raise SerializationError("register_flattenable expects a class with 'flatten' and 'unflatten', got {!r}".format(cls))
|
|
40
|
+
with _lock:
|
|
41
|
+
_flattenables_by_tag[tag] = cls
|
|
42
|
+
_flattenable_tags[cls] = tag
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def register_dataclass(tag: str, cls: type) -> None:
|
|
47
|
+
"""
|
|
48
|
+
Generates ``flatten`` and ``unflatten`` for a dataclass whose fields are by-value types.
|
|
49
|
+
"""
|
|
50
|
+
if not dataclasses.is_dataclass(cls):
|
|
51
|
+
raise SerializationError("register_dataclass expects a dataclass, got {!r}".format(cls))
|
|
52
|
+
names = [f.name for f in dataclasses.fields(cls)]
|
|
53
|
+
|
|
54
|
+
def flatten(self) -> dict:
|
|
55
|
+
return {name: getattr(self, name) for name in names}
|
|
56
|
+
|
|
57
|
+
def unflatten(klass, data: dict):
|
|
58
|
+
return klass(**data)
|
|
59
|
+
|
|
60
|
+
if not hasattr(cls, "flatten"):
|
|
61
|
+
cls.flatten = flatten
|
|
62
|
+
if not hasattr(cls, "unflatten"):
|
|
63
|
+
cls.unflatten = classmethod(unflatten)
|
|
64
|
+
register_flattenable(tag, cls)
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def enum_tag_for(cls: type):
|
|
69
|
+
return _enum_tags.get(cls)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def enum_for_tag(tag: str):
|
|
73
|
+
return _enums_by_tag.get(tag)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def flattenable_tag_for(cls: type):
|
|
77
|
+
for klass in cls.__mro__:
|
|
78
|
+
tag = _flattenable_tags.get(klass)
|
|
79
|
+
if tag is not None:
|
|
80
|
+
return tag
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def flattenable_for_tag(tag: str):
|
|
85
|
+
return _flattenables_by_tag.get(tag)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: tags
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The value tags and format version of the wire codec.
|
|
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 enum import IntEnum
|
|
14
|
+
|
|
15
|
+
FORMAT_VERSION = 1
|
|
16
|
+
MAX_DEPTH = 64
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Tag(IntEnum):
|
|
20
|
+
NONE = 0
|
|
21
|
+
TRUE = 1
|
|
22
|
+
FALSE = 2
|
|
23
|
+
INT = 3
|
|
24
|
+
FLOAT = 4
|
|
25
|
+
STR = 5
|
|
26
|
+
BYTES = 6
|
|
27
|
+
LIST = 7
|
|
28
|
+
TUPLE = 8
|
|
29
|
+
DICT = 9
|
|
30
|
+
SET = 10
|
|
31
|
+
FROZENSET = 11
|
|
32
|
+
DATETIME = 12
|
|
33
|
+
DATE = 13
|
|
34
|
+
TIMEDELTA = 14
|
|
35
|
+
UUID = 15
|
|
36
|
+
ENUM = 16
|
|
37
|
+
FLATTENABLE = 17
|
|
38
|
+
EXCEPTION = 18
|
|
39
|
+
REFERENCE = 19
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sessions own one transport and its threads.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from ccai.rpc.core.session.base import DuplexSessionBase, Waiter, rpc_context_scope
|
|
6
|
+
from ccai.rpc.core.session.client import DuplexClientSession
|
|
7
|
+
from ccai.rpc.core.session.server import DuplexServerSession
|
|
8
|
+
|
|
9
|
+
__all__ = ["DuplexSessionBase", "Waiter", "rpc_context_scope", "DuplexClientSession", "DuplexServerSession"]
|