codecraftai-python-rpc 1.4.0__tar.gz → 1.5.0__tar.gz

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. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/PKG-INFO +1 -1
  2. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/pyproject.toml +1 -1
  3. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/lanes.py +12 -3
  4. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/futures.py +13 -2
  5. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looper.py +21 -1
  6. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looperpool.py +34 -8
  7. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looperqueue.py +22 -0
  8. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/constants.py +2 -0
  9. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/remoteproxy.py +12 -1
  10. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/codec.py +73 -21
  11. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/base.py +72 -1
  12. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/dispatch.py +52 -11
  13. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/heartbeat.py +2 -1
  14. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/server.py +48 -20
  15. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/socketio.py +65 -2
  16. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/rpcsocketclient.py +2 -1
  17. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/rpcsocketserver.py +78 -15
  18. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/LICENSE.md +0 -0
  19. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/README.rst +0 -0
  20. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/__init__.py +0 -0
  21. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/aspects.py +0 -0
  22. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/__init__.py +0 -0
  23. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/__init__.py +0 -0
  24. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/context.py +0 -0
  25. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/flattenable.py +0 -0
  26. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/leases.py +0 -0
  27. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/__init__.py +0 -0
  28. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/metrics.py +0 -0
  29. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/state.py +0 -0
  30. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/__init__.py +0 -0
  31. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/header.py +0 -0
  32. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/messages.py +0 -0
  33. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/__init__.py +0 -0
  34. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/cache.py +0 -0
  35. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/handlers.py +0 -0
  36. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/table.py +0 -0
  37. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/wrappers.py +0 -0
  38. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/__init__.py +0 -0
  39. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/placeholder.py +0 -0
  40. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/registry.py +0 -0
  41. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/tags.py +0 -0
  42. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/__init__.py +0 -0
  43. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/client.py +0 -0
  44. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/__init__.py +0 -0
  45. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/base.py +0 -0
  46. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/faults.py +0 -0
  47. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/inprocess.py +0 -0
  48. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/endpoints.py +0 -0
  49. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/errors.py +0 -0
  50. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/py.typed +0 -0
  51. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/__init__.py +0 -0
  52. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/auth.py +0 -0
  53. {codecraftai_python_rpc-1.4.0 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/tls.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codecraftai-python-rpc
3
- Version: 1.4.0
3
+ Version: 1.5.0
4
4
  Summary: Code Craft AI - Python RPC Package
5
5
  License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
6
  License-File: LICENSE.md
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codecraftai-python-rpc"
3
- version = "1.4.0"
3
+ version = "1.5.0"
4
4
  description = "Code Craft AI - Python RPC Package"
5
5
  readme = "README.rst"
6
6
  license = "LicenseRef-CodeCraftAI-Source-Available"
@@ -27,20 +27,29 @@ class TargetLane:
27
27
  def run(self, work: Callable[[], None]) -> None:
28
28
  """
29
29
  Runs ``work`` now if the lane is free, otherwise queues it for the worker holding the lane, which
30
- drains the queue before releasing. Callers therefore never block on the lane.
30
+ drains the queue before releasing. Callers therefore never block on the lane. When a BaseException
31
+ escapes a work item, the lane is released and the exception propagates; work still queued stays
32
+ queued, in order, and runs ahead of the next item that arrives.
31
33
  """
32
34
  with self._lock:
33
35
  if self._busy:
34
36
  self._fifo.append(work)
35
37
  return
36
38
  self._busy = True
37
- current = work
39
+ if self._fifo:
40
+ # left behind by a holder that a BaseException ended; keep arrival order
41
+ self._fifo.append(work)
42
+ current = self._fifo.pop(0)
43
+ else:
44
+ current = work
38
45
  while True:
46
+ finished = False
39
47
  try:
40
48
  current()
49
+ finished = True
41
50
  finally:
42
51
  with self._lock:
43
- if self._fifo:
52
+ if finished and self._fifo:
44
53
  current = self._fifo.pop(0)
45
54
  continue_ = True
46
55
  else:
@@ -40,7 +40,9 @@ class Progress:
40
40
  class RemoteFuture(Generic[T]):
41
41
  """
42
42
  The result of an asynchronous remote call. Completed by the session when the reply or exception
43
- arrives, failed when the session closes, cancellable cooperatively.
43
+ arrives, failed when the session closes or when no reply has arrived by ``deadline`` seconds after
44
+ ``started_at``, cancellable cooperatively. Decoding the reply and running done callbacks happen on a
45
+ dispatch worker, never on the session's receive thread.
44
46
  """
45
47
 
46
48
  def __init__(self, session, waiter, callable_name: str, deadline: Optional[float], unwrap: bool = False) -> None:
@@ -59,7 +61,7 @@ class RemoteFuture(Generic[T]):
59
61
  self._result = None
60
62
  self._exception = None
61
63
  self._resolved = False
62
- waiter.on_complete = self._on_complete
64
+ waiter.on_complete = self._schedule_completion
63
65
  return
64
66
 
65
67
  # --------------------------------------------------------------- completion
@@ -77,6 +79,15 @@ class RemoteFuture(Generic[T]):
77
79
  self._resolved = True
78
80
  return
79
81
 
82
+ def _schedule_completion(self) -> None:
83
+ """
84
+ Called by the waiter, possibly on the receive thread, when the reply arrives or the call fails: the
85
+ session forgets the future and hands decoding and the done callbacks to a dispatch worker.
86
+ """
87
+ self._session.forget_future(self.correlation_id)
88
+ self._session.run_off_receive_thread(self._on_complete)
89
+ return
90
+
80
91
  def _on_complete(self) -> None:
81
92
  self._resolve()
82
93
  for callback in list(self._done_callbacks):
@@ -10,7 +10,7 @@ __author__ = "Myron Walker"
10
10
  __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
11
  __credits__ = []
12
12
 
13
- from typing import Optional
13
+ from typing import Callable, Optional
14
14
 
15
15
  import logging
16
16
  import threading
@@ -39,6 +39,7 @@ class Looper:
39
39
  self._stop_requested = False
40
40
  self._thread = None
41
41
  self._exit_gate = None
42
+ self._abnormal_exit_callback = None
42
43
  return
43
44
 
44
45
  @property
@@ -74,6 +75,17 @@ class Looper:
74
75
  start_gate.wait()
75
76
  return
76
77
 
78
+ def set_abnormal_exit_callback(self, callback: Optional[Callable[["Looper"], None]]) -> None:
79
+ """
80
+ Sets a callable invoked on the looper's thread when the thread is about to exit because an exception
81
+ that is not an :class:`Exception` (a BaseException) escaped ``loop``. The exception still propagates
82
+ and ends the thread; a :class:`LooperPool` uses the callback to start a replacement worker.
83
+
84
+ :param callback: Called with this looper, or None to clear it.
85
+ """
86
+ self._abnormal_exit_callback = callback
87
+ return
88
+
77
89
  def stop(self) -> None:
78
90
  """
79
91
  Requests exit. The thread leaves its loop when the next packet arrives.
@@ -92,16 +104,24 @@ class Looper:
92
104
  def _loop_entry(self, start_gate: threading.Event) -> None:
93
105
  self._running = True
94
106
  start_gate.set()
107
+ clean_exit = False
95
108
  try:
96
109
  while True:
97
110
  packet = self._queue.pop()
98
111
  if isinstance(packet, LooperQueueShutdown) or packet is None or self._stop_requested:
112
+ if packet is not None and not isinstance(packet, LooperQueueShutdown):
113
+ self._queue.task_done()
99
114
  break
100
115
  try:
101
116
  self.loop(packet)
102
117
  except Exception:
103
118
  logger.exception("Looper %s: unhandled exception processing packet %r", self.name, packet)
119
+ finally:
120
+ self._queue.task_done()
121
+ clean_exit = True
104
122
  finally:
105
123
  self._running = False
106
124
  self._exit_gate.set()
125
+ if not clean_exit and self._abnormal_exit_callback is not None:
126
+ self._abnormal_exit_callback(self)
107
127
  return
@@ -12,18 +12,23 @@ __credits__ = []
12
12
 
13
13
  from typing import List, Optional, Sequence, Type
14
14
 
15
+ import logging
15
16
  import threading
16
17
 
17
18
  from ccai.rpc.errors import LooperError
18
19
  from ccai.rpc.core.looper import Looper
19
20
  from ccai.rpc.core.looperqueue import LooperQueue
20
21
 
22
+ logger = logging.getLogger("ccai.rpc.dispatch")
23
+
21
24
 
22
25
  class LooperPool:
23
26
  """
24
27
  Owns one :class:`LooperQueue` and a growable set of loopers. ``start_pool`` starts
25
- ``min_loopers``; each push that leaves more than ``highwater`` packets queued starts one more
26
- looper up to ``max_loopers``. The pool never shrinks; ``shutdown`` is how workers exit.
28
+ ``min_loopers``; each push that finds no idle worker, or that leaves more than ``highwater``
29
+ packets queued, starts one more looper up to ``max_loopers``. A looper whose thread is ended by a
30
+ BaseException escaping ``loop`` is replaced while the pool runs. The pool never shrinks;
31
+ ``shutdown`` is how workers exit.
27
32
  """
28
33
 
29
34
  def __init__(self, looper_type: Type[Looper], group_name: str = "looper", min_loopers: int = 2,
@@ -42,6 +47,7 @@ class LooperPool:
42
47
  self._queue = LooperQueue()
43
48
  self._lock = threading.RLock()
44
49
  self._loopers: List[Looper] = []
50
+ self._looper_serial = 0
45
51
  self._running = False
46
52
  self._started = False
47
53
  return
@@ -121,16 +127,36 @@ class LooperPool:
121
127
  return
122
128
 
123
129
  def _grow_if_needed(self, depth: int) -> None:
124
- if depth > self._highwater:
125
- with self._lock:
126
- if self._running and len(self._loopers) < self._max_loopers:
127
- self._locked_start_looper()
130
+ with self._lock:
131
+ if not self._running or len(self._loopers) >= self._max_loopers:
132
+ return
133
+ # More unfinished packets than workers means every worker is busy and a packet is waiting.
134
+ no_idle_worker = self._queue.unfinished > len(self._loopers)
135
+ if no_idle_worker or depth > self._highwater:
136
+ self._locked_start_looper()
137
+ return
138
+
139
+ def _looper_exited_abnormally(self, looper: Looper) -> None:
140
+ """
141
+ Runs on the thread of a looper that a BaseException is ending: drops it from the pool and, while the
142
+ pool runs, starts a replacement so the pool keeps its workers.
143
+
144
+ :param looper: The looper whose thread is exiting.
145
+ """
146
+ with self._lock:
147
+ if looper in self._loopers:
148
+ self._loopers.remove(looper)
149
+ if self._running:
150
+ logger.error("LooperPool %s: worker %s is exiting on a BaseException; starting a replacement",
151
+ self._group_name, looper.name)
152
+ self._locked_start_looper()
128
153
  return
129
154
 
130
155
  def _locked_start_looper(self) -> None:
131
- index = len(self._loopers) + 1
132
- looper_name = "{}-{}".format(self._group_name, index)
156
+ self._looper_serial += 1
157
+ looper_name = "{}-{}".format(self._group_name, self._looper_serial)
133
158
  looper = self._looper_type(self._queue, name=looper_name, group=self._group_name, daemon=self._daemon, **self._looper_kwargs)
159
+ looper.set_abnormal_exit_callback(self._looper_exited_abnormally)
134
160
  looper.start()
135
161
  self._loopers.append(looper)
136
162
  return
@@ -31,6 +31,8 @@ class LooperQueue:
31
31
  """
32
32
  Thread-safe queue. The semaphore count always equals the number of packets appended and not
33
33
  yet popped, which is what makes one wake-up per packet, and therefore shutdown, reliable.
34
+ ``unfinished`` counts packets pushed and not yet reported done with ``task_done``, so a pool can
35
+ tell when every worker is busy.
34
36
  """
35
37
 
36
38
  def __init__(self) -> None:
@@ -38,6 +40,7 @@ class LooperQueue:
38
40
  self._available = threading.Semaphore(value=0)
39
41
  self._lock = threading.RLock()
40
42
  self._shutdown = False
43
+ self._unfinished = 0
41
44
  return
42
45
 
43
46
  @property
@@ -50,6 +53,23 @@ class LooperQueue:
50
53
  with self._lock:
51
54
  return self._shutdown
52
55
 
56
+ @property
57
+ def unfinished(self) -> int:
58
+ """
59
+ The number of packets pushed and not yet reported done, whether queued or being processed.
60
+ """
61
+ with self._lock:
62
+ return self._unfinished
63
+
64
+ def task_done(self) -> None:
65
+ """
66
+ Reports that a popped packet has been processed (or dropped).
67
+ """
68
+ with self._lock:
69
+ if self._unfinished > 0:
70
+ self._unfinished -= 1
71
+ return
72
+
53
73
  def push_work(self, packet: object) -> int:
54
74
  """
55
75
  Appends one packet and signals one available packet. Returns the resulting depth.
@@ -58,6 +78,7 @@ class LooperQueue:
58
78
  if self._shutdown:
59
79
  raise LooperError("LooperQueue: the queue is shut down, no more work is allowed to be queued.")
60
80
  self._queue.append(packet)
81
+ self._unfinished += 1
61
82
  depth = len(self._queue)
62
83
  self._available.release()
63
84
  return depth
@@ -71,6 +92,7 @@ class LooperQueue:
71
92
  if self._shutdown:
72
93
  raise LooperError("LooperQueue: the queue is shut down, no more work is allowed to be queued.")
73
94
  self._queue.extend(packets)
95
+ self._unfinished += len(packets)
74
96
  depth = len(self._queue)
75
97
  for _ in packets:
76
98
  self._available.release()
@@ -17,6 +17,8 @@ MIN_SUPPORTED_VERSION = 1
17
17
  HEADER_SIZE = 24
18
18
  FRAME_SIZE_BYTES = 8
19
19
  DEFAULT_MAX_MESSAGE_SIZE = 64 * 1024 * 1024
20
+ # The largest frame a server accepts from a peer that has not completed HELLO.
21
+ PRE_HELLO_MAX_MESSAGE_SIZE = 64 * 1024
20
22
 
21
23
 
22
24
  class MessageType(IntEnum):
@@ -235,7 +235,18 @@ class RemoteProxy:
235
235
  return self
236
236
 
237
237
  def __exit__(self, exc_type, exc, tb):
238
- return self._call("__exit__", (None, None, None), {})
238
+ """
239
+ Forwards the end of a with-block to the remote ``__exit__``. A class object and a traceback cannot
240
+ travel by value, so the remote side receives ``(type_name, exc, None)``: ``type_name`` is the
241
+ exception's ``"module.qualname"`` string, ``exc`` the exception rebuilt on the far side, and the
242
+ traceback is always None. A clean exit forwards ``(None, None, None)``. The local exception is
243
+ suppressed only when the remote ``__exit__`` saw it and returned a truthy value.
244
+ """
245
+ if exc is None:
246
+ self._call("__exit__", (None, None, None), {})
247
+ return False
248
+ type_name = "{}.{}".format(type(exc).__module__, type(exc).__qualname__)
249
+ return bool(self._call("__exit__", (type_name, exc, None), {}))
239
250
 
240
251
  def __bool__(self) -> bool:
241
252
  return True
@@ -35,6 +35,16 @@ ReferenceResolver = Callable[[ReferencePlaceholder], object]
35
35
  # Exception types are resolved only from modules already loaded in this process; decoding never imports.
36
36
  _PRELOADED_EXCEPTION_MODULES = {"builtins": builtins, "ccai.errors.exceptions": _ccai_exceptions}
37
37
 
38
+ # A peer may only make this process raise ordinary errors, plus the suite's SemanticError and ConfigurationError,
39
+ # which are never downgraded. SystemExit, KeyboardInterrupt, GeneratorExit and other BaseException types named by
40
+ # a peer arrive as RemoteError instead.
41
+ _REBUILDABLE_EXCEPTION_BASES = (Exception, _ccai_exceptions.SemanticError, _ccai_exceptions.ConfigurationError)
42
+
43
+ # Lengths, counts and every other varint fit in 10 bytes (70 bits). An INT value may be longer so that large
44
+ # Python ints still travel, but it is bounded so a hostile peer cannot make decoding take quadratic time.
45
+ MAX_VARINT_BYTES = 10
46
+ MAX_INT_VARINT_BYTES = 1024
47
+
38
48
 
39
49
  def _write_varint(out: bytearray, value: int) -> None:
40
50
  if value < 0:
@@ -49,12 +59,15 @@ def _write_varint(out: bytearray, value: int) -> None:
49
59
  return
50
60
 
51
61
 
52
- def _read_varint(data: bytes, pos: int):
62
+ def _read_varint(data: bytes, pos: int, max_bytes: int = MAX_VARINT_BYTES):
53
63
  shift = 0
54
64
  result = 0
65
+ start = pos
55
66
  while True:
56
67
  if pos >= len(data):
57
68
  raise SerializationError("truncated varint")
69
+ if pos - start >= max_bytes:
70
+ raise SerializationError("varint is longer than the limit of {} bytes".format(max_bytes))
58
71
  byte = data[pos]
59
72
  pos += 1
60
73
  result |= (byte & 0x7F) << shift
@@ -107,9 +120,17 @@ class Encoder:
107
120
  self._tag(Tag.TRUE)
108
121
  elif value is False:
109
122
  self._tag(Tag.FALSE)
123
+ elif isinstance(value, enum.Enum) and registry.enum_tag_for(type(value)) is not None:
124
+ self._tag(Tag.ENUM)
125
+ self._str(registry.enum_tag_for(type(value)))
126
+ self._str(value.name)
110
127
  elif isinstance(value, int) and not isinstance(value, enum.Enum):
111
128
  self._tag(Tag.INT)
129
+ start = len(out)
112
130
  _write_varint(out, _zigzag(value))
131
+ if len(out) - start > MAX_INT_VARINT_BYTES:
132
+ raise SerializationError("int is too large for the wire, limit is {} varint bytes (at {})".format(
133
+ MAX_INT_VARINT_BYTES, path))
113
134
  elif isinstance(value, float):
114
135
  self._tag(Tag.FLOAT)
115
136
  out.extend(struct.pack("!d", value))
@@ -120,16 +141,20 @@ class Encoder:
120
141
  self._tag(Tag.BYTES)
121
142
  self._bytes(bytes(value))
122
143
  elif isinstance(value, ByValue):
123
- self._encode(value.instance, depth, path)
144
+ if is_by_ref_type(value.instance):
145
+ # the explicit wrapper overrides the class's by-reference default
146
+ tag = registry.flattenable_tag_for(type(value.instance))
147
+ if tag is None:
148
+ raise SerializationError("type '{}' is wrapped as ByValue but is not registered as flattenable (at {})".format(
149
+ type(value.instance).__name__, path))
150
+ self._flattenable(value.instance, tag, depth, path)
151
+ else:
152
+ self._encode(value.instance, depth, path)
124
153
  elif isinstance(value, ByRef) or is_by_ref_type(value) or getattr(type(value), PROXY_MARKER, False):
125
154
  self._reference(value.instance if isinstance(value, ByRef) else value, path)
126
155
  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)
