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
ccai/rpc/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
codecraftai-python-rpc: an RPC layer for distributed automation with explicit passing semantics and
|
|
3
|
+
callback threading that never blocks the thread waiting on a reply.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ccai.rpc.aspects import AspectsRpc, DEFAULT_RPC_ASPECTS, LoggingPattern, remaining_time, rpc_aspects_scope
|
|
7
|
+
from ccai.rpc.endpoints import ServiceEndpoint, IServiceEndpoint
|
|
8
|
+
from ccai.rpc.errors import (
|
|
9
|
+
CancelledError, CompletionTimeout, ConnectionTimeout, InActivityTimeout, LeaseExpiredError, ProtocolError, RemoteError,
|
|
10
|
+
RpcError, SerializationError, SessionClosedError, SessionError, TransportClosedError, UnauthorizedError, UnknownReferenceError,
|
|
11
|
+
)
|
|
12
|
+
from ccai.rpc.rpcsocketclient import RpcSocketClient
|
|
13
|
+
from ccai.rpc.rpcsocketserver import RpcSocketServer
|
|
14
|
+
from ccai.rpc.core.dispatch.context import check_cancelled, current_call_context, is_cancelled, report_progress
|
|
15
|
+
from ccai.rpc.core.flattenable import Flattenable
|
|
16
|
+
from ccai.rpc.core.futures import RemoteFuture, Progress, as_completed, wait_all
|
|
17
|
+
from ccai.rpc.core.leases import ILeaseAware
|
|
18
|
+
from ccai.rpc.core.proxy.remoteproxy import RemoteProxy
|
|
19
|
+
from ccai.rpc.core.proxy.wrappers import ByRef, ByValue, by_ref, concurrent_callbacks, expose_private, mutable_service, oneway
|
|
20
|
+
from ccai.rpc.core.serialization import register_dataclass, register_enum, register_flattenable
|
|
21
|
+
from ccai.rpc.core.session.base import rpc_context_scope
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"AspectsRpc", "DEFAULT_RPC_ASPECTS", "LoggingPattern", "remaining_time", "rpc_aspects_scope", "rpc_context_scope",
|
|
25
|
+
"ServiceEndpoint", "IServiceEndpoint", "RpcSocketClient", "RpcSocketServer",
|
|
26
|
+
"CancelledError", "CompletionTimeout", "ConnectionTimeout", "InActivityTimeout", "LeaseExpiredError", "ProtocolError",
|
|
27
|
+
"RemoteError", "RpcError", "SerializationError", "SessionClosedError", "SessionError", "TransportClosedError",
|
|
28
|
+
"UnauthorizedError", "UnknownReferenceError",
|
|
29
|
+
"check_cancelled", "current_call_context", "is_cancelled", "report_progress", "Flattenable",
|
|
30
|
+
"RemoteFuture", "Progress", "as_completed", "wait_all", "RemoteProxy", "ILeaseAware",
|
|
31
|
+
"ByRef", "ByValue", "by_ref", "concurrent_callbacks", "expose_private", "mutable_service", "oneway",
|
|
32
|
+
"register_dataclass", "register_enum", "register_flattenable",
|
|
33
|
+
]
|
ccai/rpc/aspects.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: aspects
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: AspectsRpc, the behaviour-parameter bundle for every tunable in the package, plus the per-thread
|
|
5
|
+
override scope and the deadline helper for service code.
|
|
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 typing import Iterator, Optional
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import threading
|
|
18
|
+
|
|
19
|
+
from enum import IntEnum
|
|
20
|
+
|
|
21
|
+
from ccai.aspects.aspects import Aspects
|
|
22
|
+
from ccai.errors.exceptions import SemanticError
|
|
23
|
+
|
|
24
|
+
from ccai.rpc.core.serialization.registry import register_flattenable
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LoggingPattern(IntEnum):
|
|
28
|
+
ALL_RESULTS = 0
|
|
29
|
+
FAILURE_ONLY = 1
|
|
30
|
+
SUCCESS_ONLY = 2
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AspectsRpc(Aspects):
|
|
34
|
+
"""
|
|
35
|
+
Every tunable of the RPC layer in one frozen object. Connect behaviour comes from the base fields
|
|
36
|
+
(``connection_timeout`` per attempt, ``max_attempts``, ``completion_interval`` between attempts);
|
|
37
|
+
``completion_timeout`` is the default per-call response timeout and the deadline sent with each
|
|
38
|
+
request. The RPC-specific fields are named for what they tune so a reader of
|
|
39
|
+
``AspectsRpc(inactivity_timeout=5)`` knows dead-peer detection is being changed, not a call timeout.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, *,
|
|
43
|
+
completion_interval: float = 2.0,
|
|
44
|
+
completion_timeout: float = 600.0,
|
|
45
|
+
connection_timeout: float = 30.0,
|
|
46
|
+
max_attempts: int = 1,
|
|
47
|
+
logger_name: Optional[str] = None,
|
|
48
|
+
heartbeat_interval: float = 10.0,
|
|
49
|
+
inactivity_timeout: float = 60.0,
|
|
50
|
+
lease_duration: float = 90.0,
|
|
51
|
+
dispatch_min_workers: int = 2,
|
|
52
|
+
dispatch_max_workers: int = 8,
|
|
53
|
+
dispatch_highwater: int = 4,
|
|
54
|
+
logging_pattern: LoggingPattern = LoggingPattern.FAILURE_ONLY,
|
|
55
|
+
retry_logging_interval: float = 5.0) -> None:
|
|
56
|
+
super().__init__(completion_interval=completion_interval, completion_timeout=completion_timeout,
|
|
57
|
+
connection_timeout=connection_timeout, max_attempts=max_attempts, logger_name=logger_name)
|
|
58
|
+
self.heartbeat_interval = heartbeat_interval
|
|
59
|
+
self.inactivity_timeout = inactivity_timeout
|
|
60
|
+
self.lease_duration = lease_duration
|
|
61
|
+
self.dispatch_min_workers = dispatch_min_workers
|
|
62
|
+
self.dispatch_max_workers = dispatch_max_workers
|
|
63
|
+
self.dispatch_highwater = dispatch_highwater
|
|
64
|
+
self.logging_pattern = LoggingPattern(logging_pattern)
|
|
65
|
+
self.retry_logging_interval = retry_logging_interval
|
|
66
|
+
self._validate()
|
|
67
|
+
self.freeze()
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
def _validate(self) -> None:
|
|
71
|
+
for name in ("completion_interval", "completion_timeout", "connection_timeout", "heartbeat_interval",
|
|
72
|
+
"inactivity_timeout", "lease_duration", "retry_logging_interval"):
|
|
73
|
+
value = getattr(self, name)
|
|
74
|
+
if not isinstance(value, (int, float)) or value <= 0:
|
|
75
|
+
raise SemanticError("AspectsRpc: '{}' must be a positive number, got {!r}".format(name, value))
|
|
76
|
+
if self.max_attempts < 1:
|
|
77
|
+
raise SemanticError("AspectsRpc: 'max_attempts' must be at least 1")
|
|
78
|
+
if self.dispatch_min_workers < 1 or self.dispatch_max_workers < 1:
|
|
79
|
+
raise SemanticError("AspectsRpc: dispatch worker counts must be at least 1")
|
|
80
|
+
if self.dispatch_min_workers > self.dispatch_max_workers:
|
|
81
|
+
raise SemanticError("AspectsRpc: 'dispatch_min_workers' may not exceed 'dispatch_max_workers'")
|
|
82
|
+
if self.lease_duration < 2 * self.heartbeat_interval:
|
|
83
|
+
raise SemanticError("AspectsRpc: 'lease_duration' ({}) must be at least twice 'heartbeat_interval' ({})".format(
|
|
84
|
+
self.lease_duration, self.heartbeat_interval))
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
FIELDS = ("completion_interval", "completion_timeout", "connection_timeout", "max_attempts", "logger_name",
|
|
88
|
+
"heartbeat_interval", "inactivity_timeout", "lease_duration", "dispatch_min_workers",
|
|
89
|
+
"dispatch_max_workers", "dispatch_highwater", "logging_pattern", "retry_logging_interval")
|
|
90
|
+
|
|
91
|
+
def replace(self, **changes) -> "AspectsRpc":
|
|
92
|
+
values = {name: getattr(self, name) for name in self.FIELDS}
|
|
93
|
+
for name in changes:
|
|
94
|
+
if name not in values:
|
|
95
|
+
raise SemanticError("AspectsRpc.replace: unknown field '{}'".format(name))
|
|
96
|
+
values.update(changes)
|
|
97
|
+
return AspectsRpc(**values)
|
|
98
|
+
|
|
99
|
+
def flatten(self) -> dict:
|
|
100
|
+
data = {name: getattr(self, name) for name in self.FIELDS}
|
|
101
|
+
data["logging_pattern"] = int(self.logging_pattern)
|
|
102
|
+
return data
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def unflatten(cls, data: dict) -> "AspectsRpc":
|
|
106
|
+
return cls(**data)
|
|
107
|
+
|
|
108
|
+
def __repr__(self) -> str:
|
|
109
|
+
return "AspectsRpc({})".format(", ".join("{}={!r}".format(n, getattr(self, n)) for n in self.FIELDS))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
register_flattenable("ccai.rpc.aspects", AspectsRpc)
|
|
113
|
+
|
|
114
|
+
DEFAULT_RPC_ASPECTS = AspectsRpc()
|
|
115
|
+
|
|
116
|
+
_scope = threading.local()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def current_aspects_override() -> Optional[AspectsRpc]:
|
|
120
|
+
return getattr(_scope, "aspects", None)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@contextlib.contextmanager
|
|
124
|
+
def rpc_aspects_scope(aspects: AspectsRpc) -> Iterator[None]:
|
|
125
|
+
"""
|
|
126
|
+
Applies ``aspects`` to every request made on this thread within the block.
|
|
127
|
+
"""
|
|
128
|
+
previous = getattr(_scope, "aspects", None)
|
|
129
|
+
_scope.aspects = aspects
|
|
130
|
+
try:
|
|
131
|
+
yield
|
|
132
|
+
finally:
|
|
133
|
+
_scope.aspects = previous
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def remaining_time() -> Optional[float]:
|
|
138
|
+
"""
|
|
139
|
+
Seconds until the current call's deadline, or ``None`` outside a call or without a deadline.
|
|
140
|
+
"""
|
|
141
|
+
from ccai.rpc.core.dispatch.context import remaining_time as _remaining
|
|
142
|
+
return _remaining()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
__all__ = ["AspectsRpc", "DEFAULT_RPC_ASPECTS", "LoggingPattern", "rpc_aspects_scope", "remaining_time", "current_aspects_override"]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: context
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The per-thread call context a dispatch worker exposes while executing a request, and the helpers
|
|
5
|
+
service code uses to read the deadline, observe cancellation and report progress.
|
|
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 typing import Dict, Optional
|
|
15
|
+
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
import uuid
|
|
19
|
+
|
|
20
|
+
from ccai.errors.exceptions import SemanticError
|
|
21
|
+
|
|
22
|
+
from ccai.rpc.errors import CancelledError
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CallContext:
|
|
26
|
+
"""
|
|
27
|
+
What a dispatch worker knows about the request it is executing.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
__slots__ = ("session", "correlation_id", "caller_session_id", "target_ref", "callable_name", "started_at",
|
|
31
|
+
"deadline", "caller_context", "_cancelled", "notify")
|
|
32
|
+
|
|
33
|
+
def __init__(self, session, correlation_id: uuid.UUID, caller_session_id: Optional[uuid.UUID],
|
|
34
|
+
target_ref: Optional[uuid.UUID], callable_name: str, deadline: Optional[float],
|
|
35
|
+
caller_context: Optional[Dict[str, str]] = None, notify: bool = False) -> None:
|
|
36
|
+
self.session = session
|
|
37
|
+
self.correlation_id = correlation_id
|
|
38
|
+
self.caller_session_id = caller_session_id
|
|
39
|
+
self.target_ref = target_ref
|
|
40
|
+
self.callable_name = callable_name
|
|
41
|
+
self.started_at = time.monotonic()
|
|
42
|
+
self.deadline = deadline # monotonic time or None
|
|
43
|
+
self.caller_context = dict(caller_context or {})
|
|
44
|
+
self.notify = notify
|
|
45
|
+
self._cancelled = threading.Event()
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def elapsed(self) -> float:
|
|
50
|
+
return time.monotonic() - self.started_at
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def remaining(self) -> Optional[float]:
|
|
54
|
+
if self.deadline is None:
|
|
55
|
+
return None
|
|
56
|
+
return self.deadline - time.monotonic()
|
|
57
|
+
|
|
58
|
+
def cancel(self) -> None:
|
|
59
|
+
self._cancelled.set()
|
|
60
|
+
return
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def is_cancelled(self) -> bool:
|
|
64
|
+
if self._cancelled.is_set():
|
|
65
|
+
return True
|
|
66
|
+
remaining = self.remaining
|
|
67
|
+
return remaining is not None and remaining <= 0
|
|
68
|
+
|
|
69
|
+
def describe(self) -> dict:
|
|
70
|
+
return {"correlation_id": str(self.correlation_id), "callable": self.callable_name,
|
|
71
|
+
"target_ref": str(self.target_ref) if self.target_ref else None, "elapsed": round(self.elapsed, 3),
|
|
72
|
+
"remaining": None if self.remaining is None else round(self.remaining, 3), "cancelled": self.is_cancelled}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_current = threading.local()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def set_call_context(context: Optional[CallContext]) -> None:
|
|
79
|
+
_current.context = context
|
|
80
|
+
return
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def current_call_context() -> Optional[CallContext]:
|
|
84
|
+
return getattr(_current, "context", None)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def remaining_time() -> Optional[float]:
|
|
88
|
+
context = current_call_context()
|
|
89
|
+
if context is None:
|
|
90
|
+
return None
|
|
91
|
+
return context.remaining
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def is_cancelled() -> bool:
|
|
95
|
+
context = current_call_context()
|
|
96
|
+
return context is not None and context.is_cancelled
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def check_cancelled() -> None:
|
|
100
|
+
context = current_call_context()
|
|
101
|
+
if context is not None and context.is_cancelled:
|
|
102
|
+
raise CancelledError("call '{}' ({}) was cancelled by the caller or its deadline passed".format(
|
|
103
|
+
context.callable_name, context.correlation_id))
|
|
104
|
+
return
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def report_progress(fraction: float, message: Optional[str] = None, **details) -> None:
|
|
108
|
+
"""
|
|
109
|
+
Sends a progress notification for the current call. Raises outside a call context.
|
|
110
|
+
"""
|
|
111
|
+
context = current_call_context()
|
|
112
|
+
if context is None:
|
|
113
|
+
raise SemanticError("report_progress called outside of an RPC call context")
|
|
114
|
+
context.session.send_progress(context.correlation_id, float(fraction), message, dict(details))
|
|
115
|
+
return
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: lanes
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Per-target ordering lanes: callbacks for one target run one at a time, in arrival order, without
|
|
5
|
+
blocking pool workers.
|
|
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 typing import Callable, Dict, Hashable, List
|
|
15
|
+
|
|
16
|
+
import threading
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TargetLane:
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self._lock = threading.Lock()
|
|
23
|
+
self._busy = False
|
|
24
|
+
self._fifo: List[Callable[[], None]] = []
|
|
25
|
+
return
|
|
26
|
+
|
|
27
|
+
def run(self, work: Callable[[], None]) -> None:
|
|
28
|
+
"""
|
|
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.
|
|
31
|
+
"""
|
|
32
|
+
with self._lock:
|
|
33
|
+
if self._busy:
|
|
34
|
+
self._fifo.append(work)
|
|
35
|
+
return
|
|
36
|
+
self._busy = True
|
|
37
|
+
current = work
|
|
38
|
+
while True:
|
|
39
|
+
try:
|
|
40
|
+
current()
|
|
41
|
+
finally:
|
|
42
|
+
with self._lock:
|
|
43
|
+
if self._fifo:
|
|
44
|
+
current = self._fifo.pop(0)
|
|
45
|
+
continue_ = True
|
|
46
|
+
else:
|
|
47
|
+
self._busy = False
|
|
48
|
+
continue_ = False
|
|
49
|
+
if not continue_:
|
|
50
|
+
break
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def busy(self) -> bool:
|
|
55
|
+
with self._lock:
|
|
56
|
+
return self._busy
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class LaneTable:
|
|
60
|
+
|
|
61
|
+
def __init__(self) -> None:
|
|
62
|
+
self._lock = threading.Lock()
|
|
63
|
+
self._lanes: Dict[Hashable, TargetLane] = {}
|
|
64
|
+
return
|
|
65
|
+
|
|
66
|
+
def get(self, key: Hashable) -> TargetLane:
|
|
67
|
+
with self._lock:
|
|
68
|
+
lane = self._lanes.get(key)
|
|
69
|
+
if lane is None:
|
|
70
|
+
lane = TargetLane()
|
|
71
|
+
self._lanes[key] = lane
|
|
72
|
+
return lane
|
|
73
|
+
|
|
74
|
+
def discard(self, key: Hashable) -> None:
|
|
75
|
+
with self._lock:
|
|
76
|
+
self._lanes.pop(key, None)
|
|
77
|
+
return
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: flattenable
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The Flattenable protocol implemented by user types that are passed by value.
|
|
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 Protocol, runtime_checkable
|
|
14
|
+
|
|
15
|
+
from ccai.rpc.errors import AbstractMethodError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@runtime_checkable
|
|
19
|
+
class Flattenable(Protocol):
|
|
20
|
+
"""
|
|
21
|
+
A type that can be flattened to a dictionary of by-value types and rebuilt from one.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def flatten(self) -> dict:
|
|
25
|
+
thistype = type(self)
|
|
26
|
+
raise AbstractMethodError("The 'flatten' method must be implemented for type='{}'".format(thistype.__name__))
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def unflatten(cls, data: dict) -> "Flattenable":
|
|
30
|
+
raise AbstractMethodError("The 'unflatten' class method must be implemented for type='{}'".format(cls.__name__))
|
ccai/rpc/core/futures.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: futures
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: RemoteFuture for asynchronous calls, with cancellation and progress delivery.
|
|
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, Iterable, Iterator, List, Optional, TypeVar
|
|
14
|
+
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import uuid
|
|
18
|
+
|
|
19
|
+
from ccai.rpc.errors import CancelledError, CompletionTimeout
|
|
20
|
+
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Progress:
|
|
25
|
+
|
|
26
|
+
__slots__ = ("fraction", "message", "details", "correlation_id", "received_at")
|
|
27
|
+
|
|
28
|
+
def __init__(self, fraction: float, message: Optional[str], details: Dict, correlation_id: uuid.UUID) -> None:
|
|
29
|
+
self.fraction = fraction
|
|
30
|
+
self.message = message
|
|
31
|
+
self.details = details
|
|
32
|
+
self.correlation_id = correlation_id
|
|
33
|
+
self.received_at = time.monotonic()
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return "Progress({:.0%}{})".format(self.fraction, ", " + self.message if self.message else "")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RemoteFuture(Generic[T]):
|
|
41
|
+
"""
|
|
42
|
+
The result of an asynchronous remote call. Completed by the session when the reply or exception
|
|
43
|
+
arrives, failed when the session closes, cancellable cooperatively.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, session, waiter, callable_name: str, deadline: Optional[float], unwrap: bool = False) -> None:
|
|
47
|
+
self._session = session
|
|
48
|
+
self._waiter = waiter
|
|
49
|
+
self.correlation_id = waiter.correlation_id
|
|
50
|
+
self.callable_name = callable_name
|
|
51
|
+
self.started_at = time.monotonic()
|
|
52
|
+
self.deadline = deadline
|
|
53
|
+
self._unwrap = unwrap
|
|
54
|
+
self._lock = threading.Lock()
|
|
55
|
+
self._done_callbacks: List[Callable[["RemoteFuture"], None]] = []
|
|
56
|
+
self._progress_callbacks: List[Callable[[Progress], None]] = []
|
|
57
|
+
self.last_progress: Optional[Progress] = None
|
|
58
|
+
self._cancelled = False
|
|
59
|
+
self._result = None
|
|
60
|
+
self._exception = None
|
|
61
|
+
self._resolved = False
|
|
62
|
+
waiter.on_complete = self._on_complete
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
# --------------------------------------------------------------- completion
|
|
66
|
+
def _resolve(self) -> None:
|
|
67
|
+
with self._lock:
|
|
68
|
+
if self._resolved:
|
|
69
|
+
return
|
|
70
|
+
try:
|
|
71
|
+
reply = self._session.resolve_reply(self._waiter)
|
|
72
|
+
self._result = getattr(reply, "value", None) if self._unwrap else reply
|
|
73
|
+
except BaseException as err: # noqa: BLE001 - any failure is the future's exception
|
|
74
|
+
self._exception = err
|
|
75
|
+
if isinstance(err, CancelledError):
|
|
76
|
+
self._cancelled = True
|
|
77
|
+
self._resolved = True
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
def _on_complete(self) -> None:
|
|
81
|
+
self._resolve()
|
|
82
|
+
for callback in list(self._done_callbacks):
|
|
83
|
+
try:
|
|
84
|
+
callback(self)
|
|
85
|
+
except Exception: # noqa: BLE001
|
|
86
|
+
self._session.logger.exception("done callback for %s raised", self.callable_name)
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
def _deliver_progress(self, progress: Progress) -> None:
|
|
90
|
+
self.last_progress = progress
|
|
91
|
+
for callback in list(self._progress_callbacks):
|
|
92
|
+
try:
|
|
93
|
+
callback(progress)
|
|
94
|
+
except Exception: # noqa: BLE001
|
|
95
|
+
self._session.logger.exception("progress callback for %s raised", self.callable_name)
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
# --------------------------------------------------------------- Future API
|
|
99
|
+
def wait(self, timeout: Optional[float] = None) -> bool:
|
|
100
|
+
return self._waiter.event.wait(timeout=timeout)
|
|
101
|
+
|
|
102
|
+
def done(self) -> bool:
|
|
103
|
+
return self._waiter.event.is_set()
|
|
104
|
+
|
|
105
|
+
def cancelled(self) -> bool:
|
|
106
|
+
return self._cancelled
|
|
107
|
+
|
|
108
|
+
def result(self, timeout: Optional[float] = None) -> T:
|
|
109
|
+
if not self.wait(timeout=timeout):
|
|
110
|
+
raise CompletionTimeout("remote call '{}' did not complete within {}s".format(self.callable_name, timeout))
|
|
111
|
+
self._resolve()
|
|
112
|
+
if self._exception is not None:
|
|
113
|
+
raise self._exception
|
|
114
|
+
return self._result
|
|
115
|
+
|
|
116
|
+
def exception(self, timeout: Optional[float] = None) -> Optional[BaseException]:
|
|
117
|
+
if not self.wait(timeout=timeout):
|
|
118
|
+
raise CompletionTimeout("remote call '{}' did not complete within {}s".format(self.callable_name, timeout))
|
|
119
|
+
self._resolve()
|
|
120
|
+
return self._exception
|
|
121
|
+
|
|
122
|
+
def cancel(self) -> bool:
|
|
123
|
+
if self.done():
|
|
124
|
+
return False
|
|
125
|
+
self._cancelled = True
|
|
126
|
+
self._session.send_cancel(self.correlation_id)
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
def add_done_callback(self, fn: Callable[["RemoteFuture"], None]) -> None:
|
|
130
|
+
with self._lock:
|
|
131
|
+
if not self.done():
|
|
132
|
+
self._done_callbacks.append(fn)
|
|
133
|
+
return
|
|
134
|
+
fn(self)
|
|
135
|
+
return
|
|
136
|
+
|
|
137
|
+
def add_progress_callback(self, fn: Callable[[Progress], None]) -> None:
|
|
138
|
+
self._progress_callbacks.append(fn)
|
|
139
|
+
return
|
|
140
|
+
|
|
141
|
+
def __repr__(self) -> str:
|
|
142
|
+
state = "cancelled" if self._cancelled else "done" if self.done() else "pending"
|
|
143
|
+
return "<RemoteFuture {} {}>".format(self.callable_name, state)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def wait_all(futures: Iterable[RemoteFuture], timeout: Optional[float] = None) -> bool:
|
|
147
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
148
|
+
for future in futures:
|
|
149
|
+
remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
|
|
150
|
+
if not future.wait(timeout=remaining):
|
|
151
|
+
return False
|
|
152
|
+
return True
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def as_completed(futures: Iterable[RemoteFuture], timeout: Optional[float] = None) -> Iterator[RemoteFuture]:
|
|
156
|
+
pending = list(futures)
|
|
157
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
158
|
+
while pending:
|
|
159
|
+
for future in list(pending):
|
|
160
|
+
if future.done():
|
|
161
|
+
pending.remove(future)
|
|
162
|
+
yield future
|
|
163
|
+
if not pending:
|
|
164
|
+
break
|
|
165
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
166
|
+
raise CompletionTimeout("{} remote call(s) still pending after {}s".format(len(pending), timeout))
|
|
167
|
+
time.sleep(0.005)
|
|
168
|
+
return
|
ccai/rpc/core/leases.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: leases
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: The lease-aware protocol an owned object implements to learn that its holder disappeared.
|
|
5
|
+
|
|
6
|
+
Lease mechanics live where they act: durations in :mod:`ccai.rpc.aspects`, lease state in the reference
|
|
7
|
+
table, renewal on the session heartbeat and the sweep in the heartbeat monitor.
|
|
8
|
+
|
|
9
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__author__ = "Myron Walker"
|
|
13
|
+
__copyright__ = "Copyright 2025, Code Craft AI LLC"
|
|
14
|
+
__credits__ = []
|
|
15
|
+
|
|
16
|
+
from typing import Protocol, runtime_checkable
|
|
17
|
+
|
|
18
|
+
import uuid
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@runtime_checkable
|
|
22
|
+
class ILeaseAware(Protocol):
|
|
23
|
+
"""
|
|
24
|
+
Implemented by objects that want a callback when a peer holding a reference to them goes away.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def on_lease_lapsed(self, peer_session_id: uuid.UUID) -> None:
|
|
28
|
+
"""
|
|
29
|
+
Called on a dispatch worker when the lease held by a peer on this object lapses.
|
|
30
|
+
|
|
31
|
+
:param peer_session_id: The session id of the peer whose lease on this object lapsed.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
__all__ = ["ILeaseAware"]
|