moat-lib-stream 0.3.3__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/PKG-INFO +2 -2
  2. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/debian/changelog +24 -0
  3. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/pyproject.toml +2 -2
  4. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/__init__.py +6 -0
  5. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/_cbor.py +2 -2
  6. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/_console.py +5 -8
  7. moat_lib_stream-0.3.5/src/moat/lib/stream/_layers.py +144 -0
  8. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/anyio.py +22 -14
  9. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/base.py +173 -6
  10. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/cbor.py +2 -2
  11. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/log.py +3 -3
  12. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/reliable.py +34 -21
  13. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/serial.py +9 -50
  14. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/tcp.py +1 -1
  15. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/terminal.py +2 -2
  16. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/unix.py +1 -1
  17. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat/lib/stream/ws.py +68 -46
  18. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat_lib_stream.egg-info/PKG-INFO +2 -2
  19. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat_lib_stream.egg-info/SOURCES.txt +1 -0
  20. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat_lib_stream.egg-info/requires.txt +1 -1
  21. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/LICENSE.txt +0 -0
  22. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/README.md +0 -0
  23. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/debian/.gitignore +0 -0
  24. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/debian/control +0 -0
  25. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/debian/rules +0 -0
  26. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/setup.cfg +0 -0
  27. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat_lib_stream.egg-info/dependency_links.txt +0 -0
  28. {moat_lib_stream-0.3.3 → moat_lib_stream-0.3.5}/src/moat_lib_stream.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: moat-lib-stream
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Stream infrastructure for MoaT applications
5
5
  Maintainer-email: Matthias Urlichs <matthias@urlichs.de>
6
6
  Project-URL: homepage, https://m-o-a-t.org
@@ -19,7 +19,7 @@ Requires-Dist: moat-lib-micro~=0.3.0
19
19
  Requires-Dist: moat-lib-rpc~=0.7.0
20
20
  Requires-Dist: moat-lib-codec~=0.4.14
21
21
  Requires-Dist: moat-lib-repl~=0.1.4
22
- Requires-Dist: moat-util~=0.63.0
22
+ Requires-Dist: moat-util~=0.64.0
23
23
  Dynamic: license-file
24
24
 
25
25
  # Stream Infrastructure
@@ -1,3 +1,27 @@
1
+ moat-lib-stream (0.3.5-1) unstable; urgency=medium
2
+
3
+ * New release for 26.4.26
4
+
5
+ -- Matthias Urlichs <matthias@urlichs.de> Sat, 03 Oct 2026 12:54:00 +0200
6
+
7
+ moat-lib-stream (0.3.4-3) unstable; urgency=medium
8
+
9
+ * New release for 26.4.8
10
+
11
+ -- Matthias Urlichs <matthias@urlichs.de> Thu, 01 Oct 2026 11:15:56 +0200
12
+
13
+ moat-lib-stream (0.3.4-1) unstable; urgency=medium
14
+
15
+ * New release for 26.2.13
16
+
17
+ -- Matthias Urlichs <matthias@urlichs.de> Wed, 23 Sep 2026 15:11:55 +0200
18
+
19
+ moat-lib-stream (0.3.3-2) unstable; urgency=medium
20
+
21
+ * New release for 26.2.9
22
+
23
+ -- Matthias Urlichs <matthias@urlichs.de> Sat, 11 Jul 2026 07:53:26 +0200
24
+
1
25
  moat-lib-stream (0.3.3-1) unstable; urgency=medium
2
26
 
3
27
  * New release for 26.2.8
@@ -16,7 +16,7 @@ dependencies = [
16
16
  "moat-lib-rpc ~= 0.7.0",
17
17
  "moat-lib-codec ~= 0.4.14",
18
18
  "moat-lib-repl ~= 0.1.4",
19
- "moat-util ~= 0.63.0",
19
+ "moat-util ~= 0.64.0",
20
20
  ]
21
21
  keywords = ["MoaT"]
22
22
  requires-python = ">=3.8"
@@ -24,7 +24,7 @@ name = "moat-lib-stream"
24
24
  maintainers = [{email = "matthias@urlichs.de",name = "Matthias Urlichs"}]
25
25
  description='Stream infrastructure for MoaT applications'
26
26
  readme = "README.md"
27
- version = "0.3.3"
27
+ version = "0.3.5"
28
28
 
29
29
  [project.urls]
30
30
  homepage = "https://m-o-a-t.org"
@@ -4,6 +4,9 @@ Stream infrastructure for handling data streams in a structured manner.
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ # Import _layers to register layer factories with build_stack.
8
+ from . import _layers # noqa: F401
9
+
7
10
  # Import base classes directly (not lazy)
8
11
  from .base import Base as Base
9
12
  from .base import BaseBlk as BaseBlk
@@ -14,6 +17,7 @@ from .base import StackedBlk as StackedBlk
14
17
  from .base import StackedBuf as StackedBuf
15
18
  from .base import StackedConn as StackedConn
16
19
  from .base import StackedMsg as StackedMsg
20
+ from .base import build_stack as build_stack
17
21
 
18
22
  from typing import TYPE_CHECKING as _TC
19
23
 
@@ -100,6 +104,8 @@ __all__ = [
100
104
  "StackedBuf",
101
105
  "StackedConn",
102
106
  "StackedMsg",
107
+ # Stack builder
108
+ "build_stack",
103
109
  ] + list(_imports.keys())
104
110
 
105
111
 
@@ -44,7 +44,7 @@ class _CBORMsgBuf(StackedMsg):
44
44
  codec: Codec
45
45
  liner: Liner | None = None
46
46
 
47
- def __init__(self, stream: BaseBuf, cfg: dict):
47
+ def __init__(self, stream: BaseBuf, cfg: dict) -> None:
48
48
  StackedMsg.__init__(self, stream, cfg)
49
49
  self.w_lock = Lock()
50
50
 
@@ -57,7 +57,7 @@ class _CBORMsgBuf(StackedMsg):
57
57
  if cons:
58
58
  _CReader.__init__(cast(_CReader, self), cons)
59
59
 
60
- async def setup(self):
60
+ async def setup(self) -> None:
61
61
  await super().setup()
62
62
  if self.cons is False:
63
63
  from moat.util.liner import Liner # noqa:PLC0415
@@ -4,6 +4,8 @@ Console data handling for stream layers.
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ import sys
8
+
7
9
  from moat.lib.micro import Event
8
10
 
9
11
  from typing import TYPE_CHECKING
@@ -17,14 +19,9 @@ class _CReader:
17
19
  A mix-in that processes incoming console data.