156
+ # registered enums were encoded above; str/float/bytes mixin members travel as their value
157
+ raise SerializationError("enum type '{}' is not registered (at {})".format(type(value).__name__, path))
133
158
  elif isinstance(value, (list, tuple, set, frozenset)):
134
159
  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
160
  self._tag(tag)
@@ -166,10 +191,7 @@ class Encoder:
166
191
  else:
167
192
  tag = registry.flattenable_tag_for(type(value))
168
193
  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))
194
+ self._flattenable(value, tag, depth, path)
173
195
  elif self._known_lookup is not None and self._known_lookup(value) is not None:
174
196
  # an object this session already handed out by reference travels as that reference
175
197
  self._placeholder(self._known_lookup(value))
@@ -179,6 +201,13 @@ class Encoder:
179
201
  type(value).__name__, path))
180
202
  return
181
203
 
204
+ def _flattenable(self, value: object, tag: str, depth: int, path: str) -> None:
205
+ self._tag(Tag.FLATTENABLE)
206
+ self._str(tag)
207
+ flat = value.flatten()
208
+ self._encode(flat, depth + 1, "{}<{}>".format(path, tag))
209
+ return
210
+
182
211
  def _reference(self, obj: object, path: str) -> None:
183
212
  if self._ref_encoder is None:
