bare-rpc 0.0.1__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.
bare_rpc/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """bare-rpc message and frame codec, wire-compatible with the JS reference."""
2
+
3
+ from .constants import StreamFlag, Type
4
+ from .incoming import IncomingEvent, IncomingRequest
5
+ from .incoming_stream import IncomingStream
6
+ from .messages import (
7
+ DecodedMessage,
8
+ RequestMessage,
9
+ ResponseMessage,
10
+ RPCRemoteError,
11
+ StreamMessage,
12
+ decode_frame,
13
+ encode_error_response,
14
+ encode_event,
15
+ encode_request,
16
+ encode_response,
17
+ encode_stream,
18
+ )
19
+ from .outgoing_stream import OutgoingStream
20
+ from .rpc import RPC
21
+
22
+ __all__ = [
23
+ "DecodedMessage",
24
+ "IncomingEvent",
25
+ "IncomingRequest",
26
+ "IncomingStream",
27
+ "OutgoingStream",
28
+ "RPC",
29
+ "RPCRemoteError",
30
+ "RequestMessage",
31
+ "ResponseMessage",
32
+ "StreamFlag",
33
+ "StreamMessage",
34
+ "Type",
35
+ "decode_frame",
36
+ "encode_error_response",
37
+ "encode_event",
38
+ "encode_request",
39
+ "encode_response",
40
+ "encode_stream",
41
+ ]
bare_rpc/constants.py ADDED
@@ -0,0 +1,17 @@
1
+ class Type:
2
+ REQUEST = 1
3
+ RESPONSE = 2
4
+ STREAM = 3
5
+
6
+
7
+ class StreamFlag:
8
+ OPEN = 0x1
9
+ CLOSE = 0x2
10
+ PAUSE = 0x4
11
+ RESUME = 0x8
12
+ DATA = 0x10
13
+ END = 0x20
14
+ DESTROY = 0x40
15
+ ERROR = 0x80
16
+ REQUEST = 0x100
17
+ RESPONSE = 0x200
bare_rpc/incoming.py ADDED
@@ -0,0 +1,43 @@
1
+ from .constants import StreamFlag
2
+ from .messages import RPCRemoteError, encode_error_response, encode_response
3
+ from .outgoing_stream import OutgoingStream
4
+
5
+
6
+ class IncomingEvent:
7
+ def __init__(self, command, data):
8
+ self.command = command
9
+ self.data = data
10
+
11
+
12
+ class IncomingRequest:
13
+ def __init__(self, rpc, id, command, data):
14
+ self._rpc = rpc
15
+ self.id = id
16
+ self.command = command
17
+ self.data = data
18
+ self.request_stream = None
19
+ self._replied = False
20
+
21
+ async def reply(self, data=None):
22
+ if self._replied:
23
+ return
24
+ self._replied = True
25
+ self._rpc._send(encode_response(self.id, data=data))
26
+
27
+ async def reject(self, error):
28
+ if self._replied:
29
+ return
30
+ self._replied = True
31
+ if isinstance(error, RPCRemoteError):
32
+ message, code, errno = error.message, error.code, error.errno
33
+ else:
34
+ message = str(error)
35
+ code = getattr(error, "code", "") or ""
36
+ errno = getattr(error, "errno", 0) or 0
37
+ self._rpc._send(encode_error_response(self.id, message, code, errno))
38
+
39
+ async def create_response_stream(self):
40
+ outgoing = OutgoingStream(self._rpc, self.id, StreamFlag.RESPONSE)
41
+ self._rpc._outgoing_streams[self.id] = outgoing
42
+ self._rpc._send(encode_response(self.id, stream=StreamFlag.OPEN))
43
+ return outgoing
@@ -0,0 +1,91 @@
1
+ import asyncio
2
+ from collections import deque
3
+
4
+ from .constants import StreamFlag
5
+ from .messages import encode_stream
6
+
7
+ HIGH_WATER_MARK = 16
8
+ LOW_WATER_MARK = 4
9
+
10
+
11
+ class IncomingStream:
12
+ def __init__(self, rpc, id, mask):
13
+ self._rpc = rpc
14
+ self._id = id
15
+ self._mask = mask
16
+ self._buffer = deque()
17
+ self._paused = False
18
+ self._finished = False
19
+ self._error = None
20
+ self._waiter = None
21
+
22
+ def __aiter__(self):
23
+ return self
24
+
25
+ async def __anext__(self):
26
+ if self._buffer:
27
+ chunk = self._buffer.popleft()
28
+ if self._paused and len(self._buffer) <= LOW_WATER_MARK:
29
+ self._paused = False
30
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.RESUME))
31
+ return chunk
32
+ if self._error is not None:
33
+ raise self._error
34
+ if self._finished:
35
+ raise StopAsyncIteration
36
+ self._waiter = asyncio.get_running_loop().create_future()
37
+ try:
38
+ return await self._waiter
39
+ finally:
40
+ self._waiter = None
41
+
42
+ def push(self, data):
43
+ if self._finished:
44
+ return
45
+ if self._waiter is not None and not self._waiter.done():
46
+ waiter = self._waiter
47
+ self._waiter = None
48
+ waiter.set_result(data)
49
+ return
50
+ self._buffer.append(data)
51
+ if not self._paused and len(self._buffer) >= HIGH_WATER_MARK:
52
+ self._paused = True
53
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.PAUSE))
54
+
55
+ def end(self):
56
+ if self._finished:
57
+ return
58
+ self._finished = True
59
+ self._wake(StopAsyncIteration())
60
+ self._rpc._incoming_streams.pop(self._id, None)
61
+
62
+ def destroy(self, error=None):
63
+ if self._finished:
64
+ return
65
+ self._finished = True
66
+ self._error = error
67
+ if error is not None:
68
+ self._rpc._send(
69
+ encode_stream(
70
+ self._id,
71
+ self._mask | StreamFlag.DESTROY | StreamFlag.ERROR,
72
+ error=error,
73
+ )
74
+ )
75
+ else:
76
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.DESTROY))
77
+ self._wake(error or StopAsyncIteration())
78
+ self._rpc._incoming_streams.pop(self._id, None)
79
+
80
+ def _abort(self, error):
81
+ # Local teardown for _fail/close: fail a parked waiter, no wire send,
82
+ # no map mutation (the caller clears the maps).
83
+ self._finished = True
84
+ self._error = error
85
+ self._wake(error)
86
+
87
+ def _wake(self, exc):
88
+ if self._waiter is not None and not self._waiter.done():
89
+ waiter = self._waiter
90
+ self._waiter = None
91
+ waiter.set_exception(exc)
bare_rpc/messages.py ADDED
@@ -0,0 +1,201 @@
1
+ from dataclasses import dataclass
2
+
3
+ import compact_encoding as cenc
4
+
5
+ from .constants import StreamFlag, Type
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class RPCRemoteError(Exception):
10
+ message: str
11
+ code: str
12
+ errno: int
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class RequestMessage:
17
+ id: int
18
+ command: int
19
+ stream: int
20
+ data: bytes | None
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ResponseMessage:
25
+ id: int
26
+ stream: int
27
+ data: bytes | None
28
+ error: RPCRemoteError | None
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class StreamMessage:
33
+ id: int
34
+ flags: int
35
+ data: bytes | None
36
+ error: RPCRemoteError | None
37
+
38
+
39
+ DecodedMessage = RequestMessage | ResponseMessage | StreamMessage
40
+
41
+
42
+ def _encode_frame(preencode, encode, msg) -> bytes:
43
+ state = cenc.State()
44
+ preencode(state, msg)
45
+ state.allocate()
46
+ encode(state, msg)
47
+ body = bytes(state.buffer)
48
+ return cenc.encode(cenc.uint32, len(body)) + body
49
+
50
+
51
+ def _preencode_request(state, msg):
52
+ cenc.uint.preencode(state, Type.REQUEST)
53
+ cenc.uint.preencode(state, msg.id)
54
+ cenc.uint.preencode(state, msg.command)
55
+ cenc.uint.preencode(state, msg.stream)
56
+ if msg.stream == 0:
57
+ cenc.buffer.preencode(state, msg.data or b"")
58
+
59
+
60
+ def _encode_request(state, msg):
61
+ cenc.uint.encode(state, Type.REQUEST)
62
+ cenc.uint.encode(state, msg.id)
63
+ cenc.uint.encode(state, msg.command)
64
+ cenc.uint.encode(state, msg.stream)
65
+ if msg.stream == 0:
66
+ cenc.buffer.encode(state, msg.data or b"")
67
+
68
+
69
+ def _decode_request(state):
70
+ id = cenc.uint.decode(state)
71
+ command = cenc.uint.decode(state)
72
+ stream = cenc.uint.decode(state)
73
+ data = cenc.buffer.decode(state) if stream == 0 else None
74
+ return RequestMessage(id=id, command=command, stream=stream, data=data)
75
+
76
+
77
+ def encode_request(id, command, *, stream=0, data=None):
78
+ return _encode_frame(
79
+ _preencode_request, _encode_request, RequestMessage(id, command, stream, data)
80
+ )
81
+
82
+
83
+ def encode_event(command, data=None):
84
+ return encode_request(0, command, data=data)
85
+
86
+
87
+ def _preencode_response(state, msg):
88
+ cenc.uint.preencode(state, Type.RESPONSE)
89
+ cenc.uint.preencode(state, msg.id)
90
+ is_error = msg.error is not None
91
+ cenc.bool.preencode(state, is_error)
92
+ cenc.uint.preencode(state, msg.stream)
93
+ if is_error:
94
+ cenc.utf8.preencode(state, msg.error.message)
95
+ cenc.utf8.preencode(state, msg.error.code)
96
+ cenc.int.preencode(state, msg.error.errno)
97
+ elif msg.stream == 0:
98
+ cenc.buffer.preencode(state, msg.data or b"")
99
+
100
+
101
+ def _encode_response(state, msg):
102
+ cenc.uint.encode(state, Type.RESPONSE)
103
+ cenc.uint.encode(state, msg.id)
104
+ is_error = msg.error is not None
105
+ cenc.bool.encode(state, is_error)
106
+ cenc.uint.encode(state, msg.stream)
107
+ if is_error:
108
+ cenc.utf8.encode(state, msg.error.message)
109
+ cenc.utf8.encode(state, msg.error.code)
110
+ cenc.int.encode(state, msg.error.errno)
111
+ elif msg.stream == 0:
112
+ cenc.buffer.encode(state, msg.data or b"")
113
+
114
+
115
+ def _decode_response(state):
116
+ id = cenc.uint.decode(state)
117
+ is_error = cenc.bool.decode(state)
118
+ stream = cenc.uint.decode(state)
119
+ if is_error:
120
+ message = cenc.utf8.decode(state)
121
+ code = cenc.utf8.decode(state)
122
+ errno = cenc.int.decode(state)
123
+ error = RPCRemoteError(message=message, code=code, errno=errno)
124
+ return ResponseMessage(id=id, stream=stream, data=None, error=error)
125
+ data = cenc.buffer.decode(state) if stream == 0 else None
126
+ return ResponseMessage(id=id, stream=stream, data=data, error=None)
127
+
128
+
129
+ def encode_response(id, *, stream=0, data=None):
130
+ return _encode_frame(
131
+ _preencode_response, _encode_response, ResponseMessage(id, stream, data, None)
132
+ )
133
+
134
+
135
+ def encode_error_response(id, message, code, errno=0):
136
+ error = RPCRemoteError(message=message, code=code, errno=errno)
137
+ return _encode_frame(
138
+ _preencode_response, _encode_response, ResponseMessage(id, 0, None, error)
139
+ )
140
+
141
+
142
+ def _preencode_stream(state, msg):
143
+ cenc.uint.preencode(state, Type.STREAM)
144
+ cenc.uint.preencode(state, msg.id)
145
+ cenc.uint.preencode(state, msg.flags)
146
+ if msg.flags & StreamFlag.ERROR:
147
+ cenc.utf8.preencode(state, msg.error.message)
148
+ cenc.utf8.preencode(state, msg.error.code)
149
+ cenc.int.preencode(state, msg.error.errno)
150
+ elif msg.flags & StreamFlag.DATA:
151
+ cenc.buffer.preencode(state, msg.data or b"")
152
+
153
+
154
+ def _encode_stream(state, msg):
155
+ cenc.uint.encode(state, Type.STREAM)
156
+ cenc.uint.encode(state, msg.id)
157
+ cenc.uint.encode(state, msg.flags)
158
+ if msg.flags & StreamFlag.ERROR:
159
+ cenc.utf8.encode(state, msg.error.message)
160
+ cenc.utf8.encode(state, msg.error.code)
161
+ cenc.int.encode(state, msg.error.errno)
162
+ elif msg.flags & StreamFlag.DATA:
163
+ cenc.buffer.encode(state, msg.data or b"")
164
+
165
+
166
+ def _decode_stream(state):
167
+ id = cenc.uint.decode(state)
168
+ flags = cenc.uint.decode(state)
169
+ if flags & StreamFlag.ERROR:
170
+ message = cenc.utf8.decode(state)
171
+ code = cenc.utf8.decode(state)
172
+ errno = cenc.int.decode(state)
173
+ error = RPCRemoteError(message=message, code=code, errno=errno)
174
+ return StreamMessage(id=id, flags=flags, data=None, error=error)
175
+ if flags & StreamFlag.DATA:
176
+ data = cenc.buffer.decode(state)
177
+ return StreamMessage(id=id, flags=flags, data=data, error=None)
178
+ return StreamMessage(id=id, flags=flags, data=None, error=None)
179
+
180
+
181
+ def encode_stream(id, flags, *, data=None, error=None):
182
+ if flags & StreamFlag.ERROR and error is None:
183
+ raise ValueError("stream ERROR flag set but error is None")
184
+ return _encode_frame(
185
+ _preencode_stream, _encode_stream, StreamMessage(id, flags, data, error)
186
+ )
187
+
188
+
189
+ def decode_frame(frame):
190
+ state = cenc.State(frame)
191
+ length = cenc.uint32.decode(state)
192
+ if state.remaining < length:
193
+ raise cenc.OutOfBounds("frame body shorter than declared length")
194
+ type_ = cenc.uint.decode(state)
195
+ if type_ == Type.REQUEST:
196
+ return _decode_request(state)
197
+ if type_ == Type.RESPONSE:
198
+ return _decode_response(state)
199
+ if type_ == Type.STREAM:
200
+ return _decode_stream(state)
201
+ return None
@@ -0,0 +1,71 @@
1
+ import asyncio
2
+
3
+ from .constants import StreamFlag
4
+ from .messages import encode_stream
5
+
6
+
7
+ class OutgoingStream:
8
+ def __init__(self, rpc, id, mask):
9
+ self._rpc = rpc
10
+ self._id = id
11
+ self._mask = mask
12
+ self._ended = False
13
+ self._error = None
14
+ self._corked = False
15
+ self._uncork = asyncio.Event()
16
+ self._uncork.set() # start uncorked
17
+
18
+ async def write(self, data):
19
+ if self._ended:
20
+ raise self._error or RuntimeError("stream ended")
21
+ while self._corked and not self._ended:
22
+ await self._uncork.wait()
23
+ if self._ended:
24
+ raise self._error or RuntimeError("stream ended")
25
+ self._rpc._send(
26
+ encode_stream(self._id, self._mask | StreamFlag.DATA, data=data)
27
+ )
28
+
29
+ async def end(self):
30
+ if self._ended:
31
+ return
32
+ self._ended = True
33
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.END))
34
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.CLOSE))
35
+ self._uncork.set()
36
+ self._rpc._outgoing_streams.pop(self._id, None)
37
+
38
+ async def destroy(self, error=None):
39
+ if self._ended:
40
+ return
41
+ self._ended = True
42
+ # An errorless destroy() sends a bare CLOSE, which the peer reader treats
43
+ # as a clean end (StopAsyncIteration), not an abrupt error-close.
44
+ if error is not None:
45
+ self._rpc._send(
46
+ encode_stream(
47
+ self._id,
48
+ self._mask | StreamFlag.CLOSE | StreamFlag.ERROR,
49
+ error=error,
50
+ )
51
+ )
52
+ else:
53
+ self._rpc._send(encode_stream(self._id, self._mask | StreamFlag.CLOSE))
54
+ self._uncork.set()
55
+ self._rpc._outgoing_streams.pop(self._id, None)
56
+
57
+ def cork(self):
58
+ self._corked = True
59
+ self._uncork.clear()
60
+
61
+ def uncork(self):
62
+ self._corked = False
63
+ self._uncork.set()
64
+
65
+ def _abort(self, error):
66
+ # Local teardown for _fail/close: mark ended + store the error and wake
67
+ # a suspended write so it raises. Sends nothing (the connection is dead)
68
+ # and does not touch the maps (the caller clears them).
69
+ self._ended = True
70
+ self._error = error
71
+ self._uncork.set()
bare_rpc/py.typed ADDED
File without changes
bare_rpc/rpc.py ADDED
@@ -0,0 +1,327 @@
1
+ import asyncio
2
+ import inspect
3
+ from collections import deque
4
+
5
+ from .constants import StreamFlag
6
+ from .incoming import IncomingEvent, IncomingRequest
7
+ from .incoming_stream import IncomingStream
8
+ from .messages import (
9
+ RequestMessage,
10
+ ResponseMessage,
11
+ StreamMessage,
12
+ decode_frame,
13
+ encode_event,
14
+ encode_request,
15
+ encode_stream,
16
+ )
17
+ from .outgoing_stream import OutgoingStream
18
+
19
+ DEFAULT_MAX_FRAME_SIZE = 16 * 1024 * 1024
20
+
21
+
22
+ async def _maybe_await(result):
23
+ if inspect.isawaitable(result):
24
+ await result
25
+
26
+
27
+ class RPC:
28
+ def __init__(
29
+ self,
30
+ send,
31
+ *,
32
+ on_request=None,
33
+ on_event=None,
34
+ on_error=None,
35
+ max_frame_size=DEFAULT_MAX_FRAME_SIZE,
36
+ ):
37
+ if max_frame_size <= 0:
38
+ raise ValueError("max_frame_size must be positive")
39
+ self._send_cb = send
40
+ self._on_request = on_request
41
+ self._on_event = on_event
42
+ self._on_error = on_error
43
+ self._max_frame_size = max_frame_size
44
+ self._id = 0
45
+ self._pending = {}
46
+ self._buffer = bytearray()
47
+ self._tasks = set()
48
+ self._failed = None
49
+ self._outbound = deque()
50
+ self._outbound_ready = asyncio.Event()
51
+ self._writer_task = None
52
+ self._closed = False
53
+ self._outgoing_streams = {}
54
+ self._incoming_streams = {}
55
+ self._pending_response_streams = {}
56
+
57
+ def _send(self, frame):
58
+ if self._failed is not None or self._closed:
59
+ return
60
+ self._outbound.append(frame)
61
+ self._outbound_ready.set()
62
+ self._ensure_writer()
63
+
64
+ def _ensure_writer(self):
65
+ if self._writer_task is None:
66
+ self._writer_task = asyncio.create_task(self._writer())
67
+
68
+ async def _writer(self):
69
+ while self._failed is None and not self._closed:
70
+ await self._outbound_ready.wait()
71
+ self._outbound_ready.clear()
72
+ while self._outbound:
73
+ frame = self._outbound.popleft()
74
+ try:
75
+ await _maybe_await(self._send_cb(frame))
76
+ except Exception as exc:
77
+ self._fail(exc)
78
+ return
79
+
80
+ def close(self):
81
+ if self._failed is not None or self._closed:
82
+ return
83
+ self._closed = True
84
+ self._outbound.clear()
85
+ self._outbound_ready.set()
86
+ self._reject_all(RuntimeError("RPC is closed"))
87
+
88
+ async def request(self, command, data=None):
89
+ if self._failed is not None:
90
+ raise self._failed
91
+ if self._closed:
92
+ raise RuntimeError("RPC is closed")
93
+ self._id += 1
94
+ request_id = self._id
95
+ future = asyncio.get_running_loop().create_future()
96
+ self._pending[request_id] = future
97
+ self._send(encode_request(request_id, command, data=data))
98
+ return await future
99
+
100
+ async def request_with_response_stream(self, command, data=None):
101
+ if self._failed is not None:
102
+ raise self._failed
103
+ if self._closed:
104
+ raise RuntimeError("RPC is closed")
105
+ self._id += 1
106
+ request_id = self._id
107
+ future = asyncio.get_running_loop().create_future()
108
+ self._pending_response_streams[request_id] = future
109
+ self._send(encode_request(request_id, command, data=data))
110
+ return await future
111
+
112
+ async def stream_request(self, command):
113
+ if self._failed is not None:
114
+ raise self._failed
115
+ if self._closed:
116
+ raise RuntimeError("RPC is closed")
117
+ self._id += 1
118
+ request_id = self._id
119
+ future = asyncio.get_running_loop().create_future()
120
+ self._pending[request_id] = future
121
+ outgoing = OutgoingStream(self, request_id, StreamFlag.REQUEST)
122
+ self._outgoing_streams[request_id] = outgoing
123
+ self._send(encode_request(request_id, command, stream=StreamFlag.OPEN))
124
+ return outgoing, future
125
+
126
+ async def create_bidirectional_stream(self, command):
127
+ if self._failed is not None:
128
+ raise self._failed
129
+ if self._closed:
130
+ raise RuntimeError("RPC is closed")
131
+ self._id += 1
132
+ request_id = self._id
133
+ future = asyncio.get_running_loop().create_future()
134
+ self._pending_response_streams[request_id] = future
135
+ outgoing = OutgoingStream(self, request_id, StreamFlag.REQUEST)
136
+ self._outgoing_streams[request_id] = outgoing
137
+ self._send(encode_request(request_id, command, stream=StreamFlag.OPEN))
138
+ incoming = await future
139
+ return outgoing, incoming
140
+
141
+ async def event(self, command, data=None):
142
+ if self._failed is not None or self._closed:
143
+ return
144
+ self._send(encode_event(command, data=data))
145
+
146
+ async def receive(self, data):
147
+ if self._failed is not None or self._closed:
148
+ return
149
+ self._buffer += data
150
+ while True:
151
+ if len(self._buffer) < 4:
152
+ return
153
+ length = int.from_bytes(self._buffer[0:4], "little")
154
+ if 4 + length > self._max_frame_size:
155
+ self._fail(ValueError("frame exceeds max_frame_size"))
156
+ return
157
+ if len(self._buffer) < 4 + length:
158
+ return
159
+ frame = bytes(self._buffer[: 4 + length])
160
+ del self._buffer[: 4 + length]
161
+ try:
162
+ message = decode_frame(frame)
163
+ except Exception as exc:
164
+ self._fail(exc)
165
+ return
166
+ self._dispatch(message)
167
+
168
+ def _dispatch(self, message):
169
+ if message is None:
170
+ return
171
+ if isinstance(message, RequestMessage):
172
+ if message.stream & StreamFlag.OPEN:
173
+ self._on_request_stream_open(message)
174
+ elif message.id == 0:
175
+ if self._on_event is not None:
176
+ self._spawn(
177
+ self._run_event(IncomingEvent(message.command, message.data))
178
+ )
179
+ elif self._on_request is not None:
180
+ req = IncomingRequest(self, message.id, message.command, message.data)
181
+ self._spawn(self._run_request(req))
182
+ elif isinstance(message, ResponseMessage):
183
+ if message.stream & StreamFlag.OPEN:
184
+ self._on_response_stream_open(message)
185
+ return
186
+ if message.id == 0:
187
+ return
188
+ future = self._pending.pop(message.id, None)
189
+ if future is not None:
190
+ if not future.done():
191
+ if message.error is not None:
192
+ future.set_exception(message.error)
193
+ else:
194
+ future.set_result(message.data)
195
+ return
196
+ pending_stream = self._pending_response_streams.pop(message.id, None)
197
+ if pending_stream is not None and not pending_stream.done():
198
+ if message.error is not None:
199
+ pending_stream.set_exception(message.error)
200
+ else:
201
+ pending_stream.set_exception(
202
+ RuntimeError("expected a response stream")
203
+ )
204
+ elif isinstance(message, StreamMessage):
205
+ self._on_stream(message)
206
+
207
+ def _on_response_stream_open(self, message):
208
+ pending = self._pending_response_streams.pop(message.id, None)
209
+ if pending is None or pending.done():
210
+ return
211
+ incoming = IncomingStream(self, message.id, StreamFlag.RESPONSE)
212
+ self._incoming_streams[message.id] = incoming
213
+ self._send(encode_stream(message.id, StreamFlag.RESPONSE | StreamFlag.OPEN))
214
+ pending.set_result(incoming)
215
+
216
+ def _on_request_stream_open(self, message):
217
+ if self._on_request is None:
218
+ return
219
+ incoming = IncomingStream(self, message.id, StreamFlag.REQUEST)
220
+ self._incoming_streams[message.id] = incoming
221
+ self._send(encode_stream(message.id, StreamFlag.REQUEST | StreamFlag.OPEN))
222
+ req = IncomingRequest(self, message.id, message.command, message.data)
223
+ req.request_stream = incoming
224
+ self._spawn(self._run_stream_request(req))
225
+
226
+ async def _run_stream_request(self, req):
227
+ # Unlike _run_request, a throwing stream-open handler is NOT auto-rejected:
228
+ # by the time we're here the id has already been promoted to a stream (its
229
+ # OPEN ack is already on the wire), so a reject would send a spurious
230
+ # second/duplicate response on a stream id, not a clean error for request
231
+ # id 0. The generated code is responsible for replying / destroying its
232
+ # streams. Matches Swift's try? on handleRequestStreamOpen.
233
+ try:
234
+ await _maybe_await(self._on_request(req))
235
+ except Exception:
236
+ pass
237
+
238
+ def _on_stream(self, message):
239
+ flags = message.flags
240
+ if flags & StreamFlag.OPEN:
241
+ # STREAM|OPEN is a protocol ack, not consumed by this runtime (kept
242
+ # for wire parity / future cross-runtime interop); intentionally a
243
+ # no-op on receipt, not dead code.
244
+ return
245
+ if flags & StreamFlag.CLOSE:
246
+ stream = self._incoming_streams.get(message.id)
247
+ if stream is None:
248
+ return
249
+ if flags & StreamFlag.ERROR:
250
+ stream.destroy(message.error)
251
+ else:
252
+ stream.end()
253
+ return
254
+ if flags & StreamFlag.PAUSE:
255
+ stream = self._outgoing_streams.get(message.id)
256
+ if stream is not None:
257
+ stream.cork()
258
+ return
259
+ if flags & StreamFlag.RESUME:
260
+ stream = self._outgoing_streams.get(message.id)
261
+ if stream is not None:
262
+ stream.uncork()
263
+ return
264
+ if flags & StreamFlag.DATA:
265
+ stream = self._incoming_streams.get(message.id)
266
+ if stream is not None:
267
+ stream.push(message.data)
268
+ return
269
+ if flags & StreamFlag.END:
270
+ stream = self._incoming_streams.get(message.id)
271
+ if stream is not None:
272
+ stream.end()
273
+ return
274
+ if flags & StreamFlag.DESTROY:
275
+ stream = self._outgoing_streams.get(message.id)
276
+ if stream is not None:
277
+ stream.destroy(message.error)
278
+
279
+ def _spawn(self, coro):
280
+ task = asyncio.create_task(coro)
281
+ self._tasks.add(task)
282
+ task.add_done_callback(self._tasks.discard)
283
+
284
+ async def _run_request(self, req):
285
+ try:
286
+ await _maybe_await(self._on_request(req))
287
+ except Exception as exc:
288
+ if not req._replied:
289
+ try:
290
+ await req.reject(exc)
291
+ except Exception as send_exc:
292
+ self._fail(send_exc)
293
+
294
+ async def _run_event(self, event):
295
+ try:
296
+ await _maybe_await(self._on_event(event))
297
+ except Exception as exc:
298
+ self._fail(exc)
299
+
300
+ def _fail(self, error):
301
+ if self._failed is not None:
302
+ return
303
+ self._failed = error
304
+ self._buffer.clear()
305
+ self._outbound.clear()
306
+ self._outbound_ready.set()
307
+ self._reject_all(error)
308
+ if self._on_error is not None:
309
+ result = self._on_error(error)
310
+ if inspect.isawaitable(result):
311
+ self._spawn(_maybe_await(result))
312
+
313
+ def _reject_all(self, error):
314
+ for future in self._pending.values():
315
+ if not future.done():
316
+ future.set_exception(error)
317
+ self._pending.clear()
318
+ for future in self._pending_response_streams.values():
319
+ if not future.done():
320
+ future.set_exception(error)
321
+ self._pending_response_streams.clear()
322
+ for stream in list(self._outgoing_streams.values()):
323
+ stream._abort(error)
324
+ self._outgoing_streams.clear()
325
+ for stream in list(self._incoming_streams.values()):
326
+ stream._abort(error)
327
+ self._incoming_streams.clear()
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: bare-rpc
3
+ Version: 0.0.1
4
+ Summary: Pure-Python port of the bare-rpc message and frame wire codec
5
+ Author: Holepunch
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: compact-encoding>=0.0.1
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8; extra == 'dev'
13
+ Requires-Dist: ruff>=0.6; extra == 'dev'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # bare-rpc-python
17
+
18
+ Pure-Python port of the [bare-rpc](https://github.com/holepunchto/bare-rpc) message/frame wire codec and async RPC runtime, wire-compatible with the JavaScript reference. Built on [compact-encoding-python](https://github.com/holepunchto/compact-encoding-python).
19
+
20
+ Typically you don't call this directly - [hrpc-python](https://github.com/holepunchto/hrpc-python) generates a typed client/server on top of it. Use it directly when you want the raw transport.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pip install git+https://github.com/holepunchto/bare-rpc-python
26
+ ```
27
+
28
+ ## Wire codec
29
+
30
+ Encode and decode frames without the runtime:
31
+
32
+ ```python
33
+ import bare_rpc as rpc
34
+
35
+ frame = rpc.encode_request(1, 42, data=b"hi") # -> bytes
36
+ msg = rpc.decode_frame(frame) # -> RequestMessage(id=1, command=42, ...)
37
+ ```
38
+
39
+ Encoders: `encode_request`, `encode_response`, `encode_error_response`, `encode_event`, `encode_stream`. `decode_frame` returns a `RequestMessage`, `ResponseMessage`, or `StreamMessage`. `Type` and `StreamFlag` are the wire enums.
40
+
41
+ ## RPC runtime
42
+
43
+ `RPC` is transport-agnostic: give it a `send` callback for outgoing frames and feed it inbound bytes with `receive`. Wire those to an asyncio stream, a websocket, or an in-memory pipe.
44
+
45
+ ```python
46
+ import bare_rpc as rpc
47
+
48
+
49
+ async def on_request(req):
50
+ await req.reply(b"pong")
51
+
52
+
53
+ server = rpc.RPC(send=my_send, on_request=on_request)
54
+ client = rpc.RPC(send=my_other_send)
55
+
56
+ await server.receive(incoming_bytes) # feed inbound frames in
57
+
58
+ result = await client.request(command=5, data=b"ping") # -> b"pong"
59
+ await client.event(command=3, data=b"note") # fire-and-forget, no response
60
+ ```
61
+
62
+ Constructor: `RPC(send, *, on_request=None, on_event=None, on_error=None, max_frame_size=...)`. `on_request` receives an `IncomingRequest` (`.command`, `.data`, `await .reply(data)`, `await .reject(error)`); `on_event` receives an `IncomingEvent`. `close()` rejects all in-flight requests.
63
+
64
+ ## Streams and backpressure
65
+
66
+ All three streaming shapes are implemented, with cork/uncork backpressure. An `OutgoingStream` has `await write(data)`, `await end()`, and `await destroy(error=None)`; an `IncomingStream` is async-iterable.
67
+
68
+ Response stream (server streams back, client reads):
69
+
70
+ ```python
71
+ async def on_request(req):
72
+ out = await req.create_response_stream()
73
+ await out.write(b"chunk-1")
74
+ await out.write(b"chunk-2")
75
+ await out.end()
76
+
77
+
78
+ incoming = await client.request_with_response_stream(command=5, data=b"go")
79
+ async for chunk in incoming:
80
+ ...
81
+ ```
82
+
83
+ Request stream (client streams up, server reads, then replies):
84
+
85
+ ```python
86
+ async def on_request(req):
87
+ async for chunk in req.request_stream:
88
+ ...
89
+ await req.reply(b"done")
90
+
91
+
92
+ out, reply = await client.stream_request(command=6)
93
+ await out.write(b"chunk-1")
94
+ await out.end()
95
+ result = await reply # -> b"done"
96
+ ```
97
+
98
+ Duplex (both directions):
99
+
100
+ ```python
101
+ out, incoming = await client.create_bidirectional_stream(command=7)
102
+ await out.write(b"ping")
103
+ await out.end()
104
+ async for chunk in incoming:
105
+ ...
106
+ ```
107
+
108
+ ## Errors
109
+
110
+ A rejected request raises `RPCRemoteError` (`.message`, `.code`, `.errno`) on the caller. Pass one to `await req.reject(...)` to carry a specific code across the wire; any other exception is rejected with its string message.
111
+
112
+ ## License
113
+
114
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ bare_rpc/__init__.py,sha256=wY7mZtG1G5TLN2XXOKLHlZ9HYR-1vthpEbohhTySryU,920
2
+ bare_rpc/constants.py,sha256=Q9GZNQ24EZ9-VmXkpkwwJT_Y3TK41KIiIpNDg9JL10E,252
3
+ bare_rpc/incoming.py,sha256=A4uF8y-0Zfeq6-Hf_FJod2Y1oQCs95gh3ZM1310JhXk,1419
4
+ bare_rpc/incoming_stream.py,sha256=SNVmJTJmuuowiPT_yrEo62CCY78yqrFf6VqsF-8DXbw,2819
5
+ bare_rpc/messages.py,sha256=14Ygoe8N9yZ_Xz6gsJSQ1gCHZbjTQqMfZLFDolg8IJU,6160
6
+ bare_rpc/outgoing_stream.py,sha256=27bkJawIxx0mMnVf3fygS_Y0g9XKZX-AONsV2C3RQMc,2328
7
+ bare_rpc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ bare_rpc/rpc.py,sha256=1ocUCY4XwJsrFAh7JLWuevbtfa42a7M8u0hIUZ4iXys,12059
9
+ bare_rpc-0.0.1.dist-info/METADATA,sha256=gckpnDK2DXoP-ZBodbW8GGo8Qjt6PXCyXUWuphL9ERI,3691
10
+ bare_rpc-0.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
11
+ bare_rpc-0.0.1.dist-info/licenses/LICENSE,sha256=R6LPz3pytRiGjm1UcrDBpNo9Lde4z9-HnfLdr4CJUQo,11284
12
+ bare_rpc-0.0.1.dist-info/licenses/NOTICE,sha256=hdAkJJsXX3Bg31bhcXn-xt_HHvZOAp-Yb3rwwHPxWzU,554
13
+ bare_rpc-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (an "as is" basis
145
+ without warranties of any kind, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright [yyyy] [name of copyright owner]
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ Copyright 2026 Holepunch Inc
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.