18
20
  """
19
21
 
20
- def __init__(self, cons: bool | int):
22
+ def __init__(self, cons: bool | int) -> None:
21
23
  if cons is True:
22
- try:
23
- __import__("machine")
24
- except ImportError:
25
- cons = 32768
26
- else:
27
- cons = 240
24
+ cons = 240 if sys.implementation.name == "micropython" else 32768
28
25
  self.cevt = Event()
29
26
  self.cpos = 0
30
27
  self.cbuf = bytearray(cons)
@@ -47,7 +44,7 @@ class _CReader:
47
44
  self.cpos = 0
48
45
  return n
49
46
 
50
- def cput(self, b: int):
47
+ def cput(self, b: int) -> None:
51
48
  """store a byte in the console buffer"""
52
49
  if self.cpos == len(self.cbuf):
53
50
  if len(self.cbuf) > 100:
@@ -0,0 +1,144 @@
1
+ """Layer factory functions for :py:func:`~moat.lib.stream.build_stack`.
2
+
3
+ Each factory has the signature ``(stream, cfg[, **kw]) -> stream`` and
4
+ wraps *stream* with one layer of the stack. The factories are registered
5
+ in :py:mod:`moat.lib.stream` at import time so that ``build_stack`` can
6
+ resolve them by name.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from moat.lib.stream.base import _register_layer
12
+
13
+ from typing import TYPE_CHECKING # isort:skip
14
+
15
+ if TYPE_CHECKING:
16
+ from moat.util import attrdict
17
+ from moat.lib.stream import BaseBuf, BaseMsg
18
+
19
+
20
+ def cbor_buf(stream: BaseBuf, cfg: attrdict, *, frame=None, cons: bool = False) -> BaseMsg: # noqa: ARG001
21
+ """Self-delimiting CBOR codec layer.
22
+
23
+ Wraps a byte stream with :class:`~moat.lib.stream.CBORMsgBuf`,
24
+ which assumes the transport is reliable but does not preserve
25
+ message boundaries.
26
+
27
+ Args:
28
+ stream: The bottom-layer byte stream.
29
+ cfg: Full config dict (used for codec selection).
30
+ frame: Prefix byte for messages (``msg_prefix``). Should be
31
+ an integer or ``None``; a dict is ignored (use
32
+ :func:`cbor_blk` for framed mode).
33
+ cons: Console multiplexing flag.
34
+ """
35
+ from moat.lib.stream import CBORMsgBuf # noqa: PLC0415
36
+
37
+ if isinstance(frame, dict):
38
+ frame = None
39
+ return CBORMsgBuf(stream, dict(msg_prefix=frame, console=cons))
40
+
41
+
42
+ def cbor_blk(stream, cfg: attrdict, **kw) -> BaseMsg: # noqa: ARG001
43
+ """Block-CBOR codec layer.
44
+
45
+ Wraps a **block** stream (one carrying message boundaries via
46
+ ``snd``/``rcv``, e.g. a websocket) with
47
+ :class:`~moat.lib.stream.CBORMsgBlk`.
48
+
49
+ This layer takes blocks and turns them into messages; it does not frame.
50
+ To feed it a raw byte stream, add the framing layer
51
+ (:func:`serial_frame`) first, or use :func:`cbor_buf` for the
52
+ self-delimiting path. Keyword arguments are accepted and ignored for
53
+ backwards compatibility with older callers.
54
+
55
+ Args:
56
+ stream: A block-oriented stream (``snd``/``rcv``).
57
+ cfg: Full config dict (used for codec selection).
58
+ """
59
+ from moat.lib.stream import CBORMsgBlk # noqa: PLC0415
60
+
61
+ return CBORMsgBlk(stream, cfg)
62
+
63
+
64
+ def serial_frame(
65
+ stream,
66
+ cfg: attrdict, # noqa: ARG001
67
+ *,
68
+ frame: dict | None = None,
69
+ cons: bool | int = False,
70
+ ):
71
+ """HDLC-like framing layer (bytes \u2192 blocks).
72
+
73
+ Wraps a **byte** stream (``rd``/``wr``) with
74
+ :class:`~moat.lib.stream.SerialPackerBlkBuf`, producing a block stream
75
+ suitable as input to :func:`cbor_blk`.
76
+
77
+ Args:
78
+ stream: A byte-oriented stream (``rd``/``wr``).
79
+ frame: SerialPacker configuration dict.
80
+ cons: Console multiplexing flag.
81
+ """
82
+ from moat.lib.stream.serial import SerialPackerBlkBuf # noqa: PLC0415
83
+
84
+ if frame is None:
85
+ frame = {}
86
+ return SerialPackerBlkBuf(stream, frame=frame, console=cons)
87
+
88
+
89
+ def reliable(stream, cfg: attrdict) -> BaseMsg:
90
+ """Reliability / retransmission layer.
91
+
92
+ Wraps a message stream with :class:`~moat.lib.stream.ReliableMsg`.
93
+
94
+ Args:
95
+ stream: The message stream to protect.
96
+ cfg: Configuration for the ReliableMsg layer (window, timeout, …).
97
+ """
98
+ from moat.lib.stream import ReliableMsg # noqa: PLC0415
99
+
100
+ return ReliableMsg(stream, cfg)
101
+
102
+
103
+ def log_msg(stream, cfg: attrdict) -> BaseMsg:
104
+ """Message-level logging layer.
105
+
106
+ Wraps a stream with :class:`~moat.lib.stream.LogMsg`.
107
+
108
+ Args:
109
+ stream: The stream to log.
110
+ cfg: Logging configuration (``txt``, ``decode``, …).
111
+ """
112
+ from moat.lib.stream import LogMsg # noqa: PLC0415
113
+
114
+ return LogMsg(stream, cfg)
115
+
116
+
117
+ def log_raw(stream, cfg: attrdict):
118
+ """Raw byte-level logging layer.
119
+
120
+ Same as :func:`log_msg` but conceptually placed at the bottom of the
121
+ stack to log raw bytes. Uses :class:`~moat.lib.stream.LogMsg` /
122
+ :class:`~moat.lib.stream.LogBlk` depending on the stream type.
123
+
124
+ Args:
125
+ stream: The byte/block stream to log.
126
+ cfg: Logging configuration.
127
+ """
128
+ from moat.lib.stream import LogMsg # noqa: PLC0415
129
+
130
+ return LogMsg(stream, cfg)
131
+
132
+
133
+ # Alias: "log" is the common shorthand for the message-level log layer.
134
+ log = log_msg
135
+
136
+
137
+ # Register all factories with the build_stack resolver.
138
+ _register_layer("cbor_buf", "moat.lib.stream._layers")
139
+ _register_layer("cbor_blk", "moat.lib.stream._layers")
140
+ _register_layer("serial_frame", "moat.lib.stream._layers")
141
+ _register_layer("reliable", "moat.lib.stream._layers")
142
+ _register_layer("log_msg", "moat.lib.stream._layers")
143
+ _register_layer("log_raw", "moat.lib.stream._layers")
144
+ _register_layer("log", "moat.lib.stream._layers")
@@ -17,12 +17,15 @@ from moat.util import CtxObj
17
17
  from moat.lib.micro import AC_use