184
213
  raise SerializationError("a by-reference object cannot be encoded outside a session (at {})".format(path))
@@ -241,8 +270,8 @@ class Decoder:
241
270
  self._pos += count
242
271
  return chunk
243
272
 
244
- def _varint(self) -> int:
245
- value, self._pos = _read_varint(self._data, self._pos)
273
+ def _varint(self, max_bytes: int = MAX_VARINT_BYTES) -> int:
274
+ value, self._pos = _read_varint(self._data, self._pos, max_bytes)
246
275
  return value
247
276
 
248
277
  def _bytes(self) -> bytes:
@@ -266,7 +295,7 @@ class Decoder:
266
295
  if tag == Tag.FALSE:
267
296
  return False
268
297
  if tag == Tag.INT:
269
- return _unzigzag(self._varint())
298
+ return _unzigzag(self._varint(MAX_INT_VARINT_BYTES))
270
299
  if tag == Tag.FLOAT:
271
300
  return struct.unpack("!d", self._take(8))[0]
272
301
  if tag == Tag.STR:
@@ -307,7 +336,7 @@ class Decoder:
307
336
  data = self._value(depth + 1)
308
337
  return cls.unflatten(data)
309
338
  if tag == Tag.EXCEPTION:
310
- return self._exception()
339
+ return self._exception(depth)
311
340
  if tag == Tag.REFERENCE:
