codecraftai-python-rpc 1.3.1__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.
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/PKG-INFO +1 -1
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/pyproject.toml +1 -1
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/lanes.py +12 -3
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/futures.py +13 -2
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looper.py +21 -1
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looperpool.py +34 -8
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/looperqueue.py +22 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/constants.py +2 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/remoteproxy.py +12 -1
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/codec.py +73 -21
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/base.py +87 -2
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/dispatch.py +52 -11
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/heartbeat.py +2 -1
- codecraftai_python_rpc-1.5.0/source/packages/ccai/rpc/core/session/server.py +157 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/socketio.py +65 -2
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/rpcsocketclient.py +2 -1
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/rpcsocketserver.py +78 -15
- codecraftai_python_rpc-1.3.1/source/packages/ccai/rpc/core/session/server.py +0 -68
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/LICENSE.md +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/README.rst +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/aspects.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/dispatch/context.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/flattenable.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/leases.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/metrics.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/observability/state.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/header.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/protocol/messages.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/cache.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/handlers.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/table.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/proxy/wrappers.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/placeholder.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/registry.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/serialization/tags.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/session/client.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/base.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/faults.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/core/transport/inprocess.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/endpoints.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/errors.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/py.typed +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/__init__.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/auth.py +0 -0
- {codecraftai_python_rpc-1.3.1 → codecraftai_python_rpc-1.5.0}/source/packages/ccai/rpc/security/tls.py +0 -0
|
@@ -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
|
-
|
|
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
|
|
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.
|
|
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``
|
|
26
|
-
looper up to ``max_loopers``.
|
|
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
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
132
|
-
looper_name = "{}-{}".format(self._group_name,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
128
|
-
|
|
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.
|
|
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
|
-
|
|
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,
|
|
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,
|
|
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
|
|
|
@@ -150,6 +155,7 @@ class DuplexSessionBase:
|
|
|
150
155
|
self._running = False
|
|
151
156
|
self._closing = False
|
|
152
157
|
self._closed = False
|
|
158
|
+
self._receive_stopped = False # set when no further inbound frame may be read
|
|
153
159
|
self._closed_event = threading.Event()
|
|
154
160
|
self._close_reason: Optional[BaseException] = None
|
|
155
161
|
self._waiters: Dict[uuid.UUID, Waiter] = {}
|
|
@@ -304,6 +310,20 @@ class DuplexSessionBase:
|
|
|
304
310
|
self.logger.exception("on_closed callback raised")
|
|
305
311
|
return
|
|
306
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
|
+
|
|
307
327
|
def __enter__(self):
|
|
308
328
|
return self
|
|
309
329
|
|
|
@@ -336,9 +356,61 @@ class DuplexSessionBase:
|
|
|
336
356
|
future = RemoteFuture(self, waiter, getattr(message, "callable_name", type(message).__name__), timeout, unwrap=unwrap)
|
|
337
357
|
with self._lock:
|
|
338
358
|
self._futures[message.correlation_id] = future
|
|
339
|
-
|
|
359
|
+
try:
|
|
360
|
+
self._send_registered(message, waiter)
|
|
361
|
+
except BaseException:
|
|
362
|
+
self.forget_future(message.correlation_id)
|
|
363
|
+
raise
|
|
340
364
|
return future
|
|
341
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
|
+
|
|
342
414
|
def send_request(self, message: Message, timeout: Optional[float] = None) -> Message:
|
|
343
415
|
"""
|
|
344
416
|
Sends ``message`` and blocks the calling thread until its reply arrives. Raises the decoded
|
|
@@ -594,7 +666,7 @@ class DuplexSessionBase:
|
|
|
594
666
|
def _receive_loop(self, gate: threading.Event) -> None:
|
|
595
667
|
gate.set()
|
|
596
668
|
reason = None
|
|
597
|
-
while self._running and not self._closing:
|
|
669
|
+
while self._running and not self._closing and not self._receive_stopped:
|
|
598
670
|
try:
|
|
599
671
|
frame = self._transport.receive_frame()
|
|
600
672
|
except TimeoutError:
|
|
@@ -642,9 +714,22 @@ class DuplexSessionBase:
|
|
|
642
714
|
if header.mcode == RequestCode.HELLO:
|
|
643
715
|
self._handle_hello_frame(frame, header)
|
|
644
716
|
return
|
|
717
|
+
if not self._admit_request(header):
|
|
718
|
+
return
|
|
645
719
|
self._pool.push_work(frame)
|
|
646
720
|
return
|
|
647
721
|
|
|
722
|
+
def _admit_request(self, header: MessageHeader) -> bool:
|
|
723
|
+
"""
|
|
724
|
+
Decides, on the receive thread, whether a request other than HELLO or PING may be dispatched. The
|
|
725
|
+
base session admits every request; the server session admits requests only after a completed HELLO.
|
|
726
|
+
|
|
727
|
+
:param header: The header of the inbound request frame.
|
|
728
|
+
|
|
729
|
+
:returns: True when the frame may be handed to the dispatch pool, False when it was refused.
|
|
730
|
+
"""
|
|
731
|
+
return True
|
|
732
|
+
|
|
648
733
|
def _handle_hello_frame(self, frame: bytes, header: MessageHeader) -> None:
|
|
649
734
|
raise ProtocolError("unexpected HELLO on a {} session".format(self.role))
|
|
650
735
|
|