18
18
  from moat.lib.stream import BaseBuf
19
19
 
20
- from typing import TYPE_CHECKING, Any, cast # isort:skip
20
+ from typing import TYPE_CHECKING, cast
21
21
 
22
22
  if TYPE_CHECKING:
23
+ from types import TracebackType
24
+
23
25
  from moat.lib.rpc import SubMsgSender
24
26
  from moat.lib.stream.base import Buffer, MutBuffer
25
- from types import TracebackType
27
+
28
+ from typing import Any, Never
26
29
 
27
30
 
28
31
  class ProcessDeadError(RuntimeError):
@@ -75,7 +78,7 @@ class FilenoBuf(BaseBuf):
75
78
  wfl: int
76
79
  term: list[Any] | None
77
80
 
78
- def __init__(self, cfg, fd: int, wfd: int | None = None):
81
+ def __init__(self, cfg, fd: int, wfd: int | None = None) -> None:
79
82
  super().__init__(cfg)
80
83
  self.rfd = fd
81
84
  self.wfd = fd if wfd is None else wfd
@@ -85,7 +88,7 @@ class FilenoBuf(BaseBuf):
85
88
  "Dummy here"
86
89
  raise NotImplementedError("Dummy")
87
90
 
88
- async def setup(self):
91
+ async def setup(self) -> None:
89
92
  "Change to nonblocking and raw"
90
93
  self.rfl = fcntl.fcntl(self.rfd, fcntl.F_SETFL, 0)
91
94
  if self.rfd != self.wfd:
@@ -107,7 +110,7 @@ class FilenoBuf(BaseBuf):
107
110
  cc[termios.VTIME] = 0
108
111
  termios.tcsetattr(self.rfd, termios.TCSANOW, new)
109
112
 
110
- async def teardown(self):
113
+ async def teardown(self) -> None:
111
114
  "Return to blocking and cooked"
112
115
  fcntl.fcntl(self.rfd, fcntl.F_SETFL, self.rfl)
113
116
  if self.rfd != self.wfd:
@@ -143,7 +146,7 @@ class RemoteBufAnyio(ByteStream):
143
146
  TODO: use remote iteration for receiving
144
147
  """
145
148
 
146
- def __init__(self, disp: SubMsgSender):
149
+ def __init__(self, disp: SubMsgSender) -> None:
147
150
  self.disp = disp
148
151
 
149
152
  async def receive(self, max_bytes=256):
@@ -154,7 +157,7 @@ class RemoteBufAnyio(ByteStream):
154
157
  "forward to ``.wr``"
155
158
  await self.disp.wr(b=item)
156
159
 
157
- async def aclose(self):
160
+ async def aclose(self) -> None:
158
161
  "no-op"
159
162
 
160
163
  async def send_eof(self):
@@ -169,14 +172,19 @@ class BufAnyio(ByteStream):
169
172
 
170
173
  par = None
171
174
 
172
- def __init__(self, stream: BaseBuf):
175
+ def __init__(self, stream: BaseBuf) -> None:
173
176
  self.stream = stream
174
177
 
175
178
  async def __aenter__(self):
176
179
  self.s = await self.stream.__aenter__()
177
180
 
178
- async def __aexit__(self, exc_type: type[BaseException] | None,exc_val: BaseException | None,exc_tb: TracebackType | None) -> None:
179
- await self.stream.__aexit__(exc_type,exc_val,exc_tb)
181
+ async def __aexit__(
182
+ self,
183
+ exc_type: type[BaseException] | None,
184
+ exc_val: BaseException | None,
185
+ exc_tb: TracebackType | None,
186
+ ) -> None:
187
+ await self.stream.__aexit__(exc_type, exc_val, exc_tb)
180
188
 
181
189
  async def receive(self, max_bytes=256):
182
190
  "forward to ``.rd``"
@@ -203,7 +211,7 @@ class SingleAnyioBuf(AnyioBuf):
203
211
  once.
204
212
  """
205
213
 
206
- def __init__(self, stream):
214
+ def __init__(self, stream) -> None:
207
215
  self._s = stream
208
216
 
209
217
  async def stream(self): # noqa:D102
@@ -229,7 +237,7 @@ class ProcessBuf(CtxObj, AnyioBuf):
229
237
  argv: list[str] | None = None
230
238
  env: dict[str, str] | None = None
231
239
 
232
- def __init__(self, cfg, executable: str | None = None, **kw):
240
+ def __init__(self, cfg, executable: str | None = None, **kw) -> None:
233
241
  super().__init__(cfg)
234
242
  kw.setdefault("stderr", sys.stderr)
235
243
  self.kw: dict[str, Any] = dict(kw)
@@ -293,8 +301,8 @@ class ProcessBuf(CtxObj, AnyioBuf):
293
301
  if proc is not None and proc.returncode != 0 and proc.returncode != -9:
294
302
  raise ProcessDeadError(f"{self} died with {proc.returncode}")
295
303
 
296
- async def setup(self): # noqa:D102
304
+ async def setup(self) -> None: # noqa:D102
297
305
  pass
298
306
 
299
- async def stream(self): # noqa:D102
307
+ async def stream(self) -> Never: # noqa:D102
300
308
  raise RuntimeError("should not be called")
@@ -25,6 +25,11 @@ read or receive new messages.
25
25
 
26
26
  A `wrap` method provides a secondary context that can be used for
27
27
  a persistent outer context, e.g. to keep a listening socket open.
28
+
29
+ Use :py:func:`build_stack` to assemble a stack from a configuration
30
+ dictionary. The function is flexible: it can auto-detect the required
31
+ layers from the standard ``link`` / ``log`` / ``log_raw`` / ``log_rel``
32
+ keys, or you can pass an explicit ``layers`` list for full control.
28
33
  """
29
34
 
30
35
  from __future__ import annotations
@@ -32,6 +37,8 @@ from __future__ import annotations
32
37
  from moat.util import attrdict
33
38
  from moat.lib.micro import ACM, AC_exit, AC_use
34
39
 
40
+ from collections.abc import Mapping
41
+
35
42
  # Typing
36
43
 
37
44
  from typing import TYPE_CHECKING # isort:skip
@@ -83,7 +90,7 @@ class Base(_AACMBase):
83
90
  s = None
84
91
  cfg: attrdict
85
92
 
86
- def __init__(self, cfg: attrdict | None = None):
93
+ def __init__(self, cfg: attrdict | None = None) -> None:
87
94
  if cfg is None:
88
95
  cfg = attrdict()
89
96
  self.cfg = cfg
@@ -125,14 +132,14 @@ class Base(_AACMBase):
125
132
  ) -> bool | None:
126
133
  return await AC_exit(self, exc_type, exc, tb)
127
134
 
128
- async def setup(self):
135
+ async def setup(self) -> None:
129
136
  """