312
341
  ref_id = uuid.UUID(bytes=self._take(16))
313
342
  session_id = uuid.UUID(bytes=self._take(16))
@@ -318,14 +347,32 @@ class Decoder:
318
347
  return self._resolver(placeholder)
319
348
  raise SerializationError("unhandled value tag {}".format(tag))
320
349
 
321
- def _exception(self) -> BaseException:
350
+ def _exception(self, depth: int) -> BaseException:
322
351
  type_name = self._str()
323
352
  message = self._str()
324
353
  args_bytes = self._bytes()
325
354
  tb_text = self._str()
326
- exc = _build_exception(type_name, message, args_bytes, tb_text, self._resolver)
355
+ args = self._exception_args(args_bytes, depth)
356
+ exc = _build_exception(type_name, message, args, tb_text)
327
357
  return exc
328
358
 
359
+ def _exception_args(self, args_bytes: bytes, depth: int) -> Optional[tuple]:
360
+ """
361
+ Decodes the args tuple the encoder attached to an exception. Returns None when the sender could
362
+ not encode them (empty bytes) or they do not decode here, so the exception is rebuilt from its
363
+ message alone, as it was before args travelled.
364
+ """
365
+ if not args_bytes:
366
+ return None
367
+ nested = Decoder(args_bytes, self._resolver)
368
+ try:
369
+ args = nested._value(depth + 1)
370
+ except SerializationError:
371
+ return None
372
+ if nested._pos != len(args_bytes) or not isinstance(args, tuple):
373
+ return None
374
+ return args
375
+
329
376
 
330
377
  def _resolve_exception_type(type_name: str):
331
378
  module_name, _, qualname = type_name.rpartition(".")
@@ -337,15 +384,20 @@ def _resolve_exception_type(type_name: str):
337
384
  obj = getattr(obj, part, None)
338
385
  if obj is None:
339
386
  return None
340
- if isinstance(obj, type) and issubclass(obj, BaseException):
387
+ if isinstance(obj, type) and issubclass(obj, _REBUILDABLE_EXCEPTION_BASES):
341
388
  return obj
342
389
  return None
343
390
 
344
391
 
345
- def _build_exception(type_name: str, message: str, args_bytes: bytes, tb_text: str, resolver) -> BaseException:
392
+ def _build_exception(type_name: str, message: str, args: Optional[tuple], tb_text: str) -> BaseException:
346
393
  cls = _resolve_exception_type(type_name)
347
394
  exc = None
348
- if cls is not None:
395
+ if cls is not None and args is not None:
396
+ try:
397
+ exc = cls(*args)
398
+ except Exception:
399
+ exc = None
400
+ if cls is not None and exc is None:
349
401
  try:
350
402
  exc = cls(message)
351
403
  except Exception:
