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,698 @@
1
+ """
2
+ .. module:: base
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: DuplexSessionBase, the object that owns one transport and its receive, transmit, heartbeat and
5
+ dispatch threads, correlates replies to waiting callers and tears itself down cleanly.
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, Dict, List, Optional
15
+
16
+ import logging
17
+ import threading
18
+ import time
19
+ import uuid
20
+
21
+ from ccai.rpc.aspects import AspectsRpc, DEFAULT_RPC_ASPECTS, current_aspects_override
22
+ from ccai.rpc.errors import (
23
+ CancelledError,
24
+ CompletionTimeout,
25
+ LeaseExpiredError,
26
+ ProtocolError,
27
+ SessionClosedError,
28
+ SessionError,
29
+ TransportClosedError,
30
+ UnauthorizedError,
31
+ UnknownReferenceError,
32
+ )
33
+ from ccai.rpc.core.dispatch.context import CallContext
34
+ from ccai.rpc.core.dispatch.lanes import LaneTable
35
+ from ccai.rpc.core.futures import Progress, RemoteFuture
36
+ from ccai.rpc.core.looperpool import LooperPool
37
+ from ccai.rpc.core.looperqueue import LooperQueue
38
+ from ccai.rpc.core.protocol.constants import HEADER_SIZE, PROTOCOL_VERSION, ExceptionCode, MessageType, RequestCode
39
+ from ccai.rpc.core.protocol.header import MessageHeader
40
+ from ccai.rpc.core.protocol.messages import (
41
+ REPLY_FOR_REQUEST,
42
+ ExceptionMessage,
43
+ Message,
44
+ ReplyPing,
45
+ RequestCancel,
46
+ RequestClose,
47
+ RequestProgress,
48
+ RequestRelease,
49
+ )
50
+ from ccai.rpc.core.proxy.cache import ProxyCache
51
+ from ccai.rpc.core.proxy.remoteproxy import RemoteProxy
52
+ from ccai.rpc.core.proxy.table import ROOT_REFERENCE_ID, ReferenceTable
53
+ from ccai.rpc.core.serialization import ReferencePlaceholder
54
+ from ccai.rpc.core.session.dispatch import DispatchLooper
55
+ from ccai.rpc.core.session.heartbeat import HeartbeatMonitor
56
+ from ccai.rpc.core.transport.base import Transport
57
+
58
+ wire_logger = logging.getLogger("ccai.rpc.wire")
59
+
60
+ _request_context = threading.local()
61
+
62
+
63
+ def rpc_context_scope(**pairs: str):
64
+ """
65
+ Context manager adding ``pairs`` to every request sent on this thread within the block.
66
+ """
67
+ import contextlib
68
+
69
+ @contextlib.contextmanager
70
+ def scope():
71
+ previous = dict(getattr(_request_context, "pairs", {}))
72
+ merged = dict(previous)
73
+ merged.update({k: str(v) for k, v in pairs.items()})
74
+ _request_context.pairs = merged
75
+ try:
76
+ yield
77
+ finally:
78
+ _request_context.pairs = previous
79
+ return scope()
80
+
81
+
82
+ class Waiter:
83
+
84
+ __slots__ = ("correlation_id", "request_code", "callable_name", "event", "frame", "failure", "on_complete", "created_at")
85
+
86
+ def __init__(self, correlation_id: uuid.UUID, request_code: int, callable_name: str) -> None:
87
+ self.correlation_id = correlation_id
88
+ self.request_code = request_code
89
+ self.callable_name = callable_name
90
+ self.event = threading.Event()
91
+ self.frame = None
92
+ self.failure = None
93
+ self.on_complete = None
94
+ self.created_at = time.monotonic()
95
+ return
96
+
97
+ def complete(self, frame: bytes) -> None:
98
+ self.frame = frame
99
+ self.event.set()
100
+ if self.on_complete is not None:
101
+ self.on_complete()
102
+ return
103
+
104
+ def fail(self, error: BaseException) -> None:
105
+ self.failure = error
106
+ self.event.set()
107
+ if self.on_complete is not None:
108
+ self.on_complete()
109
+ return
110
+
111
+
112
+ Handler = Callable[["DuplexSessionBase", Message, CallContext], Optional[Message]]
113
+ LapseCallback = Callable[[uuid.UUID, object, uuid.UUID], None]
114
+
115
+
116
+ class DuplexSessionBase:
117
+ """
118
+ Symmetric session machine. Client and server sessions differ only in the HELLO direction and their
119
+ handler sets. The receive thread only reads frames and routes by header; every payload is decoded on
120
+ a dispatch worker or on the caller's own thread.
121
+ """
122
+
123
+ role = "session"
124
+
125
+ def __init__(self, transport: Transport, aspects: AspectsRpc = DEFAULT_RPC_ASPECTS, service: Optional[object] = None,
126
+ context: Optional[Dict[str, str]] = None, credential: bytes = b"", authenticator=None,
127
+ on_closed: Optional[Callable[["DuplexSessionBase", BaseException], None]] = None) -> None:
128
+ self._transport = transport
129
+ self._aspects = aspects
130
+ self._service = service
131
+ self._context = dict(context or {})
132
+ self._credential = credential
133
+ self._authenticator = authenticator
134
+ self._on_closed = on_closed
135
+
136
+ self.session_id = uuid.uuid4()
137
+ self.peer_session_id: Optional[uuid.UUID] = None
138
+ self.peer_context: Dict[str, str] = {}
139
+ self.peer_identity: Optional[str] = None
140
+ self.protocol_version = PROTOCOL_VERSION
141
+ self.lease_duration = aspects.lease_duration
142
+ self.renewal_interval = aspects.heartbeat_interval
143
+
144
+ self._short = self.session_id.hex[:8]
145
+ self.logger = logging.LoggerAdapter(
146
+ logging.getLogger("ccai.rpc" + ("." + aspects.logger_name if aspects.logger_name else "")),
147
+ {"session_id": str(self.session_id), "peer_session_id": None, "role": self.role})
148
+
149
+ self._lock = threading.RLock()
150
+ self._running = False
151
+ self._closing = False
152
+ self._closed = False
153
+ self._closed_event = threading.Event()
154
+ self._close_reason: Optional[BaseException] = None
155
+ self._waiters: Dict[uuid.UUID, Waiter] = {}
156
+ self._quiet_replies: Dict[uuid.UUID, float] = {} # correlation ids of notifications whose replies are dropped silently
157
+ self._futures: Dict[uuid.UUID, RemoteFuture] = {}
158
+ self._active_calls: Dict[uuid.UUID, CallContext] = {}
159
+ self._handlers: Dict[int, Handler] = {}
160
+ self._lapse_callbacks: List[LapseCallback] = []
161
+ self._outbound = LooperQueue()
162
+ self._pool: Optional[LooperPool] = None
163
+ self._receive_thread: Optional[threading.Thread] = None
164
+ self._transmit_thread: Optional[threading.Thread] = None
165
+ self._heartbeat: Optional[HeartbeatMonitor] = None
166
+ self._lanes = LaneTable()
167
+ self.table = ReferenceTable()
168
+ self.proxies = ProxyCache()
169
+ self.last_received_at = time.monotonic()
170
+ self.last_sent_at = time.monotonic()
171
+ self.counters = {"requests_sent": 0, "requests_received": 0, "replies_sent": 0, "replies_received": 0,
172
+ "exceptions_sent": 0, "exceptions_received": 0, "timeouts": 0, "bytes_sent": 0, "bytes_received": 0}
173
+ self._metrics_sinks: List[Callable[[uuid.UUID, dict], None]] = []
174
+ if service is not None:
175
+ self.table.register_root(service)
176
+ self._install_handlers()
177
+ return
178
+
179
+ # ------------------------------------------------------------------ properties
180
+ @property
181
+ def aspects(self) -> AspectsRpc:
182
+ return self._aspects
183
+
184
+ @property
185
+ def is_running(self) -> bool:
186
+ return self._running and not self._closing
187
+
188
+ @property
189
+ def is_closed(self) -> bool:
190
+ return self._closed
191
+
192
+ @property
193
+ def remote_address(self):
194
+ return self._transport.remote_address
195
+
196
+ @property
197
+ def transport(self) -> Transport:
198
+ return self._transport
199
+
200
+ @property
201
+ def service(self):
202
+ return self._service
203
+
204
+ # ------------------------------------------------------------------ lifecycle
205
+ def start(self) -> None:
206
+ with self._lock:
207
+ if self._running or self._closed:
208
+ raise SessionError("session {} cannot be started: it is {}".format(self._short, "already running" if self._running else "closed"))
209
+ self._running = True
210
+ aspects = self._aspects
211
+ self._pool = LooperPool(DispatchLooper, group_name="rpc-{}-dispatch-{}".format(self.role, self._short),
212
+ min_loopers=aspects.dispatch_min_workers, max_loopers=aspects.dispatch_max_workers,
213
+ highwater=aspects.dispatch_highwater, daemon=True, session=self)
214
+ self._pool.start_pool()
215
+ self._receive_thread = self._start_thread("recv", self._receive_loop)
216
+ self._transmit_thread = self._start_thread("xmit", self._transmit_loop)
217
+ self._heartbeat = HeartbeatMonitor(self)
218
+ self._heartbeat.start()
219
+ self.logger.info("session started role=%s remote=%s", self.role, self.remote_address)
220
+ return
221
+
222
+ def _start_thread(self, purpose: str, target) -> threading.Thread:
223
+ gate = threading.Event()
224
+ thread = threading.Thread(target=target, name="rpc-{}-{}-{}".format(self.role, purpose, self._short), args=(gate,), daemon=True)
225
+ thread.start()
226
+ gate.wait()
227
+ return thread
228
+
229
+ def close(self, timeout: Optional[float] = 5.0) -> None:
230
+ if self._closed:
231
+ return
232
+ if self._closing:
233
+ # Another thread is already tearing the session down (for example after the peer closed it); wait for
234
+ # that teardown so the session is closed when this call returns.
235
+ self._wait_for_teardown(timeout)
236
+ return
237
+ if self._running and self._transport.is_open:
238
+ try:
239
+ self.send_notification(RequestClose())
240
+ time.sleep(0.02)
241
+ except Exception: # noqa: BLE001 - closing anyway
242
+ pass
243
+ self._teardown(SessionClosedError("session {} closed locally".format(self._short)), timeout=timeout)
244
+ # The peer can answer RequestClose by closing its end, which starts a teardown on another thread before ours
245
+ # and makes ours return early; wait for whichever teardown is running to finish.
246
+ self._wait_for_teardown(timeout)
247
+ return
248
+
249
+ def _wait_for_teardown(self, timeout: Optional[float]) -> None:
250
+ """
251
+ Waits for a teardown that is running on another thread to finish. Threads owned by this session do not
252
+ wait, because the teardown joins them.
253
+
254
+ :param timeout: The maximum number of seconds to wait, or None to wait without a limit.
255
+ """
256
+ current_name = threading.current_thread().name
257
+ owned_by_session = current_name.startswith("rpc-{}-".format(self.role)) and self._short in current_name
258
+ if not owned_by_session:
259
+ self._closed_event.wait(timeout)
260
+ return
261
+
262
+ def _teardown(self, reason: BaseException, timeout: Optional[float] = 5.0) -> None:
263
+ with self._lock:
264
+ if self._closing or self._closed:
265
+ return
266
+ self._closing = True
267
+ self._close_reason = reason
268
+ waiters = list(self._waiters.values())
269
+ self._waiters.clear()
270
+ self.logger.info("session teardown: %s", reason)
271
+ for waiter in waiters:
272
+ waiter.fail(reason)
273
+ for future in list(self._futures.values()):
274
+ pass
275
+ self._futures.clear()
276
+ if self._pool is not None:
277
+ self._pool.shutdown(timeout=timeout)
278
+ self._transport.close()
279
+ self._outbound.shutdown(1)
280
+ if self._heartbeat is not None:
281
+ self._heartbeat.stop()
282
+ current = threading.current_thread()
283
+ for thread in (self._receive_thread, self._transmit_thread):
284
+ if thread is not None and thread is not current:
285
+ thread.join(timeout=timeout)
286
+ # references held by the peer lapse with the session
287
+ if self.peer_session_id is not None:
288
+ self._expire_references(self.table.held_by(self.peer_session_id), self.peer_session_id, "session closed")
289
+ for proxy in self.proxies.live_proxies():
290
+ proxy.rpc_mark_closed()
291
+ with self._lock:
292
+ self._running = False
293
+ self._closed = True
294
+ self._closed_event.set()
295
+ for sink in list(self._metrics_sinks):
296
+ try:
297
+ sink(self.session_id, dict(self.counters))
298
+ except Exception: # noqa: BLE001
299
+ self.logger.exception("metrics sink raised")
300
+ if self._on_closed is not None:
301
+ try:
302
+ self._on_closed(self, reason)
303
+ except Exception: # noqa: BLE001
304
+ self.logger.exception("on_closed callback raised")
305
+ return
306
+
307
+ def __enter__(self):
308
+ return self
309
+
310
+ def __exit__(self, exc_type, exc, tb) -> None:
311
+ self.close()
312
+ return None
313
+
314
+ # ------------------------------------------------------------------ sending
315
+ def _pack(self, message: Message) -> bytes:
316
+ return message.pack(ref_encoder=self.encode_reference, known_lookup=self.known_reference)
317
+
318
+ def _enqueue(self, frame: bytes) -> None:
319
+ if not self._running or self._closing:
320
+ raise SessionClosedError("session {} is not running".format(self._short))
321
+ self._outbound.push_work(frame)
322
+ return
323
+
324
+ def request_context(self) -> Dict[str, str]:
325
+ pairs = dict(getattr(_request_context, "pairs", {}))
326
+ return pairs
327
+
328
+ def resolve_aspects(self, override: Optional[AspectsRpc]) -> AspectsRpc:
329
+ if override is not None:
330
+ return override
331
+ scoped = current_aspects_override()
332
+ return scoped if scoped is not None else self._aspects
333
+
334
+ def send_request_async(self, message: Message, timeout: Optional[float] = None, unwrap: bool = False) -> RemoteFuture:
335
+ waiter = self._register_waiter(message)
336
+ future = RemoteFuture(self, waiter, getattr(message, "callable_name", type(message).__name__), timeout, unwrap=unwrap)
337
+ with self._lock:
338
+ self._futures[message.correlation_id] = future
339
+ self._send_registered(message, waiter)
340
+ return future
341
+
342
+ def send_request(self, message: Message, timeout: Optional[float] = None) -> Message:
343
+ """
344
+ Sends ``message`` and blocks the calling thread until its reply arrives. Raises the decoded
345
+ remote exception, or CompletionTimeout after ``timeout`` seconds.
346
+ """
347
+ waiter = self._register_waiter(message)
348
+ self._send_registered(message, waiter)
349
+ timeout = timeout if timeout is not None else self._aspects.completion_timeout
350
+ if not waiter.event.wait(timeout=timeout):
351
+ with self._lock:
352
+ self._waiters.pop(waiter.correlation_id, None)
353
+ self.counters["timeouts"] += 1
354
+ if message.mtype == MessageType.REQUEST and message.mcode in (RequestCode.CALL, RequestCode.GETATTR, RequestCode.SETATTR, RequestCode.DELATTR):
355
+ try:
356
+ self.send_cancel(message.correlation_id)
357
+ except Exception: # noqa: BLE001
358
+ pass
359
+ raise CompletionTimeout("no reply to {} '{}' from session {} within {}s (elapsed {:.2f}s); {}".format(
360
+ RequestCode(message.mcode).name, waiter.callable_name, self.peer_session_id, timeout,
361
+ time.monotonic() - waiter.created_at, self._pool_summary()))
362
+ return self.resolve_reply(waiter)
363
+
364
+ def _register_waiter(self, message: Message) -> Waiter:
365
+ name = getattr(message, "callable_name", None) or getattr(message, "name", None) or type(message).__name__
366
+ waiter = Waiter(message.correlation_id, int(message.mcode), str(name))
367
+ with self._lock:
368
+ if not self._running or self._closing:
369
+ raise SessionClosedError("session {} is not running".format(self._short))
370
+ self._waiters[message.correlation_id] = waiter
371
+ return waiter
372
+
373
+ def _send_registered(self, message: Message, waiter: Waiter) -> None:
374
+ try:
375
+ frame = self._pack(message)
376
+ self._enqueue(frame)
377
+ except BaseException:
378
+ with self._lock:
379
+ self._waiters.pop(waiter.correlation_id, None)
380
+ raise
381
+ self.counters["requests_sent"] += 1
382
+ return
383
+
384
+ def resolve_reply(self, waiter: Waiter) -> Message:
385
+ """
386
+ Decodes a completed waiter's frame on the caller's thread, raising remote exceptions.
387
+ """
388
+ if waiter.failure is not None:
389
+ raise waiter.failure
390
+ reply = Message.unpack(waiter.frame, resolver=self.resolve_reference)
391
+ if reply.mtype == MessageType.EXCEPTION:
392
+ self.counters["exceptions_received"] += 1
393
+ raise self._exception_from_message(reply)
394
+ self.counters["replies_received"] += 1
395
+ expected = REPLY_FOR_REQUEST.get(waiter.request_code)
396
+ if expected is not None and type(reply) is not expected:
397
+ raise ProtocolError("reply {} does not answer request {}".format(type(reply).__name__, RequestCode(waiter.request_code).name))
398
+ return reply
399
+
400
+ def _exception_from_message(self, message: ExceptionMessage) -> BaseException:
401
+ code = ExceptionCode(message.code) if message.code in ExceptionCode._value2member_map_ else ExceptionCode.REMOTE_EXCEPTION
402
+ if code == ExceptionCode.REMOTE_EXCEPTION and isinstance(message.value, BaseException):
403
+ return message.value
404
+ text = message.message or message.type_name
405
+ mapping = {ExceptionCode.PROTOCOL_ERROR: ProtocolError, ExceptionCode.UNKNOWN_REFERENCE: UnknownReferenceError,
406
+ ExceptionCode.LEASE_EXPIRED: LeaseExpiredError, ExceptionCode.CANCELLED: CancelledError,
407
+ ExceptionCode.UNAUTHORIZED: UnauthorizedError}
408
+ exc = mapping.get(code, type(message.value) if isinstance(message.value, BaseException) else RuntimeError)(text)
409
+ try:
410
+ exc.remote_traceback = message.traceback_text
411
+ except Exception: # noqa: BLE001
412
+ pass
413
+ return exc
414
+
415
+ def send_notification(self, message: Message) -> None:
416
+ with self._lock:
417
+ now = time.monotonic()
418
+ if len(self._quiet_replies) > 512:
419
+ for cid, stamp in list(self._quiet_replies.items()):
420
+ if now - stamp > self._aspects.completion_timeout:
421
+ self._quiet_replies.pop(cid, None)
422
+ self._quiet_replies[message.correlation_id] = now
423
+ self._enqueue(self._pack(message))
424
+ self.counters["requests_sent"] += 1
425
+ return
426
+
427
+ def send_reply(self, reply: Message) -> None:
428
+ self._enqueue(self._pack(reply))
429
+ self.counters["replies_sent"] += 1
430
+ return
431
+
432
+ def send_exception(self, exception_message: ExceptionMessage) -> None:
433
+ self._enqueue(self._pack(exception_message))
434
+ self.counters["exceptions_sent"] += 1
435
+ return
436
+
437
+ def send_cancel(self, target_correlation_id: uuid.UUID) -> None:
438
+ self.send_notification(RequestCancel(target_correlation_id=target_correlation_id))
439
+ return
440
+
441
+ def send_progress(self, target_correlation_id: uuid.UUID, fraction: float, message: Optional[str], details: dict) -> None:
442
+ self.send_notification(RequestProgress(target_correlation_id=target_correlation_id, fraction=fraction, message=message, details=details))
443
+ return
444
+
445
+ def release_reference(self, ref_id: uuid.UUID) -> None:
446
+ self.proxies.forget(ref_id)
447
+ if self.is_running:
448
+ try:
449
+ self.send_notification(RequestRelease(ref_id=ref_id))
450
+ except SessionClosedError:
451
+ # The session closed after the is_running check; the owning side drops every reference
452
+ # held by a closed session, so there is nothing left to release.
453
+ pass
454
+ return
455
+
456
+ # ------------------------------------------------------------------ references
457
+ def encode_reference(self, obj: object) -> Optional[ReferencePlaceholder]:
458
+ if isinstance(obj, RemoteProxy):
459
+ return ReferencePlaceholder(obj.rpc_reference_id, obj.rpc_owner_session_id, obj.rpc_remote_type_name)
460
+ ref_id = self.table.register(obj)
461
+ if self.peer_session_id is not None and ref_id != ROOT_REFERENCE_ID:
462
+ self.table.add_holder(ref_id, self.peer_session_id, self.lease_duration)
463
+ return ReferencePlaceholder(ref_id, self.session_id, type(obj).__name__)
464
+
465
+ def known_reference(self, obj: object) -> Optional[ReferencePlaceholder]:
466
+ ref_id = self.table.lookup(obj)
467
+ if ref_id is None:
468
+ return None
469
+ if self.peer_session_id is not None and ref_id != ROOT_REFERENCE_ID:
470
+ self.table.add_holder(ref_id, self.peer_session_id, self.lease_duration)
471
+ return ReferencePlaceholder(ref_id, self.session_id, type(obj).__name__)
472
+
473
+ def resolve_reference(self, placeholder: ReferencePlaceholder) -> object:
474
+ if placeholder.session_id == self.session_id:
475
+ return self.table.resolve(placeholder.ref_id)
476
+ proxy = self.proxies.get(placeholder.ref_id)
477
+ if proxy is None:
478
+ proxy = RemoteProxy(self, placeholder.ref_id, placeholder.session_id, placeholder.type_name)
479
+ self.proxies.put(placeholder.ref_id, proxy)
480
+ import weakref
481
+ weakref.finalize(proxy, self._proxy_collected, placeholder.ref_id)
482
+ return proxy
483
+
484
+ def _proxy_collected(self, ref_id: uuid.UUID) -> None:
485
+ if self.proxies.get(ref_id) is None and self.is_running:
486
+ try:
487
+ self.send_notification(RequestRelease(ref_id=ref_id))
488
+ except Exception: # noqa: BLE001
489
+ pass
490
+ self.proxies.forget(ref_id)
491
+ return
492
+
493
+ def on_lease_lapse(self, callback: LapseCallback) -> None:
494
+ self._lapse_callbacks.append(callback)
495
+ return
496
+
497
+ def _expire_references(self, ref_ids, peer: uuid.UUID, why: str) -> None:
498
+ for ref_id in ref_ids:
499
+ obj = self.table.release(ref_id, peer)
500
+ if obj is None:
501
+ continue
502
+ log = self.logger.info if why == "session closed" else self.logger.warning
503
+ log("reference %s (%s) held by %s lapsed: %s", ref_id, type(obj).__name__, peer, why)
504
+ self._fire_lapse(ref_id, obj, peer)
505
+ return
506
+
507
+ def _fire_lapse(self, ref_id: uuid.UUID, obj: object, peer: uuid.UUID) -> None:
508
+ def work():
509
+ handler = getattr(obj, "on_lease_lapsed", None)
510
+ if callable(handler):
511
+ try:
512
+ handler(peer)
513
+ except Exception: # noqa: BLE001
514
+ self.logger.exception("on_lease_lapsed on %s raised", type(obj).__name__)
515
+ for callback in list(self._lapse_callbacks):
516
+ try:
517
+ callback(ref_id, obj, peer)
518
+ except Exception: # noqa: BLE001
519
+ self.logger.exception("lease lapse callback raised")
520
+ if self._pool is not None and self._pool.is_running:
521
+ self._pool.push_work(work)
522
+ else:
523
+ work()
524
+ return
525
+
526
+ def sweep_leases(self) -> None:
527
+ expired = self.table.expired()
528
+ for ref_id, peer in expired:
529
+ self._expire_references([ref_id], peer, "lease expired")
530
+ return
531
+
532
+ # ------------------------------------------------------------------ handlers
533
+ def register_handler(self, code: RequestCode, handler: Handler) -> None:
534
+ self._handlers[int(code)] = handler
535
+ return
536
+
537
+ def _install_handlers(self) -> None:
538
+ from ccai.rpc.core.proxy.handlers import install as install_proxy_handlers
539
+ install_proxy_handlers(self)
540
+ self.register_handler(RequestCode.CLOSE, self._handle_close)
541
+ self.register_handler(RequestCode.RELEASE, self._handle_release)
542
+ self.register_handler(RequestCode.RENEW, self._handle_renew)
543
+ self.register_handler(RequestCode.CANCEL, self._handle_cancel)
544
+ self.register_handler(RequestCode.PROGRESS, self._handle_progress)
545
+ return
546
+
547
+ def _handle_close(self, session, message, context):
548
+ self.logger.info("peer %s requested close", self.peer_session_id)
549
+ threading.Thread(target=self._teardown, args=(SessionClosedError("peer {} closed the session".format(self.peer_session_id)),),
550
+ name="rpc-{}-close-{}".format(self.role, self._short), daemon=True).start()
551
+ return None
552
+
553
+ def _handle_release(self, session, message, context):
554
+ self.table.release(message.ref_id, self.peer_session_id)
555
+ from ccai.rpc.core.protocol.messages import ReplyRelease
556
+ return ReplyRelease()
557
+
558
+ def _handle_renew(self, session, message, context):
559
+ from ccai.rpc.core.protocol.messages import ReplyRenew
560
+ unknown = self.table.renew(self.peer_session_id, list(message.ref_ids), self.lease_duration)
561
+ return ReplyRenew(unknown=tuple(unknown))
562
+
563
+ def _handle_cancel(self, session, message, context):
564
+ with self._lock:
565
+ target = self._active_calls.get(message.target_correlation_id)
566
+ if target is not None:
567
+ target.cancel()
568
+ return None
569
+
570
+ def _handle_progress(self, session, message, context):
571
+ with self._lock:
572
+ future = self._futures.get(message.target_correlation_id)
573
+ if future is not None:
574
+ future._deliver_progress(Progress(message.fraction, message.message, dict(message.details or {}), message.target_correlation_id))
575
+ return None
576
+
577
+ def handler_for(self, code: int) -> Optional[Handler]:
578
+ return self._handlers.get(code)
579
+
580
+ def track_call(self, context: CallContext) -> None:
581
+ with self._lock:
582
+ self._active_calls[context.correlation_id] = context
583
+ return
584
+
585
+ def untrack_call(self, context: CallContext) -> None:
586
+ with self._lock:
587
+ self._active_calls.pop(context.correlation_id, None)
588
+ return
589
+
590
+ def lane_for(self, target_ref: Optional[uuid.UUID]):
591
+ return self._lanes.get(target_ref) if target_ref is not None else None
592
+
593
+ # ------------------------------------------------------------------ threads
594
+ def _receive_loop(self, gate: threading.Event) -> None:
595
+ gate.set()
596
+ reason = None
597
+ while self._running and not self._closing:
598
+ try:
599
+ frame = self._transport.receive_frame()
600
+ except TimeoutError:
601
+ continue
602
+ except TransportClosedError as err:
603
+ reason = err
604
+ break
605
+ except Exception as err: # noqa: BLE001
606
+ self.logger.exception("receive thread failed")
607
+ reason = err
608
+ break
609
+ try:
610
+ self._route_frame(frame)
611
+ except ProtocolError as err:
612
+ self.logger.warning("discarding malformed frame: %s", err)
613
+ except Exception: # noqa: BLE001
614
+ self.logger.exception("failed to route frame")
615
+ if reason is not None and not self._closing:
616
+ threading.Thread(target=self._teardown, args=(SessionClosedError("transport closed: {}".format(reason)),),
617
+ name="rpc-{}-teardown-{}".format(self.role, self._short), daemon=True).start()
618
+ return
619
+
620
+ def _route_frame(self, frame: bytes) -> None:
621
+ header = MessageHeader.unpack(frame)
622
+ if header.payload_length != len(frame) - HEADER_SIZE:
623
+ raise ProtocolError("frame length does not match its header")
624
+ self.last_received_at = time.monotonic()
625
+ self.counters["bytes_received"] += len(frame)
626
+ if wire_logger.isEnabledFor(logging.DEBUG):
627
+ wire_logger.debug("%s <- %s/%s cid=%s payload=%d", self._short, header.mtype.name, header.mcode, header.correlation_id.hex[:8], header.payload_length)
628
+ if header.mtype in (MessageType.REPLY, MessageType.EXCEPTION):
629
+ with self._lock:
630
+ waiter = self._waiters.pop(header.correlation_id, None)
631
+ quiet = self._quiet_replies.pop(header.correlation_id, None) is not None
632
+ if waiter is None:
633
+ if not quiet:
634
+ self.logger.warning("discarding stray %s for unknown correlation id %s", header.mtype.name, header.correlation_id)
635
+ return
636
+ waiter.complete(frame)
637
+ return
638
+ self.counters["requests_received"] += 1
639
+ if header.mcode == RequestCode.PING:
640
+ self.send_reply(ReplyPing(correlation_id=header.correlation_id))
641
+ return
642
+ if header.mcode == RequestCode.HELLO:
643
+ self._handle_hello_frame(frame, header)
644
+ return
645
+ self._pool.push_work(frame)
646
+ return
647
+
648
+ def _handle_hello_frame(self, frame: bytes, header: MessageHeader) -> None:
649
+ raise ProtocolError("unexpected HELLO on a {} session".format(self.role))
650
+
651
+ def _transmit_loop(self, gate: threading.Event) -> None:
652
+ gate.set()
653
+ from ccai.rpc.core.looperqueue import LooperQueueShutdown
654
+ while True:
655
+ frame = self._outbound.pop()
656
+ if frame is None or isinstance(frame, LooperQueueShutdown):
657
+ break
658
+ try:
659
+ self._transport.send_frame(frame)
660
+ self.last_sent_at = time.monotonic()
661
+ self.counters["bytes_sent"] += len(frame)
662
+ if wire_logger.isEnabledFor(logging.DEBUG):
663
+ header = MessageHeader.unpack(frame)
664
+ wire_logger.debug("%s -> %s/%s cid=%s payload=%d", self._short, header.mtype.name, header.mcode, header.correlation_id.hex[:8], header.payload_length)
665
+ except TransportClosedError as err:
666
+ if not self._closing:
667
+ threading.Thread(target=self._teardown, args=(SessionClosedError("send failed: {}".format(err)),),
668
+ name="rpc-{}-teardown-{}".format(self.role, self._short), daemon=True).start()
669
+ break
670
+ return
671
+
672
+ # ------------------------------------------------------------------ diagnostics
673
+ def register_metrics_sink(self, sink: Callable[[uuid.UUID, dict], None]) -> None:
674
+ self._metrics_sinks.append(sink)
675
+ return
676
+
677
+ def _pool_summary(self) -> str:
678
+ if self._pool is None:
679
+ return "dispatch pool not started"
680
+ described = self._pool.describe()
681
+ busy = sum(1 for ctx in list(self._active_calls.values()))
682
+ return "dispatch pool {}: {} workers, {} busy, {} queued".format(described["group"], described["worker_count"], busy, described["queue_depth"])
683
+
684
+ def describe(self) -> dict:
685
+ with self._lock:
686
+ active = [ctx.describe() for ctx in self._active_calls.values()]
687
+ waiters = len(self._waiters)
688
+ return {
689
+ "role": self.role, "session_id": str(self.session_id), "peer_session_id": str(self.peer_session_id) if self.peer_session_id else None,
690
+ "peer_identity": self.peer_identity, "running": self.is_running, "closed": self._closed, "protocol_version": self.protocol_version,
691
+ "remote": self.remote_address, "outstanding_requests": waiters, "outbound_depth": self._outbound.depth,
692
+ "active_calls": active, "pool": self._pool.describe() if self._pool else None, "references": self.table.describe(),
693
+ "live_proxies": len(self.proxies.live_ids()), "last_received_ago": round(time.monotonic() - self.last_received_at, 3),
694
+ "last_sent_ago": round(time.monotonic() - self.last_sent_at, 3), "counters": dict(self.counters),
695
+ }
696
+
697
+ def __repr__(self) -> str:
698
+ return "<{} {} peer={} running={}>".format(type(self).__name__, self._short, self.peer_session_id, self.is_running)