130
137
  Basic async setup method. You may use AC_exit.
131
138
 
132
139
  Call the superclass first, when overriding.
133
140
  """
134
141
 
135
- async def teardown(self):
142
+ async def teardown(self) -> None:
136
143
  """
137
144
  Object destructor.
138
145
 
@@ -157,7 +164,7 @@ class BaseConn(Base):
157
164
 
158
165
  s: Any = None
159
166
 
160
- async def setup(self):
167
+ async def setup(self) -> None:
161
168
  """
162
169
  Object construction.
163
170
 
@@ -169,7 +176,7 @@ class BaseConn(Base):
169
176
 
170
177
  self.s = await self.stream()
171
178
 
172
- async def teardown(self):
179
+ async def teardown(self) -> None:
173
180
  """
174
181
  Object destructor.
175
182
 
@@ -266,7 +273,7 @@ class StackedConn(BaseConn):
266
273
 
267
274
  link: BaseConn | None = None
268
275
 
269
- def __init__(self, link: BaseConn, cfg):
276
+ def __init__(self, link: BaseConn, cfg) -> None:
270
277
  super().__init__(cfg=cfg)
271
278
  self.link = link
272
279
 
@@ -355,3 +362,163 @@ class StackedBlk(StackedConn, BaseBlk):
355
362
  async def rcv(self) -> Buffer | bytes:
356
363
  "Receive. Returns a message."
357
364
  return await self.s.rcv()
365
+
366
+
367
+ # ---------------------------------------------------------------------------
368
+ # Stack builder
369
+ # ---------------------------------------------------------------------------
370
+
371
+ # Registry of known layer factories. Each entry maps a name to a callable
372
+ # ``(stream, cfg) -> stream``. The callable receives the current bottom
373
+ # stream and the *full* config dict; it returns the new (wrapped) stream.
374
+ #
375
+ # Factories are registered lazily to avoid importing heavy modules (CBOR,
376
+ # Reliable, SerialPacker, …) at module load time. Use :func:`_layer` to
377
+ # look up a factory by name.
378
+ _LAYER_FACTORIES: dict[str, str] = {
379
+ # name -> dotted module path containing the factory function
380
+ # The factory function itself must have the same name as the layer.
381
+ }
382
+
383
+
384
+ def _register_layer(name: str, module: str) -> None:
385
+ """Register a layer factory.
386
+
387
+ Args:
388
+ name: Layer name used in config ``layers`` lists.
389
+ module: Dotted module path that contains a same-named factory
390
+ callable ``(stream, cfg) -> stream``.
391
+ """
392
+ _LAYER_FACTORIES[name] = module
393
+
394
+
395
+ def _layer_factory(name: str):
396
+ """Resolve a layer factory by name, importing its module on demand."""
397
+ try:
398
+ module = _LAYER_FACTORIES[name]
399
+ except KeyError:
400
+ raise ValueError(f"Unknown stream layer: {name!r}") from None
401
+ mod = __import__(module, globals(), None, (name,))
402
+ return getattr(mod, name)
403
+
404
+
405
+ def build_stack(stream, cfg: attrdict, *, framed: bool | None = None, cons: bool = False):
406
+ """Build a message stack on top of a MoaT bytestream.
407
+
408
+ This is the central, flexible stack assembler. It replaces the
409
+ older per-transport ``serial_stack`` / ``ws_stack`` helpers (which
410
+ now delegate here).
411
+
412
+ Two modes of operation:
413
+
414
+ Explicit layers
415
+ If ``cfg["layers"]`` is a list, each element describes one layer
416
+ to add. Elements may be:
417
+
418
+ * a string — name of a registered layer factory
419
+ (e.g. ``"cbor_blk"``, ``"reliable"``, ``"log"``);
420
+ * a dict with keys ``name`` (required) and ``cfg`` (optional,
421
+ defaults to an empty dict) — the sub-dict is passed to the
422
+ layer factory instead of the global config.
423
+
424
+ Layers are applied bottom-up: the first element wraps *stream*
425
+ directly, the second wraps the result, and so on.
426
+
427
+ Implicit (auto-detect)
428
+ When ``cfg["layers"]`` is absent, the layers are inferred from
429
+ the standard config keys:
430
+
431
+ ``log_raw``
432
+ If present, a raw-byte logging layer is added at the very
433
+ bottom.
434
+ ``link.frame`` / ``framed``
435
+ Select the codec layer. Three cases:
436
+
437
+ * ``framed=True`` — the bottom stream already carries message
438
+ boundaries (a block stream, e.g. a websocket); it is wrapped
439
+ with ``cbor_blk`` directly, no framing.
440
+ * ``framed=False`` — force the self-delimiting codec
441
+ (``cbor_buf``).
442
+ * ``framed=None`` (default) — auto-detect from ``link.frame``:
443
+ a mapping selects HDLC framing (``serial_frame``) followed by
444
+ ``cbor_blk`` (the bottom is a byte stream needing framing);
445
+ an int or absence selects the self-delimiting codec
446
+ (``cbor_buf``, with the int as the message prefix byte).
447
+ ``link.lossy``
448
+ If truthy, a :class:`~moat.lib.stream.reliable.ReliableMsg`
449
+ layer is inserted. An optional ``log_rel`` log layer is
450
+ added just below it.
451
+ ``log``
452
+ If present, a high-level message logging layer is added on
453
+ top.
454
+
455
+ Args:
456
+ stream: The bottom-layer stream (``BaseBuf`` or ``BaseBlk``).
457
+ cfg: Configuration dictionary. See above.
458
+ framed: Select the codec in implicit mode — ``True`` for a
459
+ block-delimited bottom (block codec, no framing), ``False``
460
+ to force the self-delimiting codec, ``None`` to auto-detect
461
+ from ``link.frame``.
462
+ cons: Console flag forwarded to the framing/codec layers in
463
+ implicit mode.
464
+
465
+ Returns:
466
+ The top of the assembled stack (a :class:`BaseMsg`).
467
+ """
468
+ layers = cfg.get("layers", None)
469
+
470
+ if layers is not None:
471
+ # Explicit mode: process the user-supplied layer list.
472
+ for layer in layers:
473
+ if isinstance(layer, str):
474
+ name = layer
475
+ lcfg = cfg
476
+ else:
477
+ name = layer["name"]
478
+ lcfg = layer.get("cfg", cfg)
479
+ factory = _layer_factory(name)
480
+ stream = factory(stream, lcfg)
481
+ return stream
482
+
483
+ # Implicit mode: auto-detect layers from standard config keys.
484
+ link = cfg.get("link", {})
485
+ if cons is False:
486
+ cons = link.get("console", False)
487
+ frame = link.get("frame", None)
488
+ lossy = link.get("lossy", None)
489
+ log = cfg.get("log", None)
490
+ log_raw = cfg.get("log_raw", None)
491
+ log_rel = cfg.get("log_rel", None)
492
+
493
+ # Raw byte logging at the very bottom.
494
+ if log_raw is not None:
495
+ stream = _layer_factory("log_raw")(stream, log_raw)
496
+
497
+ # Codec layer: convert bytes ↔ messages.
498
+ if framed is False:
499
+ stream = _layer_factory("cbor_buf")(stream, cfg, frame=frame, cons=cons)
500
+ elif framed is True:
501
+ # Bottom already carries message boundaries (e.g. a websocket);
502
+ # use the block codec directly, no framing.
503
+ stream = _layer_factory("cbor_blk")(stream, cfg)
504
+ elif isinstance(frame, Mapping):
505
+ # Bottom is a byte stream needing HDLC framing: frame first
506
+ # (bytes → blocks), then encode blocks as messages.
507
+ stream = _layer_factory("serial_frame")(stream, cfg, frame=frame, cons=cons)
508
+ stream = _layer_factory("cbor_blk")(stream, cfg)
509
+ else:
510
+ stream = _layer_factory("cbor_buf")(stream, cfg, frame=frame, cons=cons)
511
+
512
+ # Reliability layer (optional).
513
+ if lossy:
514
+ if lossy is True:
515
+ lossy = {}
516
+ if log_rel is not None:
517
+ stream = _layer_factory("log_msg")(stream, log_rel)
518
+ stream = _layer_factory("reliable")(stream, lossy)
519
+
520
+ # High-level message logging on top.
521
+ if log is not None:
522
+ stream = _layer_factory("log_msg")(stream, log)
523
+
524
+ return stream
@@ -17,7 +17,7 @@ class CBORMsgBuf(_CBORMsgBuf):
17
17
  message boundaries.