@@ -23,6 +23,7 @@ from ccai.rpc.errors import (
23
23
  CancelledError,
24
24
  CompletionTimeout,
25
25
  LeaseExpiredError,
26
+ LooperError,
26
27
  ProtocolError,
27
28
  SessionClosedError,
28
29
  SessionError,
@@ -57,6 +58,10 @@ from ccai.rpc.core.transport.base import Transport
57
58
 
58
59
  wire_logger = logging.getLogger("ccai.rpc.wire")
59
60
 
61
+ # How long a session that ends itself after a final exception reply waits for that reply to leave the outbound queue
62
+ # before the transport closes.
63
+ TEARDOWN_FLUSH_SECONDS = 0.5
64
+
60
65
  _request_context = threading.local()
61
66
 
62
67
 
@@ -305,6 +310,20 @@ class DuplexSessionBase:
305
310
  self.logger.exception("on_closed callback raised")
306
311
  return
307
312
 
313
+ def _teardown_after_flush(self, reason: BaseException) -> None:
314
+ """
315
+ Waits, off the receive thread, for the outbound queue to drain (bounded by TEARDOWN_FLUSH_SECONDS) so a
316
+ final exception reply reaches the peer, then tears the session down.
317
+
318
+ :param reason: The close reason recorded by the teardown.
319
+ """
320
+ deadline = time.monotonic() + TEARDOWN_FLUSH_SECONDS
321
+ while self._outbound.depth > 0 and time.monotonic() < deadline:
322
+ time.sleep(0.01)
323
+ time.sleep(0.02) # the transmit thread has popped the last frame; give it time to write it
324
+ self._teardown(reason)
325
+ return
326
+
308
327
  def __enter__(self):
309
328
  return self
310
329
 
@@ -337,9 +356,61 @@ class DuplexSessionBase:
337
356
  future = RemoteFuture(self, waiter, getattr(message, "callable_name", type(message).__name__), timeout, unwrap=unwrap)
338
357
  with self._lock:
339
358
  self._futures[message.correlation_id] = future
340
- self._send_registered(message, waiter)
359
+ try:
360
+ self._send_registered(message, waiter)
361
+ except BaseException:
362
+ self.forget_future(message.correlation_id)
363
+ raise
341
364
  return future
342
365
 
366
+ def forget_future(self, correlation_id: uuid.UUID) -> None:
367
+ """
368
+ Drops a completed or failed asynchronous call from the session's table of outstanding futures.
369
+
370
+ :param correlation_id: The correlation id of the call.
371
+ """
372
+ with self._lock:
373
+ self._futures.pop(correlation_id, None)
374
+ return
375
+
376
+ def expire_overdue_futures(self) -> None:
377
+ """
378
+ Fails, with CompletionTimeout, every asynchronous call whose deadline has passed without a reply, the
379
+ way a synchronous call times out. Called from the heartbeat. A reply that arrives later is discarded.
380
+ """
381
+ now = time.monotonic()
382
+ overdue = []
383
+ with self._lock:
384
+ for correlation_id, future in list(self._futures.items()):
385
+ if future.deadline is None or now - future.started_at <= future.deadline:
386
+ continue
387
+ waiter = self._waiters.pop(correlation_id, None)
388
+ self._futures.pop(correlation_id, None)
389
+ if waiter is not None: # whoever pops the waiter completes it
390
+ overdue.append((future, waiter))
391
+ for future, waiter in overdue:
392
+ self.counters["timeouts"] += 1
393
+ waiter.fail(CompletionTimeout("no reply to '{}' from session {} within {}s; {}".format(
394
+ future.callable_name, self.peer_session_id, future.deadline, self._pool_summary())))
395
+ return
396
+
397
+ def run_off_receive_thread(self, work: Callable[[], None]) -> None:
398
+ """
399
+ Runs ``work`` on a dispatch worker, or on a short-lived thread when the dispatch pool is not running, so
400
+ the receive thread never runs decoding or user callbacks.
401
+
402
+ :param work: The callable to run.
403
+ """
404
+ pool = self._pool
405
+ if pool is not None and pool.is_running:
406
+ try:
407
+ pool.push_work(work)
408
+ return
409
+ except LooperError:
410
+ pass # the pool shut down after the check; run the work on its own thread instead
411
+ threading.Thread(target=work, name="rpc-{}-complete-{}".format(self.role, self._short), daemon=True).start()
412
+ return
413
+
343
414
  def send_request(self, message: Message, timeout: Optional[float] = None) -> Message:
344
415
  """
345
416
  Sends ``message`` and blocks the calling thread until its reply arrives. Raises the decoded
@@ -11,10 +11,20 @@ __author__ = "Myron Walker"
11
11
  __copyright__ = "Copyright 2025, Code Craft AI LLC"
12
12
  __credits__ = []
13
13
 
14
+ import threading
14
15
  import time
15
16
 
17
+ from ccai.errors.exceptions import ConfigurationError, SemanticError
18
+
16
19
  from ccai.rpc.aspects import LoggingPattern
17
- from ccai.rpc.errors import CancelledError, LeaseExpiredError, ProtocolError, UnauthorizedError, UnknownReferenceError
20
+ from ccai.rpc.errors import (
21
+ CancelledError,
22
+ LeaseExpiredError,
23
+ ProtocolError,
24
+ SessionClosedError,
25
+ UnauthorizedError,
26
+ UnknownReferenceError,
27
+ )
18
28
  from ccai.rpc.core.dispatch.context import CallContext, set_call_context
19
29
  from ccai.rpc.core.looper import Looper
20
30
  from ccai.rpc.core.protocol.constants import ExceptionCode, RequestCode
@@ -100,20 +110,51 @@ class DispatchLooper(Looper):
100
110
  if isinstance(err, (UnknownReferenceError, LeaseExpiredError)) or (isinstance(err, AttributeError) and "refused" in str(err)):
101
111
  session.logger.warning("refused %s '%s' from %s (%s): %s", RequestCode(code).name, context.callable_name,
102
112
  session.peer_identity or session.peer_session_id, session.remote_address, err)
103
- if notify:
104
- session.logger.warning("one-way request %s '%s' raised: %s", RequestCode(code).name, context.callable_name, err)
105
- else:
106
- exc_code = {UnknownReferenceError: ExceptionCode.UNKNOWN_REFERENCE, LeaseExpiredError: ExceptionCode.LEASE_EXPIRED,
107
- CancelledError: ExceptionCode.CANCELLED, ProtocolError: ExceptionCode.PROTOCOL_ERROR,
108
- UnauthorizedError: ExceptionCode.UNAUTHORIZED}.get(type(err), ExceptionCode.REMOTE_EXCEPTION)
109
- try:
110
- session.send_exception(ExceptionMessage.from_exception(err, code=exc_code, correlation_id=message.correlation_id))
111
- except Exception: # noqa: BLE001
112
- session.logger.exception("could not send exception reply for %s", context.callable_name)
113
+ self._report_failure(session, message, context, code, notify, err)
114
+ except (SemanticError, ConfigurationError) as err:
115
+ # The remote caller is the application layer for this request: it receives the error itself, unchanged,
116
+ # as the exception reply (decisions D13, MYT-433), and this worker stays alive for the next request.
117
+ outcome = type(err).__name__
118
+ self._report_failure(session, message, context, code, notify, err)
119
+ except BaseException as err:
120
+ # SystemExit, KeyboardInterrupt or another BaseException from a handler: answer the caller rather than
121
+ # leave it waiting, then let the exception end this worker (the pool replaces it). SystemExit and
122
+ # KeyboardInterrupt also end the session.
123
+ outcome = type(err).__name__
124
+ self._report_failure(session, message, context, code, notify, err)
125
+ if isinstance(err, (SystemExit, KeyboardInterrupt)):
126
+ session.logger.error("%s '%s' raised %s; closing the session", RequestCode(code).name, context.callable_name, outcome)
127
+ threading.Thread(target=session._teardown_after_flush, args=(SessionClosedError("handler '{}' raised {}".format(context.callable_name, outcome)),),
128
+ name="rpc-{}-teardown-{}".format(session.role, session._short), daemon=True).start()
129
+ raise
113
130
  finally:
114
131
  self._log_outcome(session, code, context, time.monotonic() - started, outcome)
115
132
  return
116
133
 
134
+ @staticmethod
135
+ def _report_failure(session, message, context, code, notify, err: BaseException) -> None:
136
+ """
137
+ Sends ``err`` back to the caller as the exception reply of ``message``, or logs it for a one-way request.
138
+
139
+ :param session: The session the request arrived on.
140
+ :param message: The request message.
141
+ :param context: The call context of the request.
142
+ :param code: The request code.
143
+ :param notify: True for a one-way request, which gets no reply.
144
+ :param err: The error the request ended with.
145
+ """
146
+ if notify:
147
+ session.logger.warning("one-way request %s '%s' raised: %s", RequestCode(code).name, context.callable_name, err)
148
+ return
149
+ exc_code = {UnknownReferenceError: ExceptionCode.UNKNOWN_REFERENCE, LeaseExpiredError: ExceptionCode.LEASE_EXPIRED,
150
+ CancelledError: ExceptionCode.CANCELLED, ProtocolError: ExceptionCode.PROTOCOL_ERROR,
151
+ UnauthorizedError: ExceptionCode.UNAUTHORIZED}.get(type(err), ExceptionCode.REMOTE_EXCEPTION)
152
+ try:
153
+ session.send_exception(ExceptionMessage.from_exception(err, code=exc_code, correlation_id=message.correlation_id))
154
+ except Exception: # noqa: BLE001
155
+ session.logger.exception("could not send exception reply for %s", context.callable_name)
156
+ return
157
+
117
158
  @staticmethod
118
159
  def _log_outcome(session, code, context, duration, outcome) -> None:
119
160
  pattern = session.aspects.logging_pattern
@@ -58,6 +58,7 @@ class HeartbeatMonitor:
58
58
  session.send_notification(RequestPing())
59
59
  except Exception: # noqa: BLE001
60
60
  pass
61
+ session.expire_overdue_futures()
61
62
  if now - self._last_sweep >= aspects.lease_duration / 2:
62
63
  self._last_sweep = now
63
64
  session.sweep_leases()
@@ -70,7 +71,7 @@ class HeartbeatMonitor:
70
71
  def _renew(self, ref_ids) -> None:
71
72
  session = self._session
72
73
  try:
73
- future = session.send_request_async(RequestRenew(ref_ids=tuple(ref_ids)))
74
+ future = session.send_request_async(RequestRenew(ref_ids=tuple(ref_ids)), timeout=session.aspects.completion_timeout)
74
75
  except Exception: # noqa: BLE001
75
76
  return
76
77
 
@@ -10,17 +10,18 @@ __author__ = "Myron Walker"
10
10
  __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
11
  __credits__ = []
12
12
 
13
+ from typing import Optional
14
+
13
15
  import threading
14
- import time
15
16
 
16
- from ccai.rpc.errors import ProtocolError, UnauthorizedError
17
+ from ccai.rpc.errors import ConnectionTimeout, ProtocolError, UnauthorizedError
17
18
  from ccai.rpc.core.protocol.constants import MIN_SUPPORTED_VERSION, PROTOCOL_VERSION, ExceptionCode, RequestCode
18
19
  from ccai.rpc.core.protocol.header import MessageHeader
19
20
  from ccai.rpc.core.protocol.messages import ExceptionMessage, Message, ReplyHello
20
- from ccai.rpc.core.session.base import DuplexSessionBase
21
+ from ccai.rpc.core.session.base import TEARDOWN_FLUSH_SECONDS, DuplexSessionBase
21
22
 
22
23
  # How long a refused session waits for its exception reply to leave the outbound queue before the transport closes.
23
- REFUSAL_FLUSH_SECONDS = 0.5
24
+ REFUSAL_FLUSH_SECONDS = TEARDOWN_FLUSH_SECONDS
24
25
 
25
26
 
26
27
  class DuplexServerSession(DuplexSessionBase):
@@ -28,15 +29,52 @@ class DuplexServerSession(DuplexSessionBase):
28
29
  The server end of a connection. No request other than HELLO or PING is dispatched until the peer has
29
30
  completed HELLO (and passed the authenticator, when one is configured). A request before HELLO, a rejected
30
31
  credential, a failed version negotiation or a repeated HELLO is answered with an exception reply, and the
31
- session stops reading frames and tears itself down.
32
+ session stops reading frames and tears itself down. A peer that has not completed HELLO within the
33
+ aspects' ``connection_timeout`` is disconnected.
32
34
  """
33
35
 
34
36
  role = "server"
35
37
 
36
- def __init__(self, *args, on_hello=None, **kwargs) -> None:
38
+ def __init__(self, *args, on_hello=None, post_hello_max_message_size: Optional[int] = None, **kwargs) -> None:
39
+ """
40
+ :param on_hello: Called on a dispatch worker with this session once HELLO has completed.
41
+ :param post_hello_max_message_size: When given, the transport's ``max_message_size`` is raised to this
42
+ value as HELLO completes, so a small limit can apply before it.
43
+ """
37
44
  super().__init__(*args, **kwargs)
38
45
  self._on_hello = on_hello
46
+ self._post_hello_max_message_size = post_hello_max_message_size
39
47
  self.hello_done = threading.Event()
48
+ self._hello_timer: Optional[threading.Timer] = None
49
+ return
50
+
51
+ def start(self) -> None:
52
+ super().start()
53
+ timeout = self._aspects.connection_timeout
54
+ self._hello_timer = threading.Timer(timeout, self._hello_deadline_passed, args=(timeout,))
55
+ self._hello_timer.name = "rpc-{}-hello-deadline-{}".format(self.role, self._short)
56
+ self._hello_timer.daemon = True
57
+ self._hello_timer.start()
58
+ return
59
+
60
+ def _hello_deadline_passed(self, timeout: float) -> None:
61
+ """
62
+ Runs when ``connection_timeout`` has passed since the session started: disconnects a peer that has not
63
+ completed HELLO.
64
+
65
+ :param timeout: The HELLO deadline in seconds, for the log and the close reason.
66
+ """
67
+ if self.hello_done.is_set() or self._closing or self._closed:
68
+ return
69
+ self.logger.warning("disconnecting %s: no HELLO within %ss", self.remote_address, timeout)
70
+ self._receive_stopped = True
71
+ self._teardown(ConnectionTimeout("peer {} did not complete HELLO within {}s".format(self.remote_address, timeout)))
72
+ return
73
+
74
+ def _teardown(self, reason: BaseException, timeout: Optional[float] = 5.0) -> None:
75
+ if self._hello_timer is not None and self._hello_timer is not threading.current_thread():
76
+ self._hello_timer.cancel()
77
+ super()._teardown(reason, timeout=timeout)
40
78
  return
41
79
 
42
80
  def _admit_request(self, header: MessageHeader) -> bool:
@@ -74,20 +112,6 @@ class DuplexServerSession(DuplexSessionBase):
74
112
  daemon=True).start()
