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.
- ccai/rpc/__init__.py +33 -0
- ccai/rpc/aspects.py +145 -0
- ccai/rpc/core/__init__.py +0 -0
- ccai/rpc/core/dispatch/__init__.py +0 -0
- ccai/rpc/core/dispatch/context.py +115 -0
- ccai/rpc/core/dispatch/lanes.py +77 -0
- ccai/rpc/core/flattenable.py +30 -0
- ccai/rpc/core/futures.py +168 -0
- ccai/rpc/core/leases.py +35 -0
- ccai/rpc/core/looper.py +107 -0
- ccai/rpc/core/looperpool.py +136 -0
- ccai/rpc/core/looperqueue.py +103 -0
- ccai/rpc/core/observability/__init__.py +10 -0
- ccai/rpc/core/observability/metrics.py +26 -0
- ccai/rpc/core/observability/state.py +51 -0
- ccai/rpc/core/protocol/__init__.py +16 -0
- ccai/rpc/core/protocol/constants.py +64 -0
- ccai/rpc/core/protocol/header.py +66 -0
- ccai/rpc/core/protocol/messages.py +265 -0
- ccai/rpc/core/proxy/__init__.py +0 -0
- ccai/rpc/core/proxy/cache.py +48 -0
- ccai/rpc/core/proxy/handlers.py +101 -0
- ccai/rpc/core/proxy/remoteproxy.py +251 -0
- ccai/rpc/core/proxy/table.py +207 -0
- ccai/rpc/core/proxy/wrappers.py +127 -0
- ccai/rpc/core/serialization/__init__.py +13 -0
- ccai/rpc/core/serialization/codec.py +371 -0
- ccai/rpc/core/serialization/placeholder.py +25 -0
- ccai/rpc/core/serialization/registry.py +85 -0
- ccai/rpc/core/serialization/tags.py +39 -0
- ccai/rpc/core/session/__init__.py +9 -0
- ccai/rpc/core/session/base.py +698 -0
- ccai/rpc/core/session/client.py +58 -0
- ccai/rpc/core/session/dispatch.py +124 -0
- ccai/rpc/core/session/heartbeat.py +96 -0
- ccai/rpc/core/session/server.py +68 -0
- ccai/rpc/core/transport/__init__.py +10 -0
- ccai/rpc/core/transport/base.py +91 -0
- ccai/rpc/core/transport/faults.py +81 -0
- ccai/rpc/core/transport/inprocess.py +22 -0
- ccai/rpc/core/transport/socketio.py +139 -0
- ccai/rpc/endpoints.py +44 -0
- ccai/rpc/errors.py +100 -0
- ccai/rpc/py.typed +0 -0
- ccai/rpc/rpcsocketclient.py +126 -0
- ccai/rpc/rpcsocketserver.py +226 -0
- ccai/rpc/security/__init__.py +10 -0
- ccai/rpc/security/auth.py +34 -0
- ccai/rpc/security/tls.py +53 -0
- codecraftai_python_rpc-1.3.0.dist-info/METADATA +105 -0
- codecraftai_python_rpc-1.3.0.dist-info/RECORD +53 -0
- codecraftai_python_rpc-1.3.0.dist-info/WHEEL +4 -0
- codecraftai_python_rpc-1.3.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: socketio
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: DuplexSocketIO, the Transport over a connected socket with complete-read guarantees.
|
|
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
|
+
import struct
|
|
17
|
+
import threading
|
|
18
|
+
|
|
19
|
+
from ccai.rpc.errors import TransportClosedError
|
|
20
|
+
from ccai.rpc.core.protocol.constants import DEFAULT_MAX_MESSAGE_SIZE, FRAME_SIZE_BYTES
|
|
21
|
+
from ccai.rpc.core.protocol.header import read_frame_size
|
|
22
|
+
from ccai.rpc.core.transport.base import Transport, Upgrader
|
|
23
|
+
|
|
24
|
+
RECV_CHUNK = 64 * 1024
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DuplexSocketIO(Transport):
|
|
28
|
+
|
|
29
|
+
def __init__(self, sock: socket.socket, receive_timeout: Optional[float] = None,
|
|
30
|
+
max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> None:
|
|
31
|
+
self._sock = sock
|
|
32
|
+
self._send_lock = threading.Lock()
|
|
33
|
+
self._max_message_size = max_message_size
|
|
34
|
+
self._open = True
|
|
35
|
+
self._released = False
|
|
36
|
+
self._pending = bytearray() # bytes of the frame currently being read, kept across timeouts
|
|
37
|
+
self._pending_size = None
|
|
38
|
+
try:
|
|
39
|
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
40
|
+
except (OSError, AttributeError):
|
|
41
|
+
# TCP_NODELAY is an optional latency optimization; sockets that are not TCP (for example a
|
|
42
|
+
# socketpair) reject it and still work correctly without it.
|
|
43
|
+
pass
|
|
44
|
+
try:
|
|
45
|
+
self._local = sock.getsockname()
|
|
46
|
+
self._remote = sock.getpeername()
|
|
47
|
+
except OSError:
|
|
48
|
+
self._local = ("", 0)
|
|
49
|
+
self._remote = ("", 0)
|
|
50
|
+
sock.settimeout(receive_timeout)
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def sock(self) -> socket.socket:
|
|
55
|
+
return self._sock
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def local_address(self) -> Tuple[str, int]:
|
|
59
|
+
return self._local if isinstance(self._local, tuple) and len(self._local) >= 2 else (str(self._local), 0)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def remote_address(self) -> Tuple[str, int]:
|
|
63
|
+
return self._remote if isinstance(self._remote, tuple) and len(self._remote) >= 2 else (str(self._remote), 0)
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def is_open(self) -> bool:
|
|
67
|
+
return self._open
|
|
68
|
+
|
|
69
|
+
def send_frame(self, message: bytes) -> None:
|
|
70
|
+
if not self._open:
|
|
71
|
+
raise TransportClosedError("send_frame on a closed transport")
|
|
72
|
+
data = struct.pack("!Q", len(message)) + message
|
|
73
|
+
with self._send_lock:
|
|
74
|
+
try:
|
|
75
|
+
self._sock.sendall(data)
|
|
76
|
+
except OSError as err:
|
|
77
|
+
self._open = False
|
|
78
|
+
raise TransportClosedError("send failed: {}".format(err)) from err
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
def receive_frame(self) -> bytes:
|
|
82
|
+
if not self._open:
|
|
83
|
+
raise TransportClosedError("receive_frame on a closed transport")
|
|
84
|
+
if self._pending_size is None:
|
|
85
|
+
self._fill(FRAME_SIZE_BYTES)
|
|
86
|
+
self._pending_size = read_frame_size(bytes(self._pending[:FRAME_SIZE_BYTES]), self._max_message_size)
|
|
87
|
+
del self._pending[:FRAME_SIZE_BYTES]
|
|
88
|
+
self._fill(self._pending_size)
|
|
89
|
+
message = bytes(self._pending[:self._pending_size])
|
|
90
|
+
del self._pending[:self._pending_size]
|
|
91
|
+
self._pending_size = None
|
|
92
|
+
return message
|
|
93
|
+
|
|
94
|
+
def _fill(self, needed: int) -> None:
|
|
95
|
+
"""
|
|
96
|
+
Reads until ``needed`` bytes are pending. A timeout keeps what was read so far.
|
|
97
|
+
"""
|
|
98
|
+
while len(self._pending) < needed:
|
|
99
|
+
want = min(needed - len(self._pending), RECV_CHUNK)
|
|
100
|
+
try:
|
|
101
|
+
chunk = self._sock.recv(want)
|
|
102
|
+
except socket.timeout:
|
|
103
|
+
raise TimeoutError("no data received within the receive timeout") from None
|
|
104
|
+
except OSError as err:
|
|
105
|
+
self._open = False
|
|
106
|
+
raise TransportClosedError("receive failed: {}".format(err)) from err
|
|
107
|
+
if len(chunk) == 0:
|
|
108
|
+
self._open = False
|
|
109
|
+
raise TransportClosedError("peer closed the connection: expected {} bytes, received {}".format(
|
|
110
|
+
needed, len(self._pending)))
|
|
111
|
+
self._pending.extend(chunk)
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
"""
|
|
116
|
+
Closes the socket. Safe to call more than once, and it always releases the descriptor even when
|
|
117
|
+
an earlier send or receive failure already marked the transport closed.
|
|
118
|
+
"""
|
|
119
|
+
self._open = False
|
|
120
|
+
if self._released:
|
|
121
|
+
return
|
|
122
|
+
self._released = True
|
|
123
|
+
try:
|
|
124
|
+
self._sock.shutdown(socket.SHUT_RDWR)
|
|
125
|
+
except OSError:
|
|
126
|
+
# Best-effort; shutdown fails when the peer already disconnected, and the close below must
|
|
127
|
+
# still run to release the descriptor.
|
|
128
|
+
pass
|
|
129
|
+
try:
|
|
130
|
+
self._sock.close()
|
|
131
|
+
except OSError:
|
|
132
|
+
# Best-effort cleanup; a failure to close an already broken socket must not mask the error
|
|
133
|
+
# that caused the transport to be closed.
|
|
134
|
+
pass
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
def upgrade(self, upgrader: Upgrader) -> None:
|
|
138
|
+
self._sock = upgrader(self._sock)
|
|
139
|
+
return
|
ccai/rpc/endpoints.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: endpoints
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Endpoint types and the provider seam through which discovery packages supply addresses.
|
|
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, Protocol, Tuple, Union, runtime_checkable
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
Endpoint = Tuple[str, int]
|
|
18
|
+
EndpointProvider = Callable[[], Endpoint]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@runtime_checkable
|
|
22
|
+
class IServiceEndpoint(Protocol):
|
|
23
|
+
host: str
|
|
24
|
+
port: int
|
|
25
|
+
service_name: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class ServiceEndpoint:
|
|
30
|
+
host: str
|
|
31
|
+
port: int
|
|
32
|
+
service_name: str
|
|
33
|
+
|
|
34
|
+
def as_tuple(self) -> Endpoint:
|
|
35
|
+
return (self.host, self.port)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def resolve_endpoint(endpoint: Union[Endpoint, EndpointProvider, IServiceEndpoint]) -> Endpoint:
|
|
39
|
+
if callable(endpoint):
|
|
40
|
+
endpoint = endpoint()
|
|
41
|
+
if isinstance(endpoint, IServiceEndpoint) and not isinstance(endpoint, tuple):
|
|
42
|
+
return (endpoint.host, endpoint.port)
|
|
43
|
+
host, port = endpoint
|
|
44
|
+
return (host, int(port))
|
ccai/rpc/errors.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: errors
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Exception types used by the RPC package. Types that already exist in the suite's shared
|
|
5
|
+
vocabulary are re-exported from ccai.errors so callers have one import point.
|
|
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 ccai.errors.exceptions import (
|
|
15
|
+
AbstractMethodError,
|
|
16
|
+
CancelledError,
|
|
17
|
+
CompletionTimeout,
|
|
18
|
+
ConnectionTimeout,
|
|
19
|
+
InActivityTimeout,
|
|
20
|
+
LooperError,
|
|
21
|
+
ProtocolError,
|
|
22
|
+
SemanticError,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RpcError(RuntimeError):
|
|
27
|
+
"""
|
|
28
|
+
Base class for the errors this package adds to the shared vocabulary.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class SerializationError(RpcError):
|
|
33
|
+
"""
|
|
34
|
+
Raised when a value cannot be encoded for the wire or decoded from it.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TransportClosedError(RpcError):
|
|
39
|
+
"""
|
|
40
|
+
Raised when a transport operation is attempted after the transport or its peer closed.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SessionError(RpcError):
|
|
45
|
+
"""
|
|
46
|
+
Raised for misuse of a session, such as starting it twice.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SessionClosedError(SessionError):
|
|
51
|
+
"""
|
|
52
|
+
Raised in callers whose outstanding requests were abandoned because the session closed.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class UnknownReferenceError(RpcError):
|
|
57
|
+
"""
|
|
58
|
+
Raised when a request names a reference id the owning side does not hold.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class LeaseExpiredError(RpcError):
|
|
63
|
+
"""
|
|
64
|
+
Raised when a request names a reference whose lease has lapsed.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class UnauthorizedError(RpcError):
|
|
69
|
+
"""
|
|
70
|
+
Raised when the server rejects a client's credential during the HELLO exchange.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class RemoteError(RpcError):
|
|
75
|
+
"""
|
|
76
|
+
Stands in for a remote exception whose type could not be resolved locally. Every decoded
|
|
77
|
+
remote exception, including resolvable types, carries ``remote_traceback``.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, message: str, remote_type_name: str = "", remote_traceback: str = "") -> None:
|
|
81
|
+
super().__init__(message)
|
|
82
|
+
self.remote_type_name = remote_type_name
|
|
83
|
+
self.remote_traceback = remote_traceback
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
def __str__(self) -> str:
|
|
87
|
+
text = super().__str__()
|
|
88
|
+
if self.remote_type_name:
|
|
89
|
+
text = "{}: {}".format(self.remote_type_name, text)
|
|
90
|
+
if self.remote_traceback:
|
|
91
|
+
text = "{}\n\nRemote traceback:\n{}".format(text, self.remote_traceback)
|
|
92
|
+
return text
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
"AbstractMethodError", "CancelledError", "CompletionTimeout", "ConnectionTimeout", "InActivityTimeout",
|
|
97
|
+
"LooperError", "ProtocolError", "SemanticError", "RpcError", "SerializationError", "TransportClosedError",
|
|
98
|
+
"SessionError", "SessionClosedError", "UnknownReferenceError", "LeaseExpiredError", "UnauthorizedError",
|
|
99
|
+
"RemoteError",
|
|
100
|
+
]
|
ccai/rpc/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: rpcsocketclient
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: RpcSocketClient, which connects to a service with retry and returns a typed proxy to it.
|
|
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, Dict, Generic, Optional, Type, TypeVar, Union
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import socket
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
from ccai.rpc.aspects import AspectsRpc, DEFAULT_RPC_ASPECTS
|
|
20
|
+
from ccai.rpc.endpoints import Endpoint, EndpointProvider, resolve_endpoint
|
|
21
|
+
from ccai.rpc.errors import ConnectionTimeout, SessionError, UnauthorizedError
|
|
22
|
+
from ccai.rpc.core.protocol.constants import DEFAULT_MAX_MESSAGE_SIZE
|
|
23
|
+
from ccai.rpc.core.session.client import DuplexClientSession
|
|
24
|
+
from ccai.rpc.core.transport.base import Transport
|
|
25
|
+
from ccai.rpc.core.transport.socketio import DuplexSocketIO
|
|
26
|
+
|
|
27
|
+
ServiceProtocol = TypeVar("ServiceProtocol")
|
|
28
|
+
|
|
29
|
+
_live_clients = set()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RpcSocketClient(Generic[ServiceProtocol]):
|
|
33
|
+
|
|
34
|
+
def __init__(self, service_protocol: Optional[Type[ServiceProtocol]], endpoint: Union[Endpoint, EndpointProvider],
|
|
35
|
+
aspects: AspectsRpc = DEFAULT_RPC_ASPECTS, upgrader: Optional[Callable[[Transport], None]] = None,
|
|
36
|
+
credential: bytes = b"", context: Optional[Dict[str, str]] = None,
|
|
37
|
+
max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> None:
|
|
38
|
+
self._service_protocol = service_protocol
|
|
39
|
+
self._endpoint = endpoint
|
|
40
|
+
self._aspects = aspects
|
|
41
|
+
self._upgrader = upgrader
|
|
42
|
+
self._credential = credential
|
|
43
|
+
self._context = dict(context or {})
|
|
44
|
+
self._max_message_size = max_message_size
|
|
45
|
+
self._session: Optional[DuplexClientSession] = None
|
|
46
|
+
self.logger = logging.getLogger("ccai.rpc.client")
|
|
47
|
+
return
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def endpoint(self) -> Endpoint:
|
|
51
|
+
return resolve_endpoint(self._endpoint)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def aspects(self) -> AspectsRpc:
|
|
55
|
+
return self._aspects
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def is_connected(self) -> bool:
|
|
59
|
+
return self._session is not None and self._session.is_running
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def session(self) -> Optional[DuplexClientSession]:
|
|
63
|
+
return self._session
|
|
64
|
+
|
|
65
|
+
def connect(self, aspects: Optional[AspectsRpc] = None) -> None:
|
|
66
|
+
if self.is_connected:
|
|
67
|
+
raise SessionError("client is already connected to {}".format(self._session.remote_address))
|
|
68
|
+
aspects = aspects if aspects is not None else self._aspects
|
|
69
|
+
last_error = None
|
|
70
|
+
endpoint = None
|
|
71
|
+
for attempt in range(1, aspects.max_attempts + 1):
|
|
72
|
+
endpoint = resolve_endpoint(self._endpoint)
|
|
73
|
+
try:
|
|
74
|
+
sock = socket.create_connection(endpoint, timeout=aspects.connection_timeout)
|
|
75
|
+
except OSError as err:
|
|
76
|
+
last_error = err
|
|
77
|
+
self.logger.info("connect attempt %d/%d to %s failed: %s", attempt, aspects.max_attempts, endpoint, err)
|
|
78
|
+
if attempt < aspects.max_attempts:
|
|
79
|
+
time.sleep(aspects.completion_interval)
|
|
80
|
+
continue
|
|
81
|
+
transport = DuplexSocketIO(sock, receive_timeout=0.5, max_message_size=self._max_message_size)
|
|
82
|
+
if self._upgrader is not None:
|
|
83
|
+
self._upgrader(transport)
|
|
84
|
+
session = DuplexClientSession(transport, aspects=self._aspects, credential=self._credential, context=self._context)
|
|
85
|
+
try:
|
|
86
|
+
session.start(hello_timeout=aspects.connection_timeout)
|
|
87
|
+
except UnauthorizedError:
|
|
88
|
+
raise
|
|
89
|
+
except Exception as err: # noqa: BLE001 - retry on a failed handshake
|
|
90
|
+
last_error = err
|
|
91
|
+
if isinstance(err, SessionError) and "UnauthorizedError" in str(err):
|
|
92
|
+
raise UnauthorizedError(str(err)) from err
|
|
93
|
+
if attempt < aspects.max_attempts:
|
|
94
|
+
time.sleep(aspects.completion_interval)
|
|
95
|
+
continue
|
|
96
|
+
self._session = session
|
|
97
|
+
_live_clients.add(self)
|
|
98
|
+
return
|
|
99
|
+
raise ConnectionTimeout("could not connect to {} after {} attempt(s); last error: {}".format(endpoint, aspects.max_attempts, last_error))
|
|
100
|
+
|
|
101
|
+
def close(self, timeout: Optional[float] = 5.0) -> None:
|
|
102
|
+
if self._session is not None:
|
|
103
|
+
self._session.close(timeout=timeout)
|
|
104
|
+
_live_clients.discard(self)
|
|
105
|
+
return
|
|
106
|
+
|
|
107
|
+
def get_service(self, aspects: Optional[AspectsRpc] = None) -> ServiceProtocol:
|
|
108
|
+
if not self.is_connected:
|
|
109
|
+
raise SessionError("get_service called before connect")
|
|
110
|
+
return self._session.get_service(protocol=self._service_protocol, aspects=aspects)
|
|
111
|
+
|
|
112
|
+
def ping(self, timeout: Optional[float] = None) -> float:
|
|
113
|
+
if not self.is_connected:
|
|
114
|
+
raise SessionError("ping called before connect")
|
|
115
|
+
return self._session.ping(timeout=timeout)
|
|
116
|
+
|
|
117
|
+
def describe(self) -> dict:
|
|
118
|
+
return {"endpoint": self.endpoint, "connected": self.is_connected, "session": self._session.describe() if self._session else None}
|
|
119
|
+
|
|
120
|
+
def __enter__(self) -> "RpcSocketClient":
|
|
121
|
+
self.connect()
|
|
122
|
+
return self
|
|
123
|
+
|
|
124
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
125
|
+
self.close()
|
|
126
|
+
return None
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: rpcsocketserver
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: RpcSocketServer, which exposes a service object on an endpoint with one session per connection.
|
|
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, Dict, Optional, Tuple
|
|
14
|
+
|
|
15
|
+
import logging
|
|
16
|
+
import socket
|
|
17
|
+
import threading
|
|
18
|
+
import uuid
|
|
19
|
+
|
|
20
|
+
from ccai.rpc.aspects import AspectsRpc, DEFAULT_RPC_ASPECTS
|
|
21
|
+
from ccai.rpc.endpoints import Endpoint, ServiceEndpoint
|
|
22
|
+
from ccai.rpc.errors import SessionError
|
|
23
|
+
from ccai.rpc.core.protocol.constants import DEFAULT_MAX_MESSAGE_SIZE
|
|
24
|
+
from ccai.rpc.core.session.server import DuplexServerSession
|
|
25
|
+
from ccai.rpc.core.transport.base import Transport
|
|
26
|
+
from ccai.rpc.core.transport.socketio import DuplexSocketIO
|
|
27
|
+
|
|
28
|
+
Authenticator = Callable[[bytes, Tuple[str, int]], Optional[str]]
|
|
29
|
+
|
|
30
|
+
_live_servers = set()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RpcSocketServer:
|
|
34
|
+
|
|
35
|
+
def __init__(self, service: object, endpoint: Endpoint, backlog: int = 16, aspects: AspectsRpc = DEFAULT_RPC_ASPECTS,
|
|
36
|
+
upgrader: Optional[Callable[[Transport], None]] = None, authenticator: Optional[Authenticator] = None,
|
|
37
|
+
on_session: Optional[Callable[[DuplexServerSession], None]] = None,
|
|
38
|
+
on_session_closed: Optional[Callable[[DuplexServerSession, BaseException], None]] = None,
|
|
39
|
+
service_name: Optional[str] = None, max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> None:
|
|
40
|
+
self._service = service
|
|
41
|
+
self._endpoint = (endpoint[0], int(endpoint[1]))
|
|
42
|
+
self._backlog = backlog
|
|
43
|
+
self._aspects = aspects
|
|
44
|
+
self._upgrader = upgrader
|
|
45
|
+
self._authenticator = authenticator
|
|
46
|
+
self._on_session = on_session
|
|
47
|
+
self._on_session_closed = on_session_closed
|
|
48
|
+
self._service_name = service_name or type(service).__name__
|
|
49
|
+
self._max_message_size = max_message_size
|
|
50
|
+
self._listen_sock: Optional[socket.socket] = None
|
|
51
|
+
self._bound: Optional[Endpoint] = None
|
|
52
|
+
self._sessions: Dict[uuid.UUID, DuplexServerSession] = {}
|
|
53
|
+
self._lock = threading.RLock()
|
|
54
|
+
self._serving = False
|
|
55
|
+
self._accept_thread: Optional[threading.Thread] = None
|
|
56
|
+
self._listening = threading.Event()
|
|
57
|
+
self.logger = logging.getLogger("ccai.rpc.server")
|
|
58
|
+
return
|
|
59
|
+
|
|
60
|
+
# ------------------------------------------------------------------ properties
|
|
61
|
+
@property
|
|
62
|
+
def service(self) -> object:
|
|
63
|
+
return self._service
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def endpoint(self) -> Endpoint:
|
|
67
|
+
return self._endpoint
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def bound_endpoint(self) -> Optional[Endpoint]:
|
|
71
|
+
return self._bound
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def aspects(self) -> AspectsRpc:
|
|
75
|
+
return self._aspects
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def is_serving(self) -> bool:
|
|
79
|
+
return self._serving
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def session_count(self) -> int:
|
|
83
|
+
with self._lock:
|
|
84
|
+
return len(self._sessions)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def sessions(self):
|
|
88
|
+
with self._lock:
|
|
89
|
+
return list(self._sessions.values())
|
|
90
|
+
|
|
91
|
+
# ------------------------------------------------------------------ lifecycle
|
|
92
|
+
def _bind(self) -> None:
|
|
93
|
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
94
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
95
|
+
try:
|
|
96
|
+
sock.bind(self._endpoint)
|
|
97
|
+
except OSError as err:
|
|
98
|
+
sock.close()
|
|
99
|
+
raise OSError("could not bind RPC server to {}:{}: {}".format(self._endpoint[0], self._endpoint[1], err)) from err
|
|
100
|
+
sock.listen(self._backlog)
|
|
101
|
+
self._listen_sock = sock
|
|
102
|
+
self._bound = sock.getsockname()[:2]
|
|
103
|
+
self._serving = True
|
|
104
|
+
_live_servers.add(self)
|
|
105
|
+
self._listening.set()
|
|
106
|
+
self.logger.info("serving %s on %s", self._service_name, self._bound)
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
def start(self) -> None:
|
|
110
|
+
with self._lock:
|
|
111
|
+
if self._serving:
|
|
112
|
+
raise SessionError("server is already serving")
|
|
113
|
+
self._listening.clear()
|
|
114
|
+
self._bind()
|
|
115
|
+
self._accept_thread = threading.Thread(target=self._accept_loop, name="rpc-server-accept-{}".format(self._bound[1]), daemon=True)
|
|
116
|
+
self._accept_thread.start()
|
|
117
|
+
return
|
|
118
|
+
|
|
119
|
+
def serve_forever(self) -> None:
|
|
120
|
+
with self._lock:
|
|
121
|
+
if self._serving:
|
|
122
|
+
raise SessionError("server is already serving")
|
|
123
|
+
self._bind()
|
|
124
|
+
self._accept_loop()
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
def _accept_loop(self) -> None:
|
|
128
|
+
while self._serving:
|
|
129
|
+
try:
|
|
130
|
+
client_sock, addr = self._listen_sock.accept()
|
|
131
|
+
except OSError:
|
|
132
|
+
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
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
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)
|
|
147
|
+
if self._upgrader is not None:
|
|
148
|
+
self._upgrader(transport)
|
|
149
|
+
session = DuplexServerSession(transport, aspects=self._aspects, service=self._service, authenticator=self._authenticator,
|
|
150
|
+
on_closed=self._session_closed, on_hello=self._session_ready)
|
|
151
|
+
with self._lock:
|
|
152
|
+
self._sessions[session.session_id] = session
|
|
153
|
+
session.start()
|
|
154
|
+
return
|
|
155
|
+
|
|
156
|
+
def _session_ready(self, session: DuplexServerSession) -> None:
|
|
157
|
+
if self._on_session is not None:
|
|
158
|
+
try:
|
|
159
|
+
self._on_session(session)
|
|
160
|
+
except Exception: # noqa: BLE001
|
|
161
|
+
self.logger.exception("on_session callback raised")
|
|
162
|
+
return
|
|
163
|
+
|
|
164
|
+
def _session_closed(self, session: DuplexServerSession, reason: BaseException) -> None:
|
|
165
|
+
with self._lock:
|
|
166
|
+
self._sessions.pop(session.session_id, None)
|
|
167
|
+
if self._on_session_closed is not None:
|
|
168
|
+
try:
|
|
169
|
+
self._on_session_closed(session, reason)
|
|
170
|
+
except Exception: # noqa: BLE001
|
|
171
|
+
self.logger.exception("on_session_closed callback raised")
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
def stop(self, timeout: Optional[float] = 5.0) -> int:
|
|
175
|
+
with self._lock:
|
|
176
|
+
if not self._serving:
|
|
177
|
+
return 0
|
|
178
|
+
self._serving = False
|
|
179
|
+
sessions = list(self._sessions.values())
|
|
180
|
+
if self._listen_sock is not None:
|
|
181
|
+
try:
|
|
182
|
+
self._listen_sock.shutdown(socket.SHUT_RDWR)
|
|
183
|
+
except OSError:
|
|
184
|
+
# Best-effort; a listening socket is not connected on every platform, and the wake-up
|
|
185
|
+
# connection and close below still stop the accept loop.
|
|
186
|
+
pass
|
|
187
|
+
if self._accept_thread is not None and self._accept_thread.is_alive() and self._bound is not None:
|
|
188
|
+
# a blocked accept() does not always wake on close; a throwaway connection guarantees it
|
|
189
|
+
try:
|
|
190
|
+
socket.create_connection(("127.0.0.1" if self._bound[0] in ("0.0.0.0", "") else self._bound[0], self._bound[1]), timeout=0.5).close()
|
|
191
|
+
except OSError:
|
|
192
|
+
# The wake-up connection is only a nudge; a refused connection means the accept loop has
|
|
193
|
+
# already stopped listening.
|
|
194
|
+
pass
|
|
195
|
+
try:
|
|
196
|
+
self._listen_sock.close()
|
|
197
|
+
except OSError:
|
|
198
|
+
# Best-effort cleanup; stopping must continue on to close the sessions.
|
|
199
|
+
pass
|
|
200
|
+
for session in sessions:
|
|
201
|
+
try:
|
|
202
|
+
session.close(timeout=timeout)
|
|
203
|
+
except Exception: # noqa: BLE001
|
|
204
|
+
self.logger.exception("closing session %s failed", session.session_id)
|
|
205
|
+
if self._accept_thread is not None and self._accept_thread is not threading.current_thread():
|
|
206
|
+
self._accept_thread.join(timeout=timeout)
|
|
207
|
+
_live_servers.discard(self)
|
|
208
|
+
self.logger.info("stopped %s on %s, closed %d session(s)", self._service_name, self._bound, len(sessions))
|
|
209
|
+
return len(sessions)
|
|
210
|
+
|
|
211
|
+
def __enter__(self) -> "RpcSocketServer":
|
|
212
|
+
self.start()
|
|
213
|
+
return self
|
|
214
|
+
|
|
215
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
216
|
+
self.stop()
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
# ------------------------------------------------------------------ diagnostics
|
|
220
|
+
def advertise(self) -> ServiceEndpoint:
|
|
221
|
+
host, port = self._bound if self._bound is not None else self._endpoint
|
|
222
|
+
return ServiceEndpoint(host=host, port=port, service_name=self._service_name)
|
|
223
|
+
|
|
224
|
+
def describe(self) -> dict:
|
|
225
|
+
return {"service": self._service_name, "endpoint": self._endpoint, "bound": self._bound, "serving": self._serving,
|
|
226
|
+
"sessions": [s.describe() for s in self.sessions]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TLS upgraders, the token authenticator and the attribute policy markers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from ccai.rpc.security.auth import Authenticator, shared_secret_authenticator
|
|
6
|
+
from ccai.rpc.security.tls import mutual_tls_server_upgrader, tls_client_upgrader, tls_server_upgrader
|
|
7
|
+
from ccai.rpc.core.proxy.wrappers import expose_private, mutable_service
|
|
8
|
+
|
|
9
|
+
__all__ = ["Authenticator", "shared_secret_authenticator", "mutual_tls_server_upgrader", "tls_client_upgrader",
|
|
10
|
+
"tls_server_upgrader", "expose_private", "mutable_service"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: auth
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The authenticator hook the server calls during HELLO, and a constant-time shared-secret implementation.
|
|
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, Optional, Tuple
|
|
14
|
+
|
|
15
|
+
import hmac
|
|
16
|
+
|
|
17
|
+
Authenticator = Callable[[bytes, Tuple[str, int]], Optional[str]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def shared_secret_authenticator(secret: bytes, identity: str = "shared-secret") -> Authenticator:
|
|
21
|
+
"""
|
|
22
|
+
Accepts a credential equal to ``secret``, compared in constant time, and names the peer ``identity``.
|
|
23
|
+
"""
|
|
24
|
+
if isinstance(secret, str):
|
|
25
|
+
secret = secret.encode("utf-8")
|
|
26
|
+
|
|
27
|
+
def authenticate(credential: bytes, address: Tuple[str, int]) -> Optional[str]:
|
|
28
|
+
if credential is None:
|
|
29
|
+
return None
|
|
30
|
+
if isinstance(credential, str):
|
|
31
|
+
credential = credential.encode("utf-8")
|
|
32
|
+
return identity if hmac.compare_digest(bytes(credential), secret) else None
|
|
33
|
+
|
|
34
|
+
return authenticate
|