codecraftai-python-rpc 1.3.1__py3-none-any.whl → 1.4.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.
@@ -150,6 +150,7 @@ class DuplexSessionBase:
150
150
  self._running = False
151
151
  self._closing = False
152
152
  self._closed = False
153
+ self._receive_stopped = False # set when no further inbound frame may be read
153
154
  self._closed_event = threading.Event()
154
155
  self._close_reason: Optional[BaseException] = None
155
156
  self._waiters: Dict[uuid.UUID, Waiter] = {}
@@ -594,7 +595,7 @@ class DuplexSessionBase:
594
595
  def _receive_loop(self, gate: threading.Event) -> None:
595
596
  gate.set()
596
597
  reason = None
597
- while self._running and not self._closing:
598
+ while self._running and not self._closing and not self._receive_stopped:
598
599
  try:
599
600
  frame = self._transport.receive_frame()
600
601
  except TimeoutError:
@@ -642,9 +643,22 @@ class DuplexSessionBase:
642
643
  if header.mcode == RequestCode.HELLO:
643
644
  self._handle_hello_frame(frame, header)
644
645
  return
646
+ if not self._admit_request(header):
647
+ return
645
648
  self._pool.push_work(frame)
646
649
  return
647
650
 
651
+ def _admit_request(self, header: MessageHeader) -> bool:
652
+ """
653
+ Decides, on the receive thread, whether a request other than HELLO or PING may be dispatched. The
654
+ base session admits every request; the server session admits requests only after a completed HELLO.
655
+
656
+ :param header: The header of the inbound request frame.
657
+
658
+ :returns: True when the frame may be handed to the dispatch pool, False when it was refused.
659
+ """
660
+ return True
661
+
648
662
  def _handle_hello_frame(self, frame: bytes, header: MessageHeader) -> None:
649
663
  raise ProtocolError("unexpected HELLO on a {} session".format(self.role))
650
664
 
@@ -11,14 +11,25 @@ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
11
  __credits__ = []
12
12
 
13
13
  import threading
14
+ import time
14
15
 
15
16
  from ccai.rpc.errors import ProtocolError, UnauthorizedError
16
- from ccai.rpc.core.protocol.constants import MIN_SUPPORTED_VERSION, PROTOCOL_VERSION, ExceptionCode
17
+ from ccai.rpc.core.protocol.constants import MIN_SUPPORTED_VERSION, PROTOCOL_VERSION, ExceptionCode, RequestCode
18
+ from ccai.rpc.core.protocol.header import MessageHeader
17
19
  from ccai.rpc.core.protocol.messages import ExceptionMessage, Message, ReplyHello
18
20
  from ccai.rpc.core.session.base import DuplexSessionBase
19
21
 
22
+ # 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
+
20
25
 
21
26
  class DuplexServerSession(DuplexSessionBase):
27
+ """
28
+ The server end of a connection. No request other than HELLO or PING is dispatched until the peer has
29
+ completed HELLO (and passed the authenticator, when one is configured). A request before HELLO, a rejected
30
+ 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
+ """
22
33
 
23
34
  role = "server"
24
35
 
@@ -28,13 +39,66 @@ class DuplexServerSession(DuplexSessionBase):
28
39
  self.hello_done = threading.Event()
29
40
  return
30
41
 
