codecraftai-python-rpc 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. ccai/rpc/__init__.py +33 -0
  2. ccai/rpc/aspects.py +145 -0
  3. ccai/rpc/core/__init__.py +0 -0
  4. ccai/rpc/core/dispatch/__init__.py +0 -0
  5. ccai/rpc/core/dispatch/context.py +115 -0
  6. ccai/rpc/core/dispatch/lanes.py +77 -0
  7. ccai/rpc/core/flattenable.py +30 -0
  8. ccai/rpc/core/futures.py +168 -0
  9. ccai/rpc/core/leases.py +35 -0
  10. ccai/rpc/core/looper.py +107 -0
  11. ccai/rpc/core/looperpool.py +136 -0
  12. ccai/rpc/core/looperqueue.py +103 -0
  13. ccai/rpc/core/observability/__init__.py +10 -0
  14. ccai/rpc/core/observability/metrics.py +26 -0
  15. ccai/rpc/core/observability/state.py +51 -0
  16. ccai/rpc/core/protocol/__init__.py +16 -0
  17. ccai/rpc/core/protocol/constants.py +64 -0
  18. ccai/rpc/core/protocol/header.py +66 -0
  19. ccai/rpc/core/protocol/messages.py +265 -0
  20. ccai/rpc/core/proxy/__init__.py +0 -0
  21. ccai/rpc/core/proxy/cache.py +48 -0
  22. ccai/rpc/core/proxy/handlers.py +101 -0
  23. ccai/rpc/core/proxy/remoteproxy.py +251 -0
  24. ccai/rpc/core/proxy/table.py +207 -0
  25. ccai/rpc/core/proxy/wrappers.py +127 -0
  26. ccai/rpc/core/serialization/__init__.py +13 -0
  27. ccai/rpc/core/serialization/codec.py +371 -0
  28. ccai/rpc/core/serialization/placeholder.py +25 -0
  29. ccai/rpc/core/serialization/registry.py +85 -0
  30. ccai/rpc/core/serialization/tags.py +39 -0
  31. ccai/rpc/core/session/__init__.py +9 -0
  32. ccai/rpc/core/session/base.py +698 -0
  33. ccai/rpc/core/session/client.py +58 -0
  34. ccai/rpc/core/session/dispatch.py +124 -0
  35. ccai/rpc/core/session/heartbeat.py +96 -0
  36. ccai/rpc/core/session/server.py +68 -0
  37. ccai/rpc/core/transport/__init__.py +10 -0
  38. ccai/rpc/core/transport/base.py +91 -0
  39. ccai/rpc/core/transport/faults.py +81 -0
  40. ccai/rpc/core/transport/inprocess.py +22 -0
  41. ccai/rpc/core/transport/socketio.py +139 -0
  42. ccai/rpc/endpoints.py +44 -0
  43. ccai/rpc/errors.py +100 -0
  44. ccai/rpc/py.typed +0 -0
  45. ccai/rpc/rpcsocketclient.py +126 -0
  46. ccai/rpc/rpcsocketserver.py +226 -0
  47. ccai/rpc/security/__init__.py +10 -0
  48. ccai/rpc/security/auth.py +34 -0
  49. ccai/rpc/security/tls.py +53 -0
  50. codecraftai_python_rpc-1.3.0.dist-info/METADATA +105 -0
  51. codecraftai_python_rpc-1.3.0.dist-info/RECORD +53 -0
  52. codecraftai_python_rpc-1.3.0.dist-info/WHEEL +4 -0
  53. codecraftai_python_rpc-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,107 @@