75
113
  return
76
114
 
77
- def _teardown_after_flush(self, reason: BaseException) -> None:
78
- """
79
- Waits, off the receive thread, for the outbound queue to drain (bounded by REFUSAL_FLUSH_SECONDS) so the
80
- exception reply reaches the peer, then tears the session down.
81
-
82
- :param reason: The close reason recorded by the teardown.
83
- """
84
- deadline = time.monotonic() + REFUSAL_FLUSH_SECONDS
85
- while self._outbound.depth > 0 and time.monotonic() < deadline:
86
- time.sleep(0.01)
87
- time.sleep(0.02) # the transmit thread has popped the last frame; give it time to write it
88
- self._teardown(reason)
89
- return
90
-
91
115
  def _handle_hello_frame(self, frame: bytes, header) -> None:
92
116
  if self.hello_done.is_set():
93
117
  self.logger.warning("refusing a repeated HELLO from %s", self.remote_address)
@@ -120,6 +144,10 @@ class DuplexServerSession(DuplexSessionBase):
120
144
  self.peer_session_id = message.session_id
121
145
  self.peer_context = dict(message.context or {})
122
146
  self.logger.extra["peer_session_id"] = str(self.peer_session_id)
147
+ if self._post_hello_max_message_size is not None:
148
+ self._transport.max_message_size = self._post_hello_max_message_size
149
+ if self._hello_timer is not None:
150
+ self._hello_timer.cancel()
123
151
  self.send_reply(ReplyHello(chosen_version=chosen, session_id=self.session_id, lease_duration=self._aspects.lease_duration,
124
152
  heartbeat_interval=self._aspects.heartbeat_interval, correlation_id=header.correlation_id))