42
+ def _admit_request(self, header: MessageHeader) -> bool:
43
+ """
44
+ Admits a request only after a completed HELLO; otherwise answers it with UNAUTHORIZED and closes the
45
+ session.
46
+
47
+ :param header: The header of the inbound request frame.
48
+
49
+ :returns: True when the frame may be handed to the dispatch pool, False when it was refused.
50
+ """
51
+ if self.hello_done.is_set():
52
+ return True
53
+ code_name = RequestCode(header.mcode).name if header.mcode in RequestCode._value2member_map_ else str(header.mcode)
54
+ self.logger.warning("refusing %s from %s: the peer has not completed HELLO", code_name, self.remote_address)
55
+ self._refuse_and_close(header, ExceptionCode.UNAUTHORIZED, "UnauthorizedError",
56
+ "HELLO must complete before {}".format(code_name),
57
+ UnauthorizedError("peer {} sent {} before completing HELLO".format(self.remote_address, code_name)))
58
+ return False
59
+
60
+ def _refuse_and_close(self, header: MessageHeader, code: ExceptionCode, type_name: str, text: str, reason: BaseException) -> None:
61
+ """
62
+ Stops the receive loop before it reads another frame, answers the offending request with an exception
63
+ reply and tears the session down once that reply has been handed to the transport.
64
+
65
+ :param header: The header of the refused request, whose correlation id the exception reply carries.
66
+ :param code: The exception code of the reply.
67
+ :param type_name: The exception type name carried in the reply.
68
+ :param text: The exception message carried in the reply.
69
+ :param reason: The close reason recorded by the teardown.
70
+ """
71
+ self._receive_stopped = True
72
+ self.send_exception(ExceptionMessage(code=int(code), type_name=type_name, message=text, correlation_id=header.correlation_id))
73
+ threading.Thread(target=self._teardown_after_flush, args=(reason,), name="rpc-{}-refuse-{}".format(self.role, self._short),
74
+ daemon=True).start()
75
+ return
76
+
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
+
31
91
  def _handle_hello_frame(self, frame: bytes, header) -> None:
92
+ if self.hello_done.is_set():
93
+ self.logger.warning("refusing a repeated HELLO from %s", self.remote_address)
94
+ self._refuse_and_close(header, ExceptionCode.PROTOCOL_ERROR, "ProtocolError", "HELLO was already completed on this session",
95
+ ProtocolError("peer {} sent a second HELLO".format(self.remote_address)))
96
+ return
32
97
  message = Message.unpack(frame)
33
98
  chosen = min(message.version_max, PROTOCOL_VERSION)
34
99
  if chosen < max(message.version_min, MIN_SUPPORTED_VERSION):
35
- self.send_exception(ExceptionMessage(code=int(ExceptionCode.PROTOCOL_ERROR), type_name="ProtocolError",
36
- message="no common protocol version", correlation_id=header.correlation_id))
37
- threading.Thread(target=self._teardown, args=(ProtocolError("no common protocol version with peer"),), daemon=True).start()
100
+ self._refuse_and_close(header, ExceptionCode.PROTOCOL_ERROR, "ProtocolError", "no common protocol version",
101
+ ProtocolError("no common protocol version with peer"))
38
102
  return
39
103
  if self._authenticator is not None:
40
104
  identity = None
@@ -44,11 +108,8 @@ class DuplexServerSession(DuplexSessionBase):
44
108
  self.logger.warning("authentication raised for %s: %s", self.remote_address, err)
45
109
  if identity is None:
46
110
  self.logger.warning("authentication failed for %s", self.remote_address)
47
- self.send_exception(ExceptionMessage(code=int(ExceptionCode.UNAUTHORIZED), type_name="UnauthorizedError",
48
- message="credential rejected", correlation_id=header.correlation_id))
49
- import time
50
- time.sleep(0.05)
51
- threading.Thread(target=self._teardown, args=(UnauthorizedError("peer {} failed authentication".format(self.remote_address)),), daemon=True).start()
111
+ self._refuse_and_close(header, ExceptionCode.UNAUTHORIZED, "UnauthorizedError", "credential rejected",
112
+ UnauthorizedError("peer {} failed authentication".format(self.remote_address)))
52
113
  return
53
114
  self.peer_identity = identity
54
115
  self.logger.info("authenticated %s as %s", self.remote_address, identity)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codecraftai-python-rpc
3
- Version: 1.3.1
3
+ Version: 1.4.0
4
4
  Summary: Code Craft AI - Python RPC Package
5
5
  License-Expression: LicenseRef-CodeCraftAI-Source-Available
6
6
  License-File: LICENSE.md
@@ -29,11 +29,11 @@ ccai/rpc/core/serialization/placeholder.py,sha256=dsEscTdI2KVxaFvdMOH4Ly7VrGbMDo
29
29
  ccai/rpc/core/serialization/registry.py,sha256=jI2nz5J17bibYxiQpKldNt0_CV7sfwJ0Ie-n2x3W-yk,2433