1
+ """
2
+ .. module:: looper
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The Looper worker thread base class. Subclasses implement ``loop`` to process one packet.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import Optional
14
+
15
+ import logging
16
+ import threading
17
+
18
+ from ccai.rpc.errors import AbstractMethodError, LooperError
19
+ from ccai.rpc.core.looperqueue import LooperQueue, LooperQueueShutdown
20
+
21
+ logger = logging.getLogger("ccai.rpc.dispatch")
22
+
23
+
24
+ class Looper:
25
+ """
26
+ A worker that owns one thread and repeatedly pops a packet from its queue and calls ``loop``.
27
+ The thread exits when it pops a :class:`LooperQueueShutdown` sentinel or after ``stop`` was
28
+ requested and the next packet arrives. The exit gate is set on every exit path.
29
+ """
30
+
31
+ def __init__(self, queue: LooperQueue, name: Optional[str] = None, group: Optional[str] = None,
32
+ daemon: Optional[bool] = None, **kwargs) -> None:
33
+ self._queue = queue
34
+ self._name = name
35
+ self._group = group
36
+ self._daemon = daemon
37
+ self._kwargs = kwargs
38
+ self._running = False
39
+ self._stop_requested = False
40
+ self._thread = None
41
+ self._exit_gate = None
42
+ return
43
+
44
+ @property
45
+ def name(self) -> str:
46
+ if self._thread is not None:
47
+ return self._thread.name
48
+ return self._name if self._name is not None else "looper"
49
+
50
+ @property
51
+ def group(self) -> Optional[str]:
52
+ return self._group
53
+
54
+ @property
55
+ def is_running(self) -> bool:
56
+ return self._running
57
+
58
+ def loop(self, packet: object) -> None:
59
+ """
60
+ Processes one packet. Overridden by derived classes.
61
+ """
62
+ raise AbstractMethodError("Looper: 'loop' must be overloaded by derived classes.")
63
+
64
+ def start(self) -> None:
65
+ """
66
+ Starts the worker thread and returns once it has entered its work loop.
67
+ """
68
+ if self._thread is not None:
69
+ raise LooperError("Looper: start called on a looper that was already started.")
70
+ self._exit_gate = threading.Event()
71
+ start_gate = threading.Event()
72
+ self._thread = threading.Thread(target=self._loop_entry, name=self._name, args=(start_gate,), daemon=self._daemon)
73
+ self._thread.start()
74
+ start_gate.wait()
75
+ return
76
+
77
+ def stop(self) -> None:
78
+ """
79
+ Requests exit. The thread leaves its loop when the next packet arrives.
80
+ """
81
+ self._stop_requested = True
82
+ return
83
+
84
+ def wait_for_exit(self, timeout: Optional[float] = None) -> bool:
85
+ """
86
+ Waits for the thread to exit. Returns ``True`` when it has, ``False`` on timeout.
87
+ """
88
+ if self._exit_gate is None:
89
+ raise LooperError("Looper: wait_for_exit called before the looper was started.")
90
+ return self._exit_gate.wait(timeout=timeout)
91
+
92
+ def _loop_entry(self, start_gate: threading.Event) -> None:
93
+ self._running = True
94
+ start_gate.set()
95
+ try:
96
+ while True:
97
+ packet = self._queue.pop()
98
+ if isinstance(packet, LooperQueueShutdown) or packet is None or self._stop_requested:
99
+ break
100
+ try:
101
+ self.loop(packet)
102
+ except Exception:
103
+ logger.exception("Looper %s: unhandled exception processing packet %r", self.name, packet)
104
+ finally:
105
+ self._running = False
106
+ self._exit_gate.set()
107
+ return
@@ -0,0 +1,136 @@
1
+ """
2
+ .. module:: looperpool
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: A pool of Looper workers that grows with queue depth and shuts down in order.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ from typing import List, Optional, Sequence, Type
14
+
15
+ import threading
16
+
17
+ from ccai.rpc.errors import LooperError
18
+ from ccai.rpc.core.looper import Looper
19
+ from ccai.rpc.core.looperqueue import LooperQueue
20
+
21
+
22
+ class LooperPool:
23
+ """
24
+ Owns one :class:`LooperQueue` and a growable set of loopers. ``start_pool`` starts
25
+ ``min_loopers``; each push that leaves more than ``highwater`` packets queued starts one more
26
+ looper up to ``max_loopers``. The pool never shrinks; ``shutdown`` is how workers exit.
27
+ """
28
+
29
+ def __init__(self, looper_type: Type[Looper], group_name: str = "looper", min_loopers: int = 2,
30
+ max_loopers: int = 8, highwater: int = 4, daemon: bool = True, **looper_kwargs) -> None:
31
+ if min_loopers < 1 or max_loopers < 1:
32
+ raise LooperError("LooperPool: min_loopers and max_loopers must both be at least 1.")
33
+ if min_loopers > max_loopers:
34
+ raise LooperError("LooperPool: min_loopers={} is greater than max_loopers={}.".format(min_loopers, max_loopers))
35
+ self._looper_type = looper_type
36
+ self._group_name = group_name
37
+ self._min_loopers = min_loopers
38
+ self._max_loopers = max_loopers
39
+ self._highwater = highwater
40
+ self._daemon = daemon
41
+ self._looper_kwargs = looper_kwargs
42
+ self._queue = LooperQueue()
43
+ self._lock = threading.RLock()
44
+ self._loopers: List[Looper] = []
45
+ self._running = False
46
+ self._started = False
47
+ return
48
+
49
+ @property
50
+ def is_running(self) -> bool:
51
+ return self._running
52
+
53
+ @property
54
+ def worker_count(self) -> int:
55
+ with self._lock:
56
+ return len(self._loopers)
57
+
58
+ @property
59
+ def queue_depth(self) -> int:
60
+ return self._queue.depth
61
+
62
+ @property
63
+ def group_name(self) -> str:
64
+ return self._group_name
65
+
66
+ def start_pool(self) -> None:
67
+ with self._lock:
68
+ if self._running:
69
+ raise LooperError("LooperPool: start_pool called while the pool is already running.")
70
+ if self._started:
71
+ raise LooperError("LooperPool: a pool cannot be restarted after shutdown.")
72
+ self._running = True
73
+ self._started = True
74
+ for _ in range(0, self._min_loopers):
75
+ self._locked_start_looper()
76
+ return
77
+
78
+ def push_work(self, packet: object) -> int:
79
+ self._check_running("push_work")
80
+ depth = self._queue.push_work(packet)
81
+ self._grow_if_needed(depth)
82
+ return depth
83
+
84
+ def push_work_packets(self, packets: Sequence[object]) -> int:
85
+ self._check_running("push_work_packets")
86
+ depth = self._queue.push_work_packets(packets)
87
+ self._grow_if_needed(depth)
88
+ return depth
89
+
90
+ def shutdown(self, timeout: Optional[float] = None) -> List[Looper]:
91
+ """
92
+ Refuses further work, wakes every worker with a sentinel and waits for each to exit.
93
+ Returns the workers that did not exit within the timeout.
94
+ """
95
+ with self._lock:
96
+ self._running = False
97
+ loopers = list(self._loopers)
98
+ self._queue.shutdown(len(loopers))
99
+ stragglers = []
100
+ for looper in loopers:
101
+ if not looper.wait_for_exit(timeout=timeout):
102
+ stragglers.append(looper)
103
+ return stragglers
104
+
105
+ def describe(self) -> dict:
106
+ with self._lock:
107
+ return {
108
+ "group": self._group_name,
109
+ "running": self._running,
110
+ "worker_count": len(self._loopers),
111
+ "queue_depth": self._queue.depth,
112
+ "min_loopers": self._min_loopers,
113
+ "max_loopers": self._max_loopers,
114
+ "highwater": self._highwater,
115
+ "workers": [{"name": lp.name, "running": lp.is_running} for lp in self._loopers],
116
+ }
117
+
118
+ def _check_running(self, operation: str) -> None:
119
+ if not self._running:
120
+ raise LooperError("LooperPool: {} called while the pool is not running.".format(operation))
121
+ return
122
+
123
+ def _grow_if_needed(self, depth: int) -> None:
124
+ if depth > self._highwater:
125
+ with self._lock:
126
+ if self._running and len(self._loopers) < self._max_loopers:
127
+ self._locked_start_looper()
128
+ return
129
+
130
+ def _locked_start_looper(self) -> None:
131
+ index = len(self._loopers) + 1
132
+ looper_name = "{}-{}".format(self._group_name, index)
133
+ looper = self._looper_type(self._queue, name=looper_name, group=self._group_name, daemon=self._daemon, **self._looper_kwargs)
134
+ looper.start()
135
+ self._loopers.append(looper)
136
+ return
@@ -0,0 +1,103 @@
1
+ """
2
+ .. module:: looperqueue
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: A thread-safe work queue coupling a list, a counting semaphore and a lock, shared by the
5
+ LooperPool producer and its Looper 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 Optional, Sequence
15
+
16
+ import threading
17
+
18
+ from ccai.rpc.errors import LooperError
19
+
20
+
21
+ class LooperQueueShutdown:
22
+ """
23
+ Sentinel packet. A worker that pops one exits its loop.
24
+ """
25
+
26
+ def __repr__(self) -> str:
27
+ return "LooperQueueShutdown()"
28
+
29
+
30
+ class LooperQueue:
31
+ """
32
+ Thread-safe queue. The semaphore count always equals the number of packets appended and not
33
+ yet popped, which is what makes one wake-up per packet, and therefore shutdown, reliable.
34
+ """
35
+
36
+ def __init__(self) -> None:
37
+ self._queue = []
38
+ self._available = threading.Semaphore(value=0)
39
+ self._lock = threading.RLock()
40
+ self._shutdown = False
41
+ return
42
+
43
+ @property
44
+ def depth(self) -> int:
45
+ with self._lock:
46
+ return len(self._queue)
47
+
48
+ @property
49
+ def is_shutdown(self) -> bool:
50
+ with self._lock:
51
+ return self._shutdown
52
+
53
+ def push_work(self, packet: object) -> int:
54
+ """
55
+ Appends one packet and signals one available packet. Returns the resulting depth.
56
+ """
57
+ with self._lock:
58
+ if self._shutdown:
59
+ raise LooperError("LooperQueue: the queue is shut down, no more work is allowed to be queued.")
60
+ self._queue.append(packet)
61
+ depth = len(self._queue)
62
+ self._available.release()
63
+ return depth
64
+
65
+ def push_work_packets(self, packets: Sequence[object]) -> int:
66
+ """
67
+ Appends every packet and signals once per packet. Returns the resulting depth.
68
+ """
69
+ packets = list(packets)
70
+ with self._lock:
71
+ if self._shutdown:
72
+ raise LooperError("LooperQueue: the queue is shut down, no more work is allowed to be queued.")
73
+ self._queue.extend(packets)
74
+ depth = len(self._queue)
75
+ for _ in packets:
76
+ self._available.release()
77
+ return depth
78
+
79
+ def pop(self, timeout: Optional[float] = None) -> Optional[object]:
80
+ """
81
+ Blocks until a packet is available and returns it in first-in, first-out order. With a
82
+ timeout, returns ``None`` when nothing became available in time.
83
+ """
84
+ acquired = self._available.acquire(timeout=timeout) if timeout is not None else self._available.acquire()
85
+ if not acquired:
86
+ return None
87
+ with self._lock:
88
+ if len(self._queue) == 0:
89
+ return None
90
+ return self._queue.pop(0)
91
+
92
+ def shutdown(self, worker_count: int) -> None:
93
+ """
94
+ Marks the queue shut down and appends one sentinel per worker, signalling each, so every
95
+ blocked worker wakes exactly once after the pending work drains.
96
+ """
97
+ with self._lock:
98
+ self._shutdown = True
99
+ for _ in range(0, worker_count):
100
+ self._queue.append(LooperQueueShutdown())
101
+ for _ in range(0, worker_count):
102
+ self._available.release()
103
+ return
@@ -0,0 +1,10 @@
1
+ """
2
+ State dumps, metrics sinks and the wire trace logger name.
3
+ """
4
+
5
+ from ccai.rpc.core.observability.state import dump_state, install_dump_on_signal, live_clients, live_servers
6
+ from ccai.rpc.core.observability.metrics import register_metrics_sink, metrics_sinks
7
+
8
+ WIRE_LOGGER_NAME = "ccai.rpc.wire"
9
+
10
+ __all__ = ["dump_state", "install_dump_on_signal", "live_clients", "live_servers", "register_metrics_sink", "metrics_sinks", "WIRE_LOGGER_NAME"]
@@ -0,0 +1,26 @@
1
+ """
2
+ .. module:: metrics
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Package-level metrics sinks invoked with a session's counters when it closes.
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, List
14
+
15
+ import uuid
16
+
17
+ _sinks: List[Callable[[uuid.UUID, dict], None]] = []
18
+
19
+
20
+ def register_metrics_sink(sink: Callable[[uuid.UUID, dict], None]) -> None:
21
+ _sinks.append(sink)
22
+ return
23
+
24
+
25
+ def metrics_sinks() -> List[Callable[[uuid.UUID, dict], None]]:
26
+ return list(_sinks)
@@ -0,0 +1,51 @@
1
+ """
2
+ .. module:: state
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: dump_state renders every live server and client, and can be bound to a signal.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+ __author__ = "Myron Walker"
10
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
11
+ __credits__ = []
12
+
13
+ import json
14
+ import logging
15
+ import signal
16
+
17
+ logger = logging.getLogger("ccai.rpc.state")
18
+
19
+
20
+ def live_servers():
21
+ from ccai.rpc.rpcsocketserver import _live_servers
22
+ return list(_live_servers)
23
+
24
+
25
+ def live_clients():
26
+ from ccai.rpc.rpcsocketclient import _live_clients
27
+ return list(_live_clients)
28
+
29
+
30
+ def dump_state() -> str:
31
+ def render(value, indent=0):
32
+ pad = " " * indent
33
+ if isinstance(value, dict):
34
+ return "\n".join("{}{}:{}".format(pad, key, ("\n" + render(item, indent + 1)) if isinstance(item, (dict, list)) and item else " " + json.dumps(item, default=str))
35
+ for key, item in value.items())
36
+ if isinstance(value, list):
37
+ return "\n".join("{}-{}".format(pad, ("\n" + render(item, indent + 1)) if isinstance(item, (dict, list)) else " " + json.dumps(item, default=str)) for item in value)
38
+ return pad + json.dumps(value, default=str)
39
+
40
+ state = {"servers": [s.describe() for s in live_servers()], "clients": [c.describe() for c in live_clients()]}
41
+ return render(state)
42
+
43
+
44
+ def install_dump_on_signal(signum: int = getattr(signal, "SIGUSR1", 0)) -> bool:
45
+ if not signum:
46
+ return False
47
+ try:
48
+ signal.signal(signum, lambda *_: logger.warning("RPC state dump\n%s", dump_state()))
49
+ except (ValueError, OSError, AttributeError):
50
+ return False
51
+ return True
@@ -0,0 +1,16 @@
1
+ """
2
+ The wire protocol: framing, the fixed header, the message vocabulary and the message classes.
3
+ """
4
+
5
+ from ccai.rpc.core.protocol.constants import (
6
+ DEFAULT_MAX_MESSAGE_SIZE, FRAME_SIZE_BYTES, HEADER_SIZE, MIN_SUPPORTED_VERSION, PROTOCOL_VERSION,
7
+ ExceptionCode, MessageType, ReplyCode, RequestCode,
8
+ )
9
+ from ccai.rpc.core.protocol.header import MessageHeader, frame, read_frame_size
10
+ from ccai.rpc.core.protocol.messages import (
11
+ REGISTRY, REPLY_FOR_REQUEST, ExceptionMessage, Message,
12
+ ReplyCall, ReplyCancel, ReplyClose, ReplyDelAttr, ReplyGetAttr, ReplyGetService, ReplyHello, ReplyPing,
13
+ ReplyProgress, ReplyRelease, ReplyRenew, ReplySetAttr,
14
+ RequestCall, RequestCancel, RequestClose, RequestDelAttr, RequestGetAttr, RequestGetService, RequestHello,
15
+ RequestPing, RequestProgress, RequestRelease, RequestRenew, RequestSetAttr,
16
+ )
@@ -0,0 +1,64 @@
1
+ """
2
+ .. module:: constants
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Protocol versions, sizes and the message type and code vocabularies.
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 enum import IntEnum
14
+
15
+ PROTOCOL_VERSION = 1
16
+ MIN_SUPPORTED_VERSION = 1
17
+ HEADER_SIZE = 24
18
+ FRAME_SIZE_BYTES = 8
19
+ DEFAULT_MAX_MESSAGE_SIZE = 64 * 1024 * 1024
20
+
21
+
22
+ class MessageType(IntEnum):
23
+ REQUEST = 1
24
+ REPLY = 2
25
+ EXCEPTION = 3
26
+
27
+
28
+ class RequestCode(IntEnum):
29
+ HELLO = 1
30
+ PING = 2
31
+ CLOSE = 3
32
+ GETSERVICE = 4
33
+ GETATTR = 5
34
+ SETATTR = 6
35
+ DELATTR = 7
36
+ CALL = 8
37
+ RELEASE = 9
38
+ RENEW = 10
39
+ CANCEL = 11
40
+ PROGRESS = 12
41
+
42
+
43
+ class ReplyCode(IntEnum):
44
+ HELLO = 1
45
+ PING = 2
46
+ CLOSE = 3
47
+ GETSERVICE = 4
48
+ GETATTR = 5
49
+ SETATTR = 6
50
+ DELATTR = 7
51
+ CALL = 8
52
+ RELEASE = 9
53
+ RENEW = 10
54
+ CANCEL = 11
55
+ PROGRESS = 12
56
+
57
+
58
+ class ExceptionCode(IntEnum):
59
+ REMOTE_EXCEPTION = 1
60
+ PROTOCOL_ERROR = 2
61
+ UNKNOWN_REFERENCE = 3
62
+ LEASE_EXPIRED = 4
63
+ CANCELLED = 5
64
+ UNAUTHORIZED = 6
@@ -0,0 +1,66 @@
1
+ """
2
+ .. module:: header
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: The fixed 24 byte message header and the frame size helpers.
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 dataclasses import dataclass
14
+
15
+ import struct
16
+ import uuid
17
+
18
+ from ccai.rpc.errors import ProtocolError
19
+ from ccai.rpc.core.protocol.constants import (
20
+ DEFAULT_MAX_MESSAGE_SIZE, FRAME_SIZE_BYTES, HEADER_SIZE, MIN_SUPPORTED_VERSION, PROTOCOL_VERSION, MessageType,
21
+ )
22
+
23
+ _HEADER_FORMAT = "!HBB16sI"
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class MessageHeader:
28
+ version: int
29
+ mtype: MessageType
30
+ mcode: int
31
+ correlation_id: uuid.UUID
32
+ payload_length: int
33
+
34
+ def pack(self) -> bytes:
35
+ return struct.pack(_HEADER_FORMAT, self.version, int(self.mtype), int(self.mcode), self.correlation_id.bytes, self.payload_length)
36
+
37
+ @classmethod
38
+ def unpack(cls, data: bytes) -> "MessageHeader":
39
+ if len(data) < HEADER_SIZE:
40
+ raise ProtocolError("message shorter than the {} byte header: {} bytes".format(HEADER_SIZE, len(data)))
41
+ version, mtype_raw, mcode, cid_bytes, payload_length = struct.unpack(_HEADER_FORMAT, data[:HEADER_SIZE])
42
+ if version < MIN_SUPPORTED_VERSION or version > PROTOCOL_VERSION:
43
+ raise ProtocolError("unsupported protocol version {} (this end supports {} to {})".format(
44
+ version, MIN_SUPPORTED_VERSION, PROTOCOL_VERSION))
45
+ try:
46
+ mtype = MessageType(mtype_raw)
47
+ except ValueError:
48
+ raise ProtocolError("unknown message type {}".format(mtype_raw)) from None
49
+ return cls(version, mtype, mcode, uuid.UUID(bytes=cid_bytes), payload_length)
50
+
51
+
52
+ def frame(message: bytes) -> bytes:
53
+ if len(message) == 0:
54
+ raise ProtocolError("a zero-length message is invalid")
55
+ return struct.pack("!Q", len(message)) + message
56
+
57
+
58
+ def read_frame_size(size_bytes: bytes, max_message_size: int = DEFAULT_MAX_MESSAGE_SIZE) -> int:
59
+ if len(size_bytes) != FRAME_SIZE_BYTES:
60
+ raise ProtocolError("frame size header must be {} bytes, got {}".format(FRAME_SIZE_BYTES, len(size_bytes)))
61
+ size = struct.unpack("!Q", size_bytes)[0]
62
+ if size == 0:
63
+ raise ProtocolError("a zero-length message is invalid")
64
+ if size > max_message_size:
65
+ raise ProtocolError("frame announces {} bytes, above the maximum message size of {}".format(size, max_message_size))
66
+ return size