18
18
  """
19
19
 
20
- async def setup(self): # noqa:D102
20
+ async def setup(self) -> None: # noqa:D102
21
21
  await super().setup()
22
22
  self.codec = get_codec(self.cfg.get("codec", "std-cbor"))
23
23
 
@@ -30,6 +30,6 @@ class CBORMsgBlk(_CBORMsgBlk):
30
30
  (one bytestring-ized message per call).
31
31
  """
32
32
 
33
- async def setup(self): # noqa:D102
33
+ async def setup(self) -> None: # noqa:D102
34
34
  await super().setup()
35
35
  self.codec = get_codec(self.cfg.get("codec", "std-cbor"))
@@ -25,18 +25,18 @@ class LogMsg(StackedMsg, StackedBuf, StackedBlk):
25
25
  # StackedMsg is first because MicroPython uses only the first class and
26
26
  # we get `cwr` and `crd` that way.
27
27
 
28
- def __init__(self, link, cfg):
28
+ def __init__(self, link, cfg) -> None:
29
29
  super().__init__(link, cfg)
30
30
  self.txt = cfg.get("txt", "S")
31
31
  self.decode = self.txt[0] == "!"
32
32
  if self.decode:
33
33
  self.txt = self.txt[1:]
34
34
 
35
- async def setup(self): # noqa:D102
35
+ async def setup(self) -> None: # noqa:D102
36
36
  log("X:%s start", self.txt)
37
37
  await super().setup()
38
38
 
39
- async def teardown(self): # noqa:D102
39
+ async def teardown(self) -> None: # noqa:D102
40
40
  log("X:%s stop", self.txt)
41
41
  await super().teardown()
42
42
 
@@ -39,7 +39,7 @@ class EphemeralMsg:
39
39
  updated.
40
40
  """
41
41
 
42
- def __init__(self, chan: int, data: Any):
42
+ def __init__(self, chan: int, data: Any) -> None:
43
43
  self.chan = chan
44
44
  self.data = data
45
45
 
@@ -108,12 +108,13 @@ class ReliableMsg(StackedMsg):
108
108
  _tg = None
109
109
  __tg = None
110
110
 
111
- def __init__(self, link, cfg):
111
+ def __init__(self, link, cfg) -> None:
112
112
  super().__init__(link, cfg)
113
113
 
114
114
  window = cfg.get("window", 8)
115
115
  timeout = cfg.get("timeout", 1000)
116
116
  retries = cfg.get("retries", 5)
117
+ self.persist = cfg.get("persist", False)
117
118
 
118
119
  if window < 4:
119
120
  raise RuntimeError(f"window must be >=4, not {window}")
@@ -127,7 +128,7 @@ class ReliableMsg(StackedMsg):
127
128
  self.retries = retries
128
129
  self._iters = {}
129
130
 
130
- def reset(self, level=1): # noqa:D102
131
+ def reset(self, level=1) -> None: # noqa:D102
131
132
  self.s_send_head = 0 # next to be transmitted
132
133
  self.s_send_tail = 0 # no open messages before this point
133
134
  self.s_recv_head = 0 # next expected message. Messages before this are out of sequence
@@ -144,7 +145,7 @@ class ReliableMsg(StackedMsg):
144
145
  if self.rq is None:
145
146
  self.rq = Queue(self.window)
146
147
 
147
- async def send_msg(self, k=None):
148
+ async def send_msg(self, k=None) -> None:
148
149
  """
149
150
  Send some message.
150
151
 
@@ -193,7 +194,7 @@ class ReliableMsg(StackedMsg):
193
194
  if k is not None and self.m_send.get(k, None) is mte:
194
195
  mte[1] = ticks_add(ticks_ms(), self.timeout)
195
196
 
196
- async def _run_bg(self):
197
+ async def _run_bg(self) -> None:
197
198
  while not self.closed:
198
199
  if self.in_reset:
199
200
  await self._trigger.wait()
@@ -269,7 +270,7 @@ class ReliableMsg(StackedMsg):
269
270
  if nk is None:
