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.
Files changed (53) hide show
  1. ccai/rpc/__init__.py +33 -0
  2. ccai/rpc/aspects.py +145 -0
  3. ccai/rpc/core/__init__.py +0 -0
  4. ccai/rpc/core/dispatch/__init__.py +0 -0
  5. ccai/rpc/core/dispatch/context.py +115 -0
  6. ccai/rpc/core/dispatch/lanes.py +77 -0
  7. ccai/rpc/core/flattenable.py +30 -0
  8. ccai/rpc/core/futures.py +168 -0
  9. ccai/rpc/core/leases.py +35 -0
  10. ccai/rpc/core/looper.py +107 -0
  11. ccai/rpc/core/looperpool.py +136 -0
  12. ccai/rpc/core/looperqueue.py +103 -0
  13. ccai/rpc/core/observability/__init__.py +10 -0
  14. ccai/rpc/core/observability/metrics.py +26 -0
  15. ccai/rpc/core/observability/state.py +51 -0
  16. ccai/rpc/core/protocol/__init__.py +16 -0
  17. ccai/rpc/core/protocol/constants.py +64 -0
  18. ccai/rpc/core/protocol/header.py +66 -0
  19. ccai/rpc/core/protocol/messages.py +265 -0
  20. ccai/rpc/core/proxy/__init__.py +0 -0
  21. ccai/rpc/core/proxy/cache.py +48 -0
  22. ccai/rpc/core/proxy/handlers.py +101 -0
  23. ccai/rpc/core/proxy/remoteproxy.py +251 -0
  24. ccai/rpc/core/proxy/table.py +207 -0
  25. ccai/rpc/core/proxy/wrappers.py +127 -0
  26. ccai/rpc/core/serialization/__init__.py +13 -0
  27. ccai/rpc/core/serialization/codec.py +371 -0
  28. ccai/rpc/core/serialization/placeholder.py +25 -0
  29. ccai/rpc/core/serialization/registry.py +85 -0
  30. ccai/rpc/core/serialization/tags.py +39 -0
  31. ccai/rpc/core/session/__init__.py +9 -0
  32. ccai/rpc/core/session/base.py +698 -0
  33. ccai/rpc/core/session/client.py +58 -0
  34. ccai/rpc/core/session/dispatch.py +124 -0
  35. ccai/rpc/core/session/heartbeat.py +96 -0
  36. ccai/rpc/core/session/server.py +68 -0
  37. ccai/rpc/core/transport/__init__.py +10 -0
  38. ccai/rpc/core/transport/base.py +91 -0
  39. ccai/rpc/core/transport/faults.py +81 -0
  40. ccai/rpc/core/transport/inprocess.py +22 -0
  41. ccai/rpc/core/transport/socketio.py +139 -0
  42. ccai/rpc/endpoints.py +44 -0
  43. ccai/rpc/errors.py +100 -0
  44. ccai/rpc/py.typed +0 -0
  45. ccai/rpc/rpcsocketclient.py +126 -0
  46. ccai/rpc/rpcsocketserver.py +226 -0
  47. ccai/rpc/security/__init__.py +10 -0
  48. ccai/rpc/security/auth.py +34 -0
  49. ccai/rpc/security/tls.py +53 -0
  50. codecraftai_python_rpc-1.3.0.dist-info/METADATA +105 -0
  51. codecraftai_python_rpc-1.3.0.dist-info/RECORD +53 -0
  52. codecraftai_python_rpc-1.3.0.dist-info/WHEEL +4 -0
  53. codecraftai_python_rpc-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,207 @@