125
153
  self.hello_done.set()
@@ -12,6 +12,7 @@ __credits__ = []
12
12
 
13
13
  from typing import Optional, Tuple
14
14
 
15
+ import selectors
15
16
  import socket
16
17
  import struct
17
18
  import threading
@@ -23,14 +24,28 @@ from ccai.rpc.core.transport.base import Transport, Upgrader
23
24
 
24
25
  RECV_CHUNK = 64 * 1024
25
26
 
27
+ # poll() has no descriptor-number limit and needs no descriptor of its own; Windows has only select().
28
+ _ReadinessSelector = getattr(selectors, "PollSelector", selectors.SelectSelector)
29
+
26
30
 
27
31
  class DuplexSocketIO(Transport):
32
+ """
33
+ Length-prefixed frames over a connected socket. The socket itself stays blocking: ``receive_timeout``
34
+ only bounds how long ``receive_frame`` waits for the socket to become readable (TimeoutError keeps the
35
+ partial frame), and ``send_frame`` is never bounded by it, so a large frame to a slow reader is delivered
36
+ rather than cut off. A dead peer is detected by the session's heartbeat and inactivity timeout, which
37
+ close the transport and so end a blocked send. ``handshake_timeout`` bounds ``upgrade`` (for example a TLS
38
+ handshake); it defaults to ``receive_timeout``.
39
+ """
28
40
 
29
41
  def __init__(self, sock: socket.socket, receive_timeout: Optional[float] = None,
30
- max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> None:
42
+ max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE, handshake_timeout: Optional[float] = None) -> None:
31
43
  self._sock = sock
32
44
  self._send_lock = threading.Lock()
33
45
  self._max_message_size = max_message_size
46
+ self._receive_timeout = receive_timeout
47
+ self._handshake_timeout = handshake_timeout if handshake_timeout is not None else receive_timeout
48
+ self._selector = None
34
49
  self._open = True
35
50
  self._released = False
36
51
  self._pending = bytearray() # bytes of the frame currently being read, kept across timeouts
@@ -47,7 +62,20 @@ class DuplexSocketIO(Transport):
47
62
  except OSError:
48
63
  self._local = ("", 0)
49
64
  self._remote = ("", 0)
50
- sock.settimeout(receive_timeout)
65
+ sock.settimeout(None)
66
+ return
67
+
68
+ @property
69
+ def max_message_size(self) -> int:
70
+ return self._max_message_size
71
+
72
+ @max_message_size.setter
73
+ def max_message_size(self, value: int) -> None:
74
+ """
75
+ Changes the largest frame accepted from the next frame header on, for example a small limit until the
76
+ peer has completed HELLO.
77
+ """
78
+ self._max_message_size = value
51
79
  return
52
80
 
53
81
  @property
@@ -97,6 +125,8 @@ class DuplexSocketIO(Transport):
97
125
  """
98
126
  while len(self._pending) < needed:
99
127
  want = min(needed - len(self._pending), RECV_CHUNK)
128
+ if self._receive_timeout is not None and not self._wait_readable(self._receive_timeout):
129
+ raise TimeoutError("no data received within the receive timeout")
100
130
  try:
101
131
  chunk = self._sock.recv(want)
102
132
  except socket.timeout:
@@ -111,6 +141,28 @@ class DuplexSocketIO(Transport):
111
141
  self._pending.extend(chunk)
112
142
  return
113
143
 
144
+ def _wait_readable(self, timeout: float) -> bool:
145
+ """
146
+ Waits up to ``timeout`` seconds for the socket to have data to read. A TLS socket may already hold
147
+ decrypted bytes that the descriptor does not show, so those count as readable first.
148
+
149
+ :param timeout: The maximum number of seconds to wait.
150
+
151
+ :returns: True when a recv will find data (or the end of the stream), False on timeout.
152
+ """
153
+ pending = getattr(self._sock, "pending", None)
154
+ if pending is not None and pending() > 0:
155
+ return True
156
+ try:
157
+ if self._selector is None:
158
+ self._selector = _ReadinessSelector()
159
+ self._selector.register(self._sock, selectors.EVENT_READ)
160
+ ready = self._selector.select(timeout)
161
+ except (OSError, ValueError):
162
+ # the socket was closed by another thread; the recv that follows reports it as a closed transport
163
+ return True
164
+ return len(ready) > 0
165
+
114
166
  def close(self) -> None:
115
167
  """
116
168
  Closes the socket. Safe to call more than once, and it always releases the descriptor even when
@@ -120,6 +172,8 @@ class DuplexSocketIO(Transport):
120
172
  if self._released:
121
173
  return
122
174
  self._released = True
175
+ if self._selector is not None:
176
+ self._selector.close()
123
177
  try:
124
178
  self._sock.shutdown(socket.SHUT_RDWR)
125
179
  except OSError:
@@ -135,5 +189,14 @@ class DuplexSocketIO(Transport):
135
189
  return
136
190
 
137
191
  def upgrade(self, upgrader: Upgrader) -> None:
192
+ """
193
+ Replaces the socket with ``upgrader(socket)``, for example a TLS-wrapped socket. The handshake is
194
+ bounded by ``handshake_timeout``; the upgraded socket is left blocking like the original.
195
+ """
196
+ if self._selector is not None:
197
+ self._selector.close()
198
+ self._selector = None
199
+ self._sock.settimeout(self._handshake_timeout)
138
200
  self._sock = upgrader(self._sock)
201
+ self._sock.settimeout(None)
139
202
  return
@@ -78,7 +78,8 @@ class RpcSocketClient(Generic[ServiceProtocol]):
78
78
  if attempt < aspects.max_attempts:
79
79
  time.sleep(aspects.completion_interval)
80
80
  continue
81
- transport = DuplexSocketIO(sock, receive_timeout=0.5, max_message_size=self._max_message_size)
81
+ transport = DuplexSocketIO(sock, receive_timeout=0.5, max_message_size=self._max_message_size,
82
+ handshake_timeout=aspects.connection_timeout)
82
83
  if self._upgrader is not None:
83
84
  self._upgrader(transport)
84
85
  session = DuplexClientSession(transport, aspects=self._aspects, credential=self._credential, context=self._context)
@@ -12,15 +12,17 @@ __credits__ = []
12
12
 
13
13
  from typing import Callable, Dict, Optional, Tuple
14
14
 
15
+ import errno
15
16
  import logging
16
17
  import socket
17
18
  import threading
19
+ import time
18
20
  import uuid
19
21
 
20
22
  from ccai.rpc.aspects import AspectsRpc, DEFAULT_RPC_ASPECTS
21
23
  from ccai.rpc.endpoints import Endpoint, ServiceEndpoint
22
24
  from ccai.rpc.errors import SessionError
23
- from ccai.rpc.core.protocol.constants import DEFAULT_MAX_MESSAGE_SIZE
25
+ from ccai.rpc.core.protocol.constants import DEFAULT_MAX_MESSAGE_SIZE, PRE_HELLO_MAX_MESSAGE_SIZE
24
26
  from ccai.rpc.core.session.server import DuplexServerSession
