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,58 @@
1
+ """
2
+ .. module:: client
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: DuplexClientSession: the session that opens with HELLO and exposes get_service.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import Optional
14
+
15
+ from ccai.rpc.errors import ProtocolError, SessionError
16
+ from ccai.rpc.core.protocol.constants import MIN_SUPPORTED_VERSION, PROTOCOL_VERSION
17
+ from ccai.rpc.core.protocol.messages import RequestGetService, RequestHello, RequestPing
18
+ from ccai.rpc.core.session.base import DuplexSessionBase
19
+
20
+
21
+ class DuplexClientSession(DuplexSessionBase):
22
+
23
+ role = "client"
24
+
25
+ def start(self, hello_timeout: Optional[float] = None) -> None:
26
+ super().start()
27
+ timeout = hello_timeout if hello_timeout is not None else self._aspects.connection_timeout
28
+ hello = RequestHello(version_min=MIN_SUPPORTED_VERSION, version_max=PROTOCOL_VERSION, session_id=self.session_id,
29
+ credential=self._credential, context=self._context)
30
+ try:
31
+ reply = self.send_request(hello, timeout=timeout)
32
+ except BaseException as err:
33
+ self._teardown(SessionError("HELLO failed: {}".format(err)))
34
+ raise
35
+ if not (MIN_SUPPORTED_VERSION <= reply.chosen_version <= PROTOCOL_VERSION):
36
+ self._teardown(ProtocolError("server chose unsupported protocol version {}".format(reply.chosen_version)))
37
+ raise ProtocolError("server chose unsupported protocol version {}".format(reply.chosen_version))
38
+ self.protocol_version = reply.chosen_version
39
+ self.peer_session_id = reply.session_id
40
+ self.lease_duration = reply.lease_duration
41
+ self.renewal_interval = min(self._aspects.heartbeat_interval, reply.lease_duration / 3.0)
42
+ self.logger.extra["peer_session_id"] = str(self.peer_session_id)
43
+ self.logger.info("HELLO complete: protocol %s, server session %s, lease %ss", self.protocol_version, self.peer_session_id, self.lease_duration)
44
+ return
45
+
46
+ def get_service(self, protocol: Optional[type] = None, aspects=None):
47
+ reply = self.send_request(RequestGetService(), timeout=self.resolve_aspects(aspects).completion_timeout)
48
+ proxy = reply.value
49
+ if protocol is not None or aspects is not None:
50
+ proxy = proxy.rpc_with_protocol(protocol) if protocol is not None else proxy
51
+ proxy = proxy.rpc_with_aspects(aspects) if aspects is not None else proxy
52
+ return proxy
53
+
54
+ def ping(self, timeout: Optional[float] = None) -> float:
55
+ import time
56
+ started = time.monotonic()
57
+ self.send_request(RequestPing(), timeout=timeout if timeout is not None else self._aspects.connection_timeout)
58
+ return time.monotonic() - started
@@ -0,0 +1,124 @@
1
+ """
2
+ .. module:: dispatch
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: DispatchLooper, the pool worker that decodes an inbound request, runs its handler under a call
5
+ context and per-target ordering, and answers with a reply or an exception message.
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
+ import time
15
+
16
+ from ccai.rpc.aspects import LoggingPattern
17
+ from ccai.rpc.errors import CancelledError, LeaseExpiredError, ProtocolError, UnauthorizedError, UnknownReferenceError
18
+ from ccai.rpc.core.dispatch.context import CallContext, set_call_context
19
+ from ccai.rpc.core.looper import Looper
20
+ from ccai.rpc.core.protocol.constants import ExceptionCode, RequestCode
21
+ from ccai.rpc.core.protocol.messages import ExceptionMessage, Message
22
+ from ccai.rpc.core.proxy.wrappers import CONCURRENT_MARKER
23
+
24
+ _TARGETED = (int(RequestCode.CALL), int(RequestCode.GETATTR), int(RequestCode.SETATTR), int(RequestCode.DELATTR))
25
+
26
+
27
+ class DispatchLooper(Looper):
28
+
29
+ def __init__(self, queue, name=None, group=None, daemon=None, session=None, **kwargs) -> None:
30
+ super().__init__(queue, name=name, group=group, daemon=daemon, **kwargs)
31
+ self._session = session
32
+ return
33
+
34
+ def loop(self, packet) -> None:
35
+ if callable(packet):
36
+ packet()
37
+ return
38
+ session = self._session
39
+ try:
40
+ message = Message.unpack(packet, resolver=session.resolve_reference)
41
+ except Exception as err: # noqa: BLE001
42
+ session.logger.warning("could not decode inbound request: %s", err)
43
+ try:
44
+ from ccai.rpc.core.protocol.header import MessageHeader
45
+ header = MessageHeader.unpack(packet)
46
+ session.send_exception(ExceptionMessage(code=int(ExceptionCode.PROTOCOL_ERROR), type_name="ProtocolError",
47
+ message=str(err), correlation_id=header.correlation_id))
48
+ except Exception: # noqa: BLE001
49
+ pass
50
+ return
51
+ code = int(message.mcode)
52
+ target_ref = getattr(message, "target_ref", None)
53
+ lane = None
54
+ # Ordering lanes apply to one-way callbacks only. An acknowledged call already serialises its caller,
55
+ # and a lane on an acknowledged call would deadlock a re-entrant chain that targets the same object.
56
+ if code in _TARGETED and target_ref is not None and getattr(message, "notify", False):
57
+ try:
58
+ obj = session.table.resolve(target_ref)
59
+ if not getattr(type(obj), CONCURRENT_MARKER, False):
60
+ lane = session.lane_for(target_ref)
61
+ except Exception: # noqa: BLE001 - the handler reports the missing reference
62
+ lane = None
63
+ work = lambda: self._execute(session, message) # noqa: E731
64
+ if lane is not None:
65
+ lane.run(work)
66
+ else:
67
+ work()
68
+ return
69
+
70
+ def _execute(self, session, message) -> None:
71
+ code = int(message.mcode)
72
+ notify = bool(getattr(message, "notify", False)) or code in (int(RequestCode.CANCEL), int(RequestCode.PROGRESS), int(RequestCode.CLOSE))
73
+ deadline_remaining = getattr(message, "deadline", None)
74
+ deadline = time.monotonic() + deadline_remaining if deadline_remaining is not None else None
75
+ context = CallContext(session, message.correlation_id, session.peer_session_id, getattr(message, "target_ref", None),
76
+ getattr(message, "callable_name", None) or getattr(message, "name", None) or RequestCode(code).name,
77
+ deadline, caller_context={**session.peer_context, **(getattr(message, "context", None) or {})}, notify=notify)
78
+ handler = session.handler_for(code)
79
+ started = time.monotonic()
80
+ outcome = "ok"
81
+ try:
82
+ if handler is None:
83
+ raise ProtocolError("no handler for request code {}".format(RequestCode(code).name))
84
+ if deadline is not None and deadline_remaining <= 0:
85
+ raise CancelledError("deadline of call '{}' had already passed when it was received".format(context.callable_name))
86
+ session.track_call(context)
87
+ set_call_context(context)
88
+ try:
89
+ reply = handler(session, message, context)
90
+ finally:
91
+ set_call_context(None)
92
+ session.untrack_call(context)
93
+ if context.is_cancelled and code in _TARGETED:
94
+ raise CancelledError("call '{}' was cancelled".format(context.callable_name))
95
+ if reply is not None and not notify:
96
+ reply.correlation_id = message.correlation_id
97
+ session.send_reply(reply)
98
+ except Exception as err: # noqa: BLE001 - every failure travels back as an exception message
99
+ outcome = type(err).__name__
100
+ if isinstance(err, (UnknownReferenceError, LeaseExpiredError)) or (isinstance(err, AttributeError) and "refused" in str(err)):
101
+ session.logger.warning("refused %s '%s' from %s (%s): %s", RequestCode(code).name, context.callable_name,
102
+ 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
+ finally:
114
+ self._log_outcome(session, code, context, time.monotonic() - started, outcome)
115
+ return
116
+
117
+ @staticmethod
118
+ def _log_outcome(session, code, context, duration, outcome) -> None:
119
+ pattern = session.aspects.logging_pattern
120
+ failed = outcome != "ok"
121
+ if pattern == LoggingPattern.ALL_RESULTS or (failed and pattern == LoggingPattern.FAILURE_ONLY) or (not failed and pattern == LoggingPattern.SUCCESS_ONLY):
122
+ session.logger.info("%s %s target=%s caller=%s %.3fs %s", RequestCode(code).name, context.callable_name,
123
+ context.target_ref, context.caller_session_id, duration, outcome)
124
+ return
@@ -0,0 +1,96 @@
1
+ """
2
+ .. module:: heartbeat
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The per-session timer thread: idle pings, lease renewals, dead-peer detection and lease sweeps.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ import threading
14
+ import time
15
+
16
+ from ccai.rpc.errors import InActivityTimeout
17
+ from ccai.rpc.core.protocol.messages import RequestPing, RequestRenew
18
+
19
+
20
+ class HeartbeatMonitor:
21
+
22
+ def __init__(self, session) -> None:
23
+ self._session = session
24
+ self._stop = threading.Event()
25
+ self._thread = None
26
+ self._last_sweep = time.monotonic()
27
+ self._warned_calls = set()
28
+ return
29
+
30
+ def start(self) -> None:
31
+ self._thread = threading.Thread(target=self._run, name="rpc-{}-heartbeat-{}".format(self._session.role, self._session._short), daemon=True)
32
+ self._thread.start()
33
+ return
34
+
35
+ def stop(self) -> None:
36
+ self._stop.set()
37
+ return
38
+
39
+ def tick(self) -> None:
40
+ session = self._session
41
+ aspects = session.aspects
42
+ now = time.monotonic()
43
+ if not session.is_running:
44
+ return
45
+ if now - session.last_received_at > aspects.inactivity_timeout:
46
+ session.logger.warning("no frame received for %.1fs, treating peer %s as dead", now - session.last_received_at, session.peer_session_id)
47
+ threading.Thread(target=session._teardown, args=(InActivityTimeout("no frame received from peer {} for {:.1f}s".format(
48
+ session.peer_session_id, now - session.last_received_at)),), name="rpc-{}-teardown-{}".format(session.role, session._short), daemon=True).start()
49
+ return
50
+ from ccai.rpc.core.proxy.table import ROOT_REFERENCE_ID
51
+ live = [ref_id for ref_id in session.proxies.live_ids() if ref_id != ROOT_REFERENCE_ID]
52
+ interval = min(aspects.heartbeat_interval, session.renewal_interval) if live else aspects.heartbeat_interval
53
+ if live and now - getattr(self, "_last_renew", 0.0) >= interval:
54
+ self._last_renew = now
55
+ self._renew(live)
56
+ elif now - session.last_sent_at >= aspects.heartbeat_interval:
57
+ try:
58
+ session.send_notification(RequestPing())
59
+ except Exception: # noqa: BLE001
60
+ pass
61
+ if now - self._last_sweep >= aspects.lease_duration / 2:
62
+ self._last_sweep = now
63
+ session.sweep_leases()
64
+ for context in list(session._active_calls.values()):
65
+ if context.elapsed > aspects.completion_timeout and context.correlation_id not in self._warned_calls:
66
+ self._warned_calls.add(context.correlation_id)
67
+ session.logger.warning("callback '%s' has been running for %.1fs, longer than completion_timeout", context.callable_name, context.elapsed)
68
+ return
69
+
70
+ def _renew(self, ref_ids) -> None:
71
+ session = self._session
72
+ try:
73
+ future = session.send_request_async(RequestRenew(ref_ids=tuple(ref_ids)))
74
+ except Exception: # noqa: BLE001
75
+ return
76
+
77
+ def on_done(fut):
78
+ try:
79
+ reply = fut.result(timeout=0)
80
+ except Exception: # noqa: BLE001
81
+ return
82
+ for ref_id in reply.unknown:
83
+ proxy = session.proxies.get(ref_id)
84
+ if proxy is not None:
85
+ proxy.rpc_mark_expired()
86
+ future.add_done_callback(on_done)
87
+ return
88
+
89
+ def _run(self) -> None:
90
+ period = max(0.05, min(self._session.aspects.heartbeat_interval, self._session.renewal_interval) / 4)
91
+ while not self._stop.wait(timeout=period):
92
+ try:
93
+ self.tick()
94
+ except Exception: # noqa: BLE001
95
+ self._session.logger.exception("heartbeat tick failed")
96
+ return
@@ -0,0 +1,68 @@
1
+ """
2
+ .. module:: server
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: DuplexServerSession: the session that answers HELLO, authenticating the peer first.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ import threading
14
+
15
+ 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.messages import ExceptionMessage, Message, ReplyHello
18
+ from ccai.rpc.core.session.base import DuplexSessionBase
19
+
20
+
21
+ class DuplexServerSession(DuplexSessionBase):
22
+
23
+ role = "server"
24
+
25
+ def __init__(self, *args, on_hello=None, **kwargs) -> None:
26
+ super().__init__(*args, **kwargs)
27
+ self._on_hello = on_hello
28
+ self.hello_done = threading.Event()
29
+ return
30
+
31
+ def _handle_hello_frame(self, frame: bytes, header) -> None:
32
+ message = Message.unpack(frame)
33
+ chosen = min(message.version_max, PROTOCOL_VERSION)
34
+ 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()
38
+ return
39
+ if self._authenticator is not None:
40
+ identity = None
41
+ try:
42
+ identity = self._authenticator(message.credential or b"", self.remote_address)
43
+ except Exception as err: # noqa: BLE001
44
+ self.logger.warning("authentication raised for %s: %s", self.remote_address, err)
45
+ if identity is None:
46
+ 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()
52
+ return
53
+ self.peer_identity = identity
54
+ self.logger.info("authenticated %s as %s", self.remote_address, identity)
55
+ elif getattr(self._transport, "peer_identity", None):
56
+ self.peer_identity = getattr(self._transport, "peer_identity")
57
+ self.logger.info("authenticated %s by client certificate as %s", self.remote_address, self.peer_identity)
58
+ self.protocol_version = chosen
59
+ self.peer_session_id = message.session_id
60
+ self.peer_context = dict(message.context or {})
61
+ self.logger.extra["peer_session_id"] = str(self.peer_session_id)
62
+ self.send_reply(ReplyHello(chosen_version=chosen, session_id=self.session_id, lease_duration=self._aspects.lease_duration,
63
+ heartbeat_interval=self._aspects.heartbeat_interval, correlation_id=header.correlation_id))
64
+ self.hello_done.set()
65
+ self.logger.info("HELLO complete: protocol %s, client session %s", chosen, self.peer_session_id)
66
+ if self._on_hello is not None:
67
+ self._pool.push_work(lambda: self._on_hello(self))
68
+ return
@@ -0,0 +1,10 @@
1
+ """
2
+ Transports move whole frames between two endpoints.
3
+ """
4
+
5
+ from ccai.rpc.core.transport.base import Transport, TransportWrapper, Upgrader
6
+ from ccai.rpc.core.transport.faults import FaultInjectingTransport
7
+ from ccai.rpc.core.transport.inprocess import create_socketpair_transports
8
+ from ccai.rpc.core.transport.socketio import DuplexSocketIO
9
+
10
+ __all__ = ["Transport", "TransportWrapper", "Upgrader", "FaultInjectingTransport", "create_socketpair_transports", "DuplexSocketIO"]
@@ -0,0 +1,91 @@
1
+ """
2
+ .. module:: base
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Transport interface sessions program against, and the forwarding TransportWrapper.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import Callable, Tuple
14
+
15
+ import socket
16
+
17
+ from ccai.rpc.errors import AbstractMethodError
18
+
19
+ Upgrader = Callable[[socket.socket], socket.socket]
20
+
21
+
22
+ class Transport:
23
+ """
24
+ Moves whole frames between two endpoints. ``receive_frame`` blocks until a full frame is available
25
+ or the transport is closed; concurrent ``send_frame`` calls are serialised by the implementation.
26
+ """
27
+
28
+ @property
29
+ def local_address(self) -> Tuple[str, int]:
30
+ raise AbstractMethodError("Transport.local_address must be implemented")
31
+
32
+ @property
33
+ def remote_address(self) -> Tuple[str, int]:
34
+ raise AbstractMethodError("Transport.remote_address must be implemented")
35
+
36
+ @property
37
+ def is_open(self) -> bool:
38
+ raise AbstractMethodError("Transport.is_open must be implemented")
39
+
40
+ def send_frame(self, message: bytes) -> None:
41
+ raise AbstractMethodError("Transport.send_frame must be implemented")
42
+
43
+ def receive_frame(self) -> bytes:
44
+ raise AbstractMethodError("Transport.receive_frame must be implemented")
45
+
46
+ def close(self) -> None:
47
+ raise AbstractMethodError("Transport.close must be implemented")
48
+
49
+ def upgrade(self, upgrader: Upgrader) -> None:
50
+ raise AbstractMethodError("Transport.upgrade must be implemented")
51
+
52
+
53
+ class TransportWrapper(Transport):
54
+ """
55
+ Forwards every operation to an inner transport. Subclasses override what they change.
56
+ """
57
+
58
+ def __init__(self, inner: Transport) -> None:
59
+ self._inner = inner
60
+ return
61
+
62
+ @property
63
+ def inner(self) -> Transport:
64
+ return self._inner
65
+
66
+ @property
67
+ def local_address(self) -> Tuple[str, int]:
68
+ return self._inner.local_address
69
+
70
+ @property
71
+ def remote_address(self) -> Tuple[str, int]:
72
+ return self._inner.remote_address
73
+
74
+ @property
75
+ def is_open(self) -> bool:
76
+ return self._inner.is_open
77
+
78
+ def send_frame(self, message: bytes) -> None:
79
+ self._inner.send_frame(message)
80
+ return
81
+
82
+ def receive_frame(self) -> bytes:
83
+ return self._inner.receive_frame()
84
+
85
+ def close(self) -> None:
86
+ self._inner.close()
87
+ return
88
+
89
+ def upgrade(self, upgrader: Upgrader) -> None:
90
+ self._inner.upgrade(upgrader)
91
+ return
@@ -0,0 +1,81 @@
1
+ """
2
+ .. module:: faults
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: A transport wrapper that drops, delays, truncates or closes on command, for failure-path tests.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import List
14
+
15
+ import threading
16
+ import time
17
+
18
+ from ccai.rpc.core.transport.base import Transport, TransportWrapper
19
+
20
+
21
+ class FaultInjectingTransport(TransportWrapper):
22
+
23
+ def __init__(self, inner: Transport) -> None:
24
+ super().__init__(inner)
25
+ self._lock = threading.Lock()
26
+ self._drop = 0
27
+ self._delay = 0.0
28
+ self._truncate = 0
29
+ self._close_after = None
30
+ self._sent = 0
31
+ self._actions: List[str] = []
32
+ return
33
+
34
+ @property
35
+ def actions(self) -> List[str]:
36
+ with self._lock:
37
+ return list(self._actions)
38
+
39
+ def drop_next(self, count: int) -> None:
40
+ with self._lock:
41
+ self._drop = count
42
+ return
43
+
44
+ def delay_frames(self, seconds: float) -> None:
45
+ with self._lock:
46
+ self._delay = seconds
47
+ return
48
+
49
+ def truncate_next(self, count: int = 1) -> None:
50
+ with self._lock:
51
+ self._truncate = count
52
+ return
53
+
54
+ def close_after(self, count: int) -> None:
55
+ with self._lock:
56
+ self._close_after = count
57
+ return
58
+
59
+ def send_frame(self, message: bytes) -> None:
60
+ with self._lock:
61
+ if self._drop > 0:
62
+ self._drop -= 1
63
+ self._actions.append("dropped")
64
+ return
65
+ delay = self._delay
66
+ truncate = self._truncate > 0
67
+ if truncate:
68
+ self._truncate -= 1
69
+ self._sent += 1
70
+ close_now = self._close_after is not None and self._sent >= self._close_after
71
+ if delay:
72
+ self._actions.append("delayed {}s".format(delay))
73
+ time.sleep(delay)
74
+ if truncate:
75
+ self._actions.append("truncated")
76
+ message = message[: max(1, len(message) // 2)]
77
+ self._inner.send_frame(message)
78
+ if close_now:
79
+ self._actions.append("closed")
80
+ self._inner.close()
81
+ return
@@ -0,0 +1,22 @@
1
+ """
2
+ .. module:: inprocess
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Two connected transports in one process, for testing the full stack without a network.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import Optional, Tuple
14
+
15
+ import socket
16
+
17
+ from ccai.rpc.core.transport.socketio import DuplexSocketIO
18
+
19
+
20
+ def create_socketpair_transports(receive_timeout: Optional[float] = None) -> Tuple[DuplexSocketIO, DuplexSocketIO]:
21
+ left, right = socket.socketpair()
22
+ return DuplexSocketIO(left, receive_timeout=receive_timeout), DuplexSocketIO(right, receive_timeout=receive_timeout)