270
271
  self.t_recv = ticks_add(ticks_ms(), self.timeout)
271
272
 
272
- async def wait(self):
273
+ async def wait(self) -> None:
273
274
  """
274
275
  Wait until the lower side is (again) ready to be used.
275
276
 
@@ -295,20 +296,23 @@ class ReliableMsg(StackedMsg):
295
296
  await AC_exit(self, type(exc), exc, None)
296
297
  raise
297
298
 
298
- async def __aexit__(self, exc_type: type[BaseException] | None,
299
- exc: BaseException | None,
300
- tb: TracebackType | None) -> bool|None:
299
+ async def __aexit__(
300
+ self,
301
+ exc_type: type[BaseException] | None,
302
+ exc: BaseException | None,
303
+ tb: TracebackType | None,
304
+ ) -> bool | None:
301
305
  if self._tg is not None:
302
306
  self._tg.cancel()
303
307
  self._tg = None
304
- return await AC_exit(self, exc_type,exc,tb)
308
+ return await AC_exit(self, exc_type, exc, tb)
305
309
 
306
- async def _mon(self):
310
+ async def _mon(self) -> None:
307
311
  while True:
308
312
  await wait_for_ms(self.retries * self.timeout, self._is_up.wait)
309
313
  await self._is_down.wait()
310
314
 
311
- async def _run_(self):
315
+ async def _run_(self) -> None:
312
316
  if self._is_down.is_set():
313
317
  self._is_down = Event()
314
318
  self.reset_level = 1
@@ -337,12 +341,21 @@ class ReliableMsg(StackedMsg):
337
341
 
338
342
  await idle()
339
343
 
340
- except Exception: # noqa:TRY203
341
- # if not self.persist:
342
- raise
343
- # log("Reliable", err=exc)
344
+ except (EOFError, OSError) as exc:
345
+ # Connection dropped. If persist is set, log and return so
346
+ # _run()'s loop reconnects; otherwise re-raise.
347
+ if not self.persist:
348
+ raise
349
+ log("Reliable reconnect: %r", exc)
350
+ # Signal that the link is down while we reconnect.
351
+ self.__tg = None
352
+ self.s = None
353
+ self._is_down.set()
354
+ if self._is_up.is_set():
355
+ self._is_up = Event()
356
+ self._trigger.set()
344
357
 
345
- async def _run(self):
358
+ async def _run(self) -> None:
346
359
  self.reset()
347
360
  try:
348
361
  while True:
@@ -382,7 +395,7 @@ class ReliableMsg(StackedMsg):
382
395
  except EOFError:
383
396
  pass
384
397
 
385
- async def send_reset(self, level=None, err=None):
398
+ async def send_reset(self, level=None, err=None) -> None:
386
399
  "send a Reset message to the other side"
387
400
  if level is None:
388
401
  level = self.reset_level
@@ -437,13 +450,13 @@ class ReliableMsg(StackedMsg):
437
450
  def _get_config(self):
438
451
  return [self.window, self.timeout]
439
452
 
440
- def _update_config(self, c):
453
+ def _update_config(self, c) -> None:
441
454
  if len(c) > 0 and c[0] > 0:
442
455
  self.window = max(4, min(self.window, c[0]))
443
456
  if len(c) > 1 and c[1] > 0:
444
457
  self.timeout = max(10, self.timeout, c[1])
445
458
 
446
- def _reset_done(self):
459
+ def _reset_done(self) -> None:
447
460
  if self.in_reset:
448
461
  self.in_reset = False
449
462
  self._trigger.set()
@@ -472,7 +485,7 @@ class ReliableMsg(StackedMsg):
472
485
  "check if the link is down"
473
486
  return self._is_down.is_set()
474
487
 
475
- async def _dispatch(self, msg):
488
+ async def _dispatch(self, msg) -> None:
476
489
  if not isinstance(msg, (tuple, list)):
477
490
  raise TypeError(msg)
478
491
 
@@ -5,7 +5,8 @@ SerialPacker protocol support for stream layers.
5
5
  from __future__ import annotations
6
6
 
7
7
  from moat.lib.micro import Lock
8
- from moat.lib.stream import BaseBuf, BaseMsg, StackedBlk
8
+ from moat.lib.stream import BaseBuf, StackedBlk
9
+ from moat.lib.stream.base import build_stack
9
10
 
10
11
  from ._console import _CReader
11
12
 
@@ -26,10 +27,10 @@ class SerialPackerBlkBuf(StackedBlk):
26
27
 
27
28
  cons = False
28
29
 
29
- def __init__(self, stream: BaseBuf, frame: dict, console: bool | int = False):
30
+ def __init__(self, stream: BaseBuf, frame: dict, console: bool | int = False) -> None:
30
31
  StackedBlk.__init__(self, stream, None)
31
32
 
32
- SerialPacker = __import__("serialpacker", fromlist=("SerialPacker",)).SerialPacker
33
+ SerialPacker = __import__("serialpacker", globals(), None, ("SerialPacker",)).SerialPacker
33
34
 
34
35
  self.p = SerialPacker(**frame)
35
36
  self.buf = bytearray(16)
@@ -85,9 +86,10 @@ class SerialPackerBlkBuf(StackedBlk):
85
86
 
86
87
 
87
88
  def serial_stack(stream, cfg: attrdict, cons: bool = False):
88
- # lossy=False, log=False, use_console=False, msg_prefix=None
89
- """
90
- Build a message stack on top of a MoaT bytestream.
89
+ """Build a message stack on top of a MoaT bytestream.
90
+
91
+ This is a thin wrapper around :py:func:`moat.lib.stream.build_stack`
92
+ that preserves the original calling convention.
91
93
 
92
94
  Configuration:
93
95
  link(dict):
@@ -118,50 +120,7 @@ def serial_stack(stream, cfg: attrdict, cons: bool = False):
118
120
  There is no start-of-frame character escaping. Choose a value that cannot occur
119
121
  in an ASCII or possibly UTF-8 bytestream (≥ 0xF8).
120
122
  """
121
-
122
123
  if not hasattr(stream, "rd") or not hasattr(stream, "wr"):
123
124
  raise TypeError(f"need a BaseBuf not {stream}")
124
125
 