30
30
  ccai/rpc/core/serialization/tags.py,sha256=u_VhyisLge9EGetyWxcFKIzQu5-BxA8X2GShL9-pcLw,677
31
31
  ccai/rpc/core/session/__init__.py,sha256=xvgS2D1eTcCudaQbLIS4PZ0Oe5lJ7f6qxYKO53iKUGQ,373
32
- ccai/rpc/core/session/base.py,sha256=sJOOqZBnpC8KrwVuKwfIDphHN8g229xaIkSz4z36ViU,31399
32
+ ccai/rpc/core/session/base.py,sha256=EOjqSJ3GtIgYdPOBIt9ZXXkpz8r64xRgsiu5ZwqPx2E,32105
33
33
  ccai/rpc/core/session/client.py,sha256=vqADvyM0H_q53stS7hfgAXEMnRGOOd4q1-Dmh59mcYQ,2854
34
34
  ccai/rpc/core/session/dispatch.py,sha256=oEBszBDvq-6s9Q1EwYTw0MXZXcycIZwr4ECkj8kT0E4,6914
35
35
  ccai/rpc/core/session/heartbeat.py,sha256=gHCt2p2PSc0N_9vQCMvUfCxerwqrytm9lrQm7HLP7Ew,3915
36
- ccai/rpc/core/session/server.py,sha256=UnIPBLztVSbZrXOiIapFcNkTsRCqmFOJry_6lz437To,3607
36
+ ccai/rpc/core/session/server.py,sha256=eCQ3xj8IwjozLiaCdAAAmtmHR_ZkmnDNcrf2UZ0T79w,7044
37
37
  ccai/rpc/core/transport/__init__.py,sha256=s1SKl1uT5950qLuRujSEnB9sK60kEEupOyySANHDfaw,480
38
38
  ccai/rpc/core/transport/base.py,sha256=wf-JKdGKn2q2sHPRjX_vYcip9rOGwBde76BTQqQ3Z_c,2591
39
39
  ccai/rpc/core/transport/faults.py,sha256=NmVUMIKs364lvY-4MFmAm-NIDQJ3_mYywt4CFgQzbbI,2284
@@ -47,7 +47,7 @@ ccai/rpc/rpcsocketserver.py,sha256=a4ekH1EWXM2z_FH5Pu5hFNfu4v9LKknj3xCZifNyx2c,9
47
47
  ccai/rpc/security/__init__.py,sha256=yNK_sc3V_bpKuZSrrw_gyb10ll6BQmAS1O9NZDWUUbU,524
48
48
  ccai/rpc/security/auth.py,sha256=z7q1QzIhHxTmZvnH4ZI_G2-NUmGzMm8UGkDY0FiyIXc,1108
49
49
  ccai/rpc/security/tls.py,sha256=SFXOa9p8F7PQz_iP6Y3XnHHa1mJTNHGPwyRcFbBS7M0,1890
50
- codecraftai_python_rpc-1.3.1.dist-info/METADATA,sha256=JV4LXJM-tW3pVv5bFfcCXiBV6cgkHvSj-k3oZhbeAhY,4872
51
- codecraftai_python_rpc-1.3.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
52
- codecraftai_python_rpc-1.3.1.dist-info/licenses/LICENSE.md,sha256=5tyUZ2kpPxNXbULzrdiT14-ZV-jCBeBFL0xyO-zt1mg,17907
53
- codecraftai_python_rpc-1.3.1.dist-info/RECORD,,
50
+ codecraftai_python_rpc-1.4.0.dist-info/METADATA,sha256=R7sMKZrWodBP039mYsdN2ub8G5dSaH93QiQTYAtvdG0,4872
51
+ codecraftai_python_rpc-1.4.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
52
+ codecraftai_python_rpc-1.4.0.dist-info/licenses/LICENSE.md,sha256=5tyUZ2kpPxNXbULzrdiT14-ZV-jCBeBFL0xyO-zt1mg,17907
53
+ codecraftai_python_rpc-1.4.0.dist-info/RECORD,,