25
27
  from ccai.rpc.core.transport.base import Transport
26
28
  from ccai.rpc.core.transport.socketio import DuplexSocketIO
@@ -29,14 +31,27 @@ Authenticator = Callable[[bytes, Tuple[str, int]], Optional[str]]
29
31
 
30
32
  _live_servers = set()
31
33
 
34
+ # How long the accept loop pauses after accept() fails while serving; descriptor exhaustion gets a longer pause.
35
+ ACCEPT_RETRY_SECONDS = 0.1
36
+ ACCEPT_RETRY_EXHAUSTED_SECONDS = 0.5
37
+ _DESCRIPTOR_EXHAUSTION = {errno.EMFILE, errno.ENFILE, errno.ENOBUFS, errno.ENOMEM}
38
+
32
39
 
33
40
  class RpcSocketServer:
41
+ """
42
+ Accepts connections and runs one :class:`DuplexServerSession` per connection. Each accepted connection is
43
+ upgraded (when an upgrader is given) on its own thread, bounded by the aspects' ``connection_timeout``;
44
+ the peer must complete HELLO within the same timeout, and frames before HELLO are limited to
45
+ ``PRE_HELLO_MAX_MESSAGE_SIZE``. ``max_sessions``, when given, caps the number of connections being set up
46
+ or served at once; connections beyond it are closed as they are accepted.
47
+ """
34
48
 
35
49
  def __init__(self, service: object, endpoint: Endpoint, backlog: int = 16, aspects: AspectsRpc = DEFAULT_RPC_ASPECTS,
36
50
  upgrader: Optional[Callable[[Transport], None]] = None, authenticator: Optional[Authenticator] = None,
37
51
  on_session: Optional[Callable[[DuplexServerSession], None]] = None,
38
52
  on_session_closed: Optional[Callable[[DuplexServerSession, BaseException], None]] = None,
39
- service_name: Optional[str] = None, max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> None:
53
+ service_name: Optional[str] = None, max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE,
54
+ max_sessions: Optional[int] = None) -> None:
40
55
  self._service = service
41
56
  self._endpoint = (endpoint[0], int(endpoint[1]))
42
57
  self._backlog = backlog
@@ -47,6 +62,8 @@ class RpcSocketServer:
47
62
  self._on_session_closed = on_session_closed
48
63
  self._service_name = service_name or type(service).__name__
49
64
  self._max_message_size = max_message_size
65
+ self._max_sessions = max_sessions
66
+ self._handshaking = 0
50
67
  self._listen_sock: Optional[socket.socket] = None
51
68
  self._bound: Optional[Endpoint] = None
52
69
  self._sessions: Dict[uuid.UUID, DuplexServerSession] = {}
@@ -125,30 +142,76 @@ class RpcSocketServer:
125
142
  return
126
143
 
127
144
  def _accept_loop(self) -> None:
145
+ last_logged = None
128
146
  while self._serving:
129
147
  try:
130
148
  client_sock, addr = self._listen_sock.accept()
131
- except OSError:
149
+ except OSError as err:
150
+ if not self._serving:
151
+ break # stop() closed the listening socket
152
+ # A transient failure (descriptor limit, aborted connection, no buffers) must not end the loop.
153
+ now = time.monotonic()
154
+ if last_logged is None or now - last_logged >= self._aspects.retry_logging_interval:
155
+ last_logged = now
156
+ self.logger.warning("accept() on %s failed, retrying: %s", self._bound, err)
157
+ time.sleep(ACCEPT_RETRY_EXHAUSTED_SECONDS if err.errno in _DESCRIPTOR_EXHAUSTION else ACCEPT_RETRY_SECONDS)
158
+ continue
159
+ if not self._serving:
160
+ self._close_socket(client_sock) # the wake-up connection made by stop()
132
161
  break
133
- try:
134
- self._accept(client_sock, addr)
135
- except Exception: # noqa: BLE001
136
- self.logger.exception("failed to start a session for %s", addr)
137
- try:
138
- client_sock.close()
139
- except OSError:
140
- # Best-effort cleanup; the session start failure was already logged above and a failure
141
- # to close the rejected socket must not stop the accept loop.
142
- pass
162
+ with self._lock:
163
+ in_use = len(self._sessions) + self._handshaking
164
+ refuse = self._max_sessions is not None and in_use >= self._max_sessions
165
+ if not refuse:
166
+ self._handshaking += 1
167
+ if refuse:
168
+ self.logger.warning("refusing connection from %s: %d of max_sessions=%d in use", addr, in_use, self._max_sessions)
169
+ self._close_socket(client_sock)
170
+ continue
171
+ threading.Thread(target=self._handshake, args=(client_sock, addr),
172
+ name="rpc-server-handshake-{}".format(self._bound[1]), daemon=True).start()
173
+ return
174
+
175
+ def _handshake(self, client_sock: socket.socket, addr) -> None:
176
+ """
177
+ Runs on a per-connection thread: upgrades the connection and starts its session, so a slow or silent
178
+ peer never holds up the accept loop.
179
+
180
+ :param client_sock: The accepted socket.
181
+ :param addr: The peer address, for the log.
182
+ """
183
+ try:
184
+ self._accept(client_sock, addr)
185
+ except Exception: # noqa: BLE001
186
+ self.logger.exception("failed to start a session for %s", addr)
187
+ self._close_socket(client_sock)
188
+ finally:
189
+ with self._lock:
190
+ self._handshaking -= 1
191
+ return
192
+
193
+ @staticmethod
194
+ def _close_socket(client_sock: socket.socket) -> None:
195
+ try:
196
+ client_sock.close()
197
+ except OSError:
198
+ # Best-effort cleanup; the reason the connection is dropped was already logged and a failure to
199
+ # close the rejected socket must not stop the accept loop.
200
+ pass
143
201
  return
144
202
 
145
203
  def _accept(self, client_sock: socket.socket, addr) -> None:
146
- transport = DuplexSocketIO(client_sock, receive_timeout=0.5, max_message_size=self._max_message_size)
204
+ transport = DuplexSocketIO(client_sock, receive_timeout=0.5, max_message_size=min(self._max_message_size, PRE_HELLO_MAX_MESSAGE_SIZE),
205
+ handshake_timeout=self._aspects.connection_timeout)
147
206
  if self._upgrader is not None:
148
207
  self._upgrader(transport)
149
208
  session = DuplexServerSession(transport, aspects=self._aspects, service=self._service, authenticator=self._authenticator,
150
- on_closed=self._session_closed, on_hello=self._session_ready)
209
+ on_closed=self._session_closed, on_hello=self._session_ready,
210
+ post_hello_max_message_size=self._max_message_size)
151
211
  with self._lock:
212
+ if not self._serving:
213
+ transport.close()
214
+ return
152
215
  self._sessions[session.session_id] = session
153
216
  session.start()
154
217
  return