125
- link = cfg.get("link", {})
126
- cons = link.get("console", cons)
127
- frame = link.get("frame", None)
128
- lossy = link.get("lossy", None)
129
- log = cfg.get("log", None)
130
- log_raw = cfg.get("log_raw", None)
131
- log_rel = cfg.get("log_rel", None)
132
-
133
- if log_raw is not None:
134
- from moat.lib.stream import LogMsg # noqa: PLC0415
135
-
136
- stream = LogMsg(stream, log_raw)
137
-
138
- if isinstance(frame, dict):
139
- from moat.lib.stream import CBORMsgBlk # noqa: PLC0415
140
-
141
- stream = SerialPackerBlkBuf(stream, frame=frame, console=cons)
142
- stream = CBORMsgBlk(stream, cfg)
143
- else:
144
- from moat.lib.stream import CBORMsgBuf # noqa: PLC0415
145
-
146
- stream = CBORMsgBuf(stream, dict(msg_prefix=frame, console=cons))
147
-
148
- assert isinstance(stream, BaseMsg)
149
-
150
- if lossy:
151
- if lossy is True:
152
- lossy = {}
153
- from moat.lib.stream import ReliableMsg # noqa: PLC0415
154
-
155
- if log_rel is not None:
156
- from moat.lib.stream import LogMsg # noqa: PLC0415
157
-
158
- stream = LogMsg(stream, log_rel)
159
-
160
- stream = ReliableMsg(stream, lossy)
161
-
162
- if log is not None:
163
- from moat.lib.stream import LogMsg # noqa: PLC0415
164
-
165
- stream = LogMsg(stream, log)
166
-
167
- return stream
126
+ return build_stack(stream, cfg, cons=cons)
@@ -17,7 +17,7 @@ class TcpLink(AnyioBuf):
17
17
  A channel that connects to a remote TCP socket.
18
18
  """
19
19
 
20
- def __init__(self, host: str, port: int, retry: dict = {}): # noqa:B006
20
+ def __init__(self, host: str, port: int, retry: dict = {}) -> None: # noqa:B006
21
21
  self.host = host
22
22
  self.port = port
23
23
  self.retry = retry
@@ -89,7 +89,7 @@ class FilenoTerm(FilenoBuf, TermBuf):
89
89
  Warning: Setting up raw mode etc. is the responsibility of the caller.
90
90
  """
91
91
 
92
- async def setup(self): # noqa:D102
92
+ async def setup(self) -> None: # noqa:D102
93
93
  await super().setup()
94
94
 
95
95
  self.__orig_termstate = await self.tget()
@@ -135,7 +135,7 @@ class FilenoTerm(FilenoBuf, TermBuf):
135
135
  else:
136
136
  return True
137
137
 
138
- async def forget_input(self):
138
+ async def forget_input(self) -> None:
139
139
  "Delete pending input"
140
140
  termios.tcflush(self.rfd, termios.TCIFLUSH)
141
141
 
@@ -23,7 +23,7 @@ class UnixLink(AnyioBuf):
23
23
  A channel that connects to a remote Unix socket.
24
24
  """
25
25
 
26
- def __init__(self, port: str | PathLike[str], retry: dict | None = None):
26
+ def __init__(self, port: str | PathLike[str], retry: dict | None = None) -> None:
27
27
  self.port = port
28
28
  if retry is None:
29
29
  retry = {}
@@ -32,23 +32,41 @@ if TYPE_CHECKING:
32
32
  from httpx_ws import AsyncWebSocketSession
33
33
 
34
34
  from moat.util import attrdict
35
- from moat.lib.stream import BaseMsg
36
35
  from moat.lib.stream.base import Buffer, MutBuffer
37
36
 
38
37
 
39
38
  class WsLink(BaseBlk):
40
39
  """
41
40
  A block stream that connects to a remote websocket server.
41
+
42
+ Args:
43
+ url: WebSocket URL to connect to.
44
+ retry: Reconnection parameters (delay, timeout, attempts, backoff).
45
+ subprotocols: Optional list of WebSocket subprotocols to offer
46
+ during the handshake. The negotiated subprotocol is stored in
47
+ :attr:`subprotocol` after a successful connection.
48
+ **kw: Additional keyword arguments forwarded to
49
+ ``httpx_ws.aconnect_ws``.
42
50
  """
43
51
 
44
52
  _crd_buf: bytearray
45
-
46
- def __init__(self, url: str, retry: dict | None = None, **kw):
53
+ subprotocol: str | None
54
+
55
+ def __init__(
56
+ self,
57
+ url: str,
58
+ retry: dict | None = None,
59
+ *,
60
+ subprotocols: list[str] | None = None,
61
+ **kw,
62
+ ) -> None:
47
63
  self.url = url
48
64
  if retry is None:
49
65
  retry = {}
50
66
  self.retry = retry
51
67
  self.kw = kw
68
+ self.subprotocols = subprotocols
69
+ self.subprotocol = None
52
70
 
53
71
  async def stream(self): # noqa:D102
54
72
  from httpx_ws import ( # noqa:PLC0415
@@ -64,10 +82,13 @@ class WsLink(BaseBlk):
64
82
  deadline = anyio.current_time() + retry.get("timeout", 999)
65
83
  attempts = retry.get("attempts", 10)
66
84
  client = await AC_use(self, httpx.AsyncClient())
85
+ kw = dict(self.kw)
86
+ if self.subprotocols is not None:
87
+ kw["subprotocols"] = self.subprotocols
67
88
  try:
68
89
  while True:
69
90
  try:
70
- ws = await AC_use(self, aconnect_ws(self.url, client=client, **self.kw))
91
+ ws = await AC_use(self, aconnect_ws(self.url, client=client, **kw))
71
92
  except (
72
93
  OSError,
73
94
  httpx.HTTPError,
@@ -85,12 +106,13 @@ class WsLink(BaseBlk):
85
106
  else:
86
107
  if n:
87
108
  log("Success: %s", self.url)
109
+ self.subprotocol = ws.subprotocol
88
110
  return ws
89
111
  except TimeoutError:
90
112
  log("Fail: %s, %r", self.url, er)
91
113
  raise
92
114
 
93
- async def setup(self): # noqa:D102
115
+ async def setup(self) -> None: # noqa:D102
94
116
  await super().setup()
95
117
 
96
118
  self._crd_buf = bytearray()
@@ -107,7 +129,7 @@ class WsLink(BaseBlk):
107
129
  await AC_use(self, self._tg.cancel_scope.cancel)
108
130
  self._tg.start_soon(self._reader)
109
131
 
110
- async def _reader(self):
132
+ async def _reader(self) -> None:
111
133
  from httpx_ws import WebSocketDisconnect, WebSocketNetworkError # noqa:PLC0415
112
134
 
113
135
  ws = cast("AsyncWebSocketSession", self.s)
@@ -183,20 +205,39 @@ class WsLink(BaseBlk):
183
205
  class SingleWsBlk(BaseBlk):
184
206
  """
185
207
  Adapt a single accepted TCP connection to a websocket block stream.