1
+ """
2
+ .. module:: table
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The owner-side reference table: which objects were handed to which peers, with holder counts and
5
+ lease state per holder.
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 Dict, Iterable, List, Optional, Tuple
15
+
16
+ import threading
17
+ import time
18
+ import uuid
19
+
20
+ from ccai.rpc.errors import LeaseExpiredError, UnknownReferenceError
21
+
22
+ ROOT_REFERENCE_ID = uuid.UUID(int=0)
23
+
24
+
25
+ class LeaseState:
26
+
27
+ __slots__ = ("expires_at", "last_renewed_at")
28
+
29
+ def __init__(self, duration: float) -> None:
30
+ now = time.monotonic()
31
+ self.expires_at = now + duration
32
+ self.last_renewed_at = now
33
+ return
34
+
35
+ def renew(self, duration: float) -> None:
36
+ now = time.monotonic()
37
+ self.expires_at = now + duration
38
+ self.last_renewed_at = now
39
+ return
40
+
41
+
42
+ class ReferenceEntry:
43
+
44
+ __slots__ = ("ref_id", "obj", "holders")
45
+
46
+ def __init__(self, ref_id: uuid.UUID, obj: object) -> None:
47
+ self.ref_id = ref_id
48
+ self.obj = obj
49
+ self.holders: Dict[uuid.UUID, LeaseState] = {}
50
+ return
51
+
52
+
53
+ class ReferenceTable:
54
+
55
+ def __init__(self) -> None:
56
+ self._lock = threading.RLock()
57
+ self._entries: Dict[uuid.UUID, ReferenceEntry] = {}
58
+ self._ids_by_object: Dict[int, uuid.UUID] = {}
59
+ self._tombstones: Dict[uuid.UUID, Tuple[str, float]] = {} # expired references: type name, seconds since last renewal at expiry
60
+ self._released: Dict[uuid.UUID, object] = {} # recently released objects, so a reference coming home still resolves
61
+ return
62
+
63
+ def _remember_released(self, ref_id: uuid.UUID, obj: object) -> None:
64
+ if len(self._released) >= 256:
65
+ self._released.pop(next(iter(self._released)))
66
+ self._released[ref_id] = obj
67
+ return
68
+
69
+ def _remember_expired(self, ref_id: uuid.UUID, entry: "ReferenceEntry", lease: "LeaseState") -> None:
70
+ if len(self._tombstones) >= 256:
71
+ self._tombstones.pop(next(iter(self._tombstones)))
72
+ self._tombstones[ref_id] = (type(entry.obj).__name__, time.monotonic() - lease.last_renewed_at)
73
+ return
74
+
75
+ def register(self, obj: object) -> uuid.UUID:
76
+ """
77
+ Returns the existing id for an already registered object, or assigns a new one.
78
+ """
79
+ with self._lock:
80
+ ref_id = self._ids_by_object.get(id(obj))
81
+ if ref_id is not None and ref_id in self._entries and self._entries[ref_id].obj is obj:
82
+ return ref_id
83
+ ref_id = uuid.uuid4()
84
+ self._entries[ref_id] = ReferenceEntry(ref_id, obj)
85
+ self._ids_by_object[id(obj)] = ref_id
86
+ return ref_id
87
+
88
+ def lookup(self, obj: object) -> Optional[uuid.UUID]:
89
+ """
90
+ The id of an already registered object, or ``None``. Never registers.
91
+ """
92
+ with self._lock:
93
+ ref_id = self._ids_by_object.get(id(obj))
94
+ if ref_id is not None and ref_id in self._entries and self._entries[ref_id].obj is obj:
95
+ return ref_id
96
+ return None
97
+
98
+ def register_root(self, obj: object) -> None:
99
+ with self._lock:
100
+ self._entries[ROOT_REFERENCE_ID] = ReferenceEntry(ROOT_REFERENCE_ID, obj)
101
+ self._ids_by_object[id(obj)] = ROOT_REFERENCE_ID
102
+ return
103
+
104
+ def has_root(self) -> bool:
105
+ with self._lock:
106
+ return ROOT_REFERENCE_ID in self._entries
107
+
108
+ def resolve(self, ref_id: uuid.UUID, peer: Optional[uuid.UUID] = None) -> object:
109
+ """
110
+ Returns the object for ``ref_id``. With ``peer`` given, the peer must hold the reference (the root
111
+ is exempt) and its lease must not have lapsed.
112
+ """
113
+ with self._lock:
114
+ entry = self._entries.get(ref_id)
115
+ if entry is None and peer is None and ref_id in self._released:
116
+ return self._released[ref_id]
117
+ if entry is None:
118
+ tomb = self._tombstones.get(ref_id)
119
+ if tomb is not None:
120
+ raise LeaseExpiredError("lease on reference {} ({}) expired; it was last renewed {:.1f}s before expiry".format(ref_id, tomb[0], tomb[1]))
121
+ raise UnknownReferenceError("unknown or released reference {}".format(ref_id))
122
+ if peer is not None and ref_id != ROOT_REFERENCE_ID:
123
+ lease = entry.holders.get(peer)
124
+ if lease is None:
125
+ raise UnknownReferenceError("reference {} ({}) is not held by session {}".format(
126
+ ref_id, type(entry.obj).__name__, peer))
127
+ if lease.expires_at < time.monotonic():
128
+ raise LeaseExpiredError("lease on reference {} ({}) expired; last renewed {:.1f}s ago".format(
129
+ ref_id, type(entry.obj).__name__, time.monotonic() - lease.last_renewed_at))
130
+ return entry.obj
131
+
132
+ def add_holder(self, ref_id: uuid.UUID, peer: uuid.UUID, duration: float) -> None:
133
+ with self._lock:
134
+ entry = self._entries[ref_id]
135
+ lease = entry.holders.get(peer)
136
+ if lease is None:
137
+ entry.holders[peer] = LeaseState(duration)
138
+ else:
139
+ lease.renew(duration)
140
+ return
141
+
142
+ def release(self, ref_id: uuid.UUID, peer: Optional[uuid.UUID] = None) -> Optional[object]:
143
+ """
144
+ Removes ``peer`` as a holder (or every holder). Returns the object when the entry was removed.
145
+ """
146
+ with self._lock:
147
+ entry = self._entries.get(ref_id)
148
+ if entry is None or ref_id == ROOT_REFERENCE_ID:
149
+ return None
150
+ if peer is None:
151
+ entry.holders.clear()
152
+ else:
153
+ entry.holders.pop(peer, None)
154
+ if not entry.holders:
155
+ self._entries.pop(ref_id, None)
156
+ self._ids_by_object.pop(id(entry.obj), None)
157
+ self._remember_released(ref_id, entry.obj)
158
+ return entry.obj
159
+ return None
160
+
161
+ def release_all(self) -> None:
162
+ with self._lock:
163
+ root = self._entries.get(ROOT_REFERENCE_ID)
164
+ self._entries.clear()
165
+ self._ids_by_object.clear()
166
+ if root is not None:
167
+ self._entries[ROOT_REFERENCE_ID] = root
168
+ self._ids_by_object[id(root.obj)] = ROOT_REFERENCE_ID
169
+ return
170
+
171
+ def renew(self, peer: uuid.UUID, ref_ids: Iterable[uuid.UUID], duration: float) -> List[uuid.UUID]:
172
+ unknown = []
173
+ with self._lock:
174
+ for ref_id in ref_ids:
175
+ if ref_id == ROOT_REFERENCE_ID:
176
+ continue
177
+ entry = self._entries.get(ref_id)
178
+ lease = entry.holders.get(peer) if entry is not None else None
179
+ if lease is None:
180
+ unknown.append(ref_id)
181
+ else:
182
+ lease.renew(duration)
183
+ return unknown
184
+
185
+ def expired(self, now: Optional[float] = None) -> List[Tuple[uuid.UUID, uuid.UUID]]:
186
+ now = time.monotonic() if now is None else now
187
+ with self._lock:
188
+ found = [(ref_id, peer, entry, lease) for ref_id, entry in self._entries.items() if ref_id != ROOT_REFERENCE_ID
189
+ for peer, lease in entry.holders.items() if lease.expires_at < now]
190
+ for ref_id, peer, entry, lease in found:
191
+ self._remember_expired(ref_id, entry, lease)
192
+ return [(ref_id, peer) for ref_id, peer, _, _ in found]
193
+
194
+ def held_by(self, peer: uuid.UUID) -> List[uuid.UUID]:
195
+ with self._lock:
196
+ return [ref_id for ref_id, entry in self._entries.items() if peer in entry.holders]
197
+
198
+ def describe(self) -> List[dict]:
199
+ now = time.monotonic()
200
+ with self._lock:
201
+ return [{"ref_id": str(ref_id), "type": type(entry.obj).__name__, "holders": len(entry.holders),
202
+ "lease_expires_in": min((lease.expires_at - now for lease in entry.holders.values()), default=None)}
203
+ for ref_id, entry in self._entries.items()]
204
+
205
+ def __len__(self) -> int:
206
+ with self._lock:
207
+ return len(self._entries)
@@ -0,0 +1,127 @@
1
+ """
2
+ .. module:: wrappers
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The ByRef and ByValue wrappers that declare, at the call site, how an object crosses the wire.
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
+ BY_REF_MARKER = "__rpc_by_ref__"
14
+ CONCURRENT_MARKER = "__rpc_concurrent_callbacks__"
15
+ ONEWAY_MARKER = "__rpc_oneway__"
16
+ EXPOSE_PRIVATE_MARKER = "__rpc_expose_private__"
17
+ MUTABLE_SERVICE_MARKER = "__rpc_mutable_service__"
18
+ PROXY_MARKER = "__rpc_proxy__"
19
+
20
+
21
+ class RemoteMethodDescriptor:
22
+ """
23
+ What a get-attribute of a callable comes back as: the far side builds a bound remote method from it
24
+ instead of holding a reference to a transient bound-method object.
25
+ """
26
+
27
+ __slots__ = ("name",)
28
+
29
+ def __init__(self, name: str) -> None:
30
+ self.name = name
31
+ return
32
+
33
+ def flatten(self) -> dict:
34
+ return {"name": self.name}
35
+
36
+ @classmethod
37
+ def unflatten(cls, data: dict) -> "RemoteMethodDescriptor":
38
+ return cls(data["name"])
39
+
40
+ def __repr__(self) -> str:
41
+ return "RemoteMethodDescriptor({!r})".format(self.name)
42
+
43
+
44
+ from ccai.rpc.core.serialization.registry import register_flattenable as _register_flattenable # noqa: E402
45
+ _register_flattenable("ccai.rpc.method", RemoteMethodDescriptor)
46
+
47
+
48
+ class ByRef:
49
+ """
50
+ Marks an object as passed by reference: the owner keeps it and the far side gets a proxy.
51
+ """
52
+
53
+ __slots__ = ("_instance",)
54
+
55
+ def __init__(self, instance: object) -> None:
56
+ self._instance = instance
57
+ return
58
+
59
+ @property
60
+ def instance(self) -> object:
61
+ return self._instance
62
+
63
+ def __repr__(self) -> str:
64
+ return "ByRef({!r})".format(self._instance)
65
+
66
+
67
+ class ByValue:
68
+ """
69
+ Marks an object as passed by value: it is flattened and copied to the far side.
70
+ """
71
+
72
+ __slots__ = ("_instance",)
73
+
74
+ def __init__(self, instance: object) -> None:
75
+ self._instance = instance
76
+ return
77
+
78
+ @property
79
+ def instance(self) -> object:
80
+ return self._instance
81
+
82
+ def __repr__(self) -> str:
83
+ return "ByValue({!r})".format(self._instance)
84
+
85
+
86
+ def by_ref(cls: type) -> type:
87
+ """
88
+ Class decorator marking every instance of the class as passed by reference by default.
89
+ """
90
+ setattr(cls, BY_REF_MARKER, True)
91
+ return cls
92
+
93
+
94
+ def is_by_ref_type(obj: object) -> bool:
95
+ return bool(getattr(type(obj), BY_REF_MARKER, False))
96
+
97
+
98
+ def concurrent_callbacks(cls: type) -> type:
99
+ """
100
+ Class decorator: callbacks targeting instances may run concurrently rather than in order.
101
+ """
102
+ setattr(cls, CONCURRENT_MARKER, True)
103
+ return cls
104
+
105
+
106
+ def oneway(method):
107
+ """
108
+ Method decorator: calls to this method through a proxy use fire-and-forget delivery.
109
+ """
110
+ setattr(method, ONEWAY_MARKER, True)
111
+ return method
112
+
113
+
114
+ def expose_private(cls: type) -> type:
115
+ """
116
+ Class decorator: allows remote access to underscore-prefixed attributes.
117
+ """
118
+ setattr(cls, EXPOSE_PRIVATE_MARKER, True)
119
+ return cls
120
+
121
+
122
+ def mutable_service(cls: type) -> type:
123
+ """
124
+ Class decorator: allows remote attribute writes and deletes on a root service object.
125
+ """
126
+ setattr(cls, MUTABLE_SERVICE_MARKER, True)
127
+ return cls
@@ -0,0 +1,13 @@
1
+ """
2
+ The wire codec. ``encode`` and ``decode`` turn values into payload bytes and back using a tagged
3
+ binary format with a closed type set; user types opt in through ``register_enum``,
4
+ ``register_flattenable`` and ``register_dataclass``.
5
+ """
6
+
7
+ from ccai.rpc.core.serialization.codec import decode, encode
8
+ from ccai.rpc.core.serialization.placeholder import ReferencePlaceholder
9
+ from ccai.rpc.core.serialization.registry import register_dataclass, register_enum, register_flattenable
10
+ from ccai.rpc.core.serialization.tags import FORMAT_VERSION, MAX_DEPTH, Tag
11
+
12
+ __all__ = ["encode", "decode", "ReferencePlaceholder", "register_dataclass", "register_enum",
13
+ "register_flattenable", "FORMAT_VERSION", "MAX_DEPTH", "Tag"]