208
+
209
+ Args:
210
+ stream: The underlying byte stream (typically a TCP connection).
211
+ path: Optional URL path to accept. Connections to other paths
212
+ are rejected with HTTP 404.
213
+ subprotocols: Optional list of WebSocket subprotocols the server
214
+ is willing to negotiate. During the handshake, the first
215
+ subprotocol offered by the client that also appears in this
216
+ list is selected. The negotiated subprotocol is stored in
217
+ :attr:`subprotocol`.
186
218
  """
187
219
 
188
220
  _crd_buf: bytearray
189
221
  _ws: wsproto.WSConnection | None
190
222
  path: str | None
191
-
192
- def __init__(self, stream: ByteStream, path: str | None = None):
223
+ subprotocol: str | None
224
+
225
+ def __init__(
226
+ self,
227
+ stream: ByteStream,
228
+ path: str | None = None,
229
+ *,
230
+ subprotocols: list[str] | None = None,
231
+ ) -> None:
193
232
  self._stream = stream
194
233
  self.path = path
234
+ self.subprotocols = subprotocols
235
+ self.subprotocol = None
195
236
 
196
237
  async def stream(self): # noqa:D102
197
238
  return await AC_use(self, self._stream)
198
239
 
199
- async def setup(self): # noqa:D102
240
+ async def setup(self) -> None: # noqa:D102
200
241
  await super().setup()
201
242
  self._ws = wsproto.WSConnection(ConnectionType.SERVER)
202
243
  self._crd_buf = bytearray()
@@ -240,7 +281,16 @@ class SingleWsBlk(BaseBlk):
240
281
  if self.path is not None and urlsplit(event.target).path != self.path:
241
282
  await self._send_raw(ws.send(RejectConnection(status_code=404)))
242
283
  raise EOFError
243
- await self._send_raw(ws.send(AcceptConnection()))
284
+ sel = None
285
+ if self.subprotocols is not None:
286
+ for proto in event.subprotocols:
287
+ if proto in self.subprotocols:
288
+ sel = proto
289
+ break
290
+ self.subprotocol = sel
291
+ await self._send_raw(
292
+ ws.send(AcceptConnection(subprotocol=sel) if sel else AcceptConnection())
293
+ )
244
294
  return
245
295
  if isinstance(event, CloseConnection):
246
296
  with suppress(EOFError):
@@ -250,7 +300,7 @@ class SingleWsBlk(BaseBlk):
250
300
  if closed:
251
301
  raise EOFError
252
302
 
253
- async def _reader(self):
303
+ async def _reader(self) -> None:
254
304
  ws = self._ws
255
305
  if ws is None:
256
306
  return
@@ -327,7 +377,7 @@ class SingleWsBlk(BaseBlk):
327
377
  self._crd_buf = self._crd_buf[n:]
328
378
  return n
329
379
 
330
- async def teardown(self): # noqa:D102
380
+ async def teardown(self) -> None: # noqa:D102
331
381
  if self._ws is not None:
332
382
  with suppress(Exception):
333
383
  await self._send_raw(self._ws.send(CloseConnection(code=1000, reason="bye")))
@@ -336,42 +386,14 @@ class SingleWsBlk(BaseBlk):
336
386
 
337
387
 
338
388
  def ws_stack(stream, cfg: attrdict):
339
- """
340
- Build a message stack on top of a websocket block stream.
389
+ """Build a message stack on top of a websocket block stream.
390
+
391
+ This is a thin wrapper around :py:func:`moat.lib.stream.build_stack`
392
+ that forces framed mode (websockets are inherently block-oriented).
341
393
  """
342
394
  if not hasattr(stream, "snd") or not hasattr(stream, "rcv"):
343
395
  raise TypeError(f"need a BaseBlk not {stream}")
344
396
 
345
- link = cfg.get("link", {})
346
- lossy = link.get("lossy", None)
347
- log_cfg = cfg.get("log", None)
348
- log_rel = cfg.get("log_rel", None)
349
- log_raw = cfg.get("log_raw", None)
350
-
351
- if log_raw is not None:
352
- from moat.lib.stream import LogBlk # noqa:PLC0415
353
-
354
- stream = LogBlk(stream, log_raw)
355
-
356
- from moat.lib.stream import CBORMsgBlk # noqa:PLC0415
357
-
358
- stream = CBORMsgBlk(stream, cfg)
359
-
360
- if lossy:
361
- if lossy is True:
362
- lossy = {}
363
- from moat.lib.stream import ReliableMsg # noqa:PLC0415
364
-
365
- if log_rel is not None:
366
- from moat.lib.stream import LogMsg # noqa:PLC0415
367
-
368
- stream = LogMsg(stream, log_rel)
369
-
370
- stream = ReliableMsg(stream, lossy)
371
-
372
- if log_cfg is not None:
373
- from moat.lib.stream import LogMsg # noqa:PLC0415
374
-
375
- stream = LogMsg(stream, log_cfg)
397
+ from moat.lib.stream.base import build_stack # noqa: PLC0415
376
398
 
377
- return cast("BaseMsg", stream)
399
+ return build_stack(stream, cfg, framed=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: moat-lib-stream
3
- Version: 0.3.3
3
+ Version: 0.3.5
4
4
  Summary: Stream infrastructure for MoaT applications
5
5
  Maintainer-email: Matthias Urlichs <matthias@urlichs.de>
6
6
  Project-URL: homepage, https://m-o-a-t.org
@@ -19,7 +19,7 @@ Requires-Dist: moat-lib-micro~=0.3.0
19
19
  Requires-Dist: moat-lib-rpc~=0.7.0
20
20
  Requires-Dist: moat-lib-codec~=0.4.14
21
21
  Requires-Dist: moat-lib-repl~=0.1.4
22
- Requires-Dist: moat-util~=0.63.0
22
+ Requires-Dist: moat-util~=0.64.0
23
23
  Dynamic: license-file
24
24
 
25
25
  # Stream Infrastructure
@@ -8,6 +8,7 @@ debian/rules
8
8
  src/moat/lib/stream/__init__.py
9
9
  src/moat/lib/stream/_cbor.py
10
10
  src/moat/lib/stream/_console.py
11
+ src/moat/lib/stream/_layers.py
11
12
  src/moat/lib/stream/anyio.py
12
13
  src/moat/lib/stream/base.py
13
14
  src/moat/lib/stream/cbor.py
@@ -2,4 +2,4 @@ moat-lib-codec~=0.4.14
2
2
  moat-lib-micro~=0.3.0
3
3
  moat-lib-repl~=0.1.4
4
4
  moat-lib-rpc~=0.7.0
5
- moat-util~=0.63.0
5
+ moat-util~=0.64.0