laborchestra 0.1.0a1__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.
@@ -0,0 +1,29 @@
1
+ """LabOrchestra: one control layer for all instruments of an experiment."""
2
+
3
+ from .device import Device, Service, action
4
+ from .errors import AuthError, ConnectionLost, LabOrchestraError, RemoteError, SchemaError
5
+ from .lab import AsyncLab, Lab, connect, connect_async
6
+ from .procedures import procedure
7
+ from .recording import Recording, load_recording
8
+ from .stream import Frame
9
+
10
+ __version__ = "0.1.0a1" # PEP 440; the server and the release say 0.1.0-alpha.1, the same version
11
+ from ._hub import PROTOCOL # noqa: E402
12
+ __all__ = [
13
+ "Device",
14
+ "Service",
15
+ "action",
16
+ "procedure",
17
+ "connect",
18
+ "connect_async",
19
+ "Lab",
20
+ "AsyncLab",
21
+ "Recording",
22
+ "Frame",
23
+ "load_recording",
24
+ "LabOrchestraError",
25
+ "RemoteError",
26
+ "AuthError",
27
+ "ConnectionLost",
28
+ "SchemaError",
29
+ ]
@@ -0,0 +1,24 @@
1
+ """Names for the channels of a device, filled in by the framework: a driver does nothing for them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def name_channels(state: dict, names: list | dict | None = None) -> None:
9
+ """Gives every channel in ``state`` (a ``channels`` list of dicts, at the top or under a mounted profile such as ``generator.channels``) a
10
+ ``name``, in place: from the option ``channel_names`` (a list for the top-level ``channels``, or a dict from the path of a channel list to
11
+ its list: ``{"channels": [...], "generator.channels": [...]}``), else ``Channel <index>``. A driver does not name its channels."""
12
+ wanted = {"channels": names} if isinstance(names, list) else dict(names or {})
13
+
14
+ def walk(node: dict, path: str) -> None:
15
+ for key, value in node.items():
16
+ here = f"{path}.{key}" if path else key
17
+ if key == "channels" and isinstance(value, list) and value and all(isinstance(c, dict) for c in value):
18
+ given = wanted.get(here) or []
19
+ for i, channel in enumerate(value):
20
+ channel["name"] = str(given[i]) if i < len(given) and given[i] else f"Channel {i}"
21
+ elif isinstance(value, dict):
22
+ walk(value, here)
23
+
24
+ walk(state, "")
laborchestra/_hub.py ADDED
@@ -0,0 +1,266 @@
1
+ """Minimal asyncio client for the SignalR MessagePack protocol.
2
+
3
+ Supports invocations in both directions with results and errors (``client results``), binary
4
+ payloads, automatic reconnect and a callback after every (re)connect. No negotiation: it speaks
5
+ WebSocket directly.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import inspect
12
+ import itertools
13
+ import json
14
+ import logging
15
+ import ssl
16
+ import traceback
17
+ from typing import Any, Awaitable, Callable
18
+ from urllib.parse import urlsplit, urlunsplit
19
+
20
+ import msgpack
21
+ import websockets
22
+ from websockets.exceptions import InvalidStatus, WebSocketException
23
+
24
+ from . import _tls
25
+ from .errors import AuthError, ConnectionLost, RemoteError
26
+
27
+ log = logging.getLogger("laborchestra.hub")
28
+ _RS = b"\x1e"
29
+
30
+
31
+ def _default(obj: Any) -> Any:
32
+ if hasattr(obj, "tolist"): # numpy arrays and scalars
33
+ return obj.tolist()
34
+ if hasattr(obj, "item"):
35
+ return obj.item()
36
+ raise TypeError(f"Cannot serialize {type(obj).__name__}")
37
+
38
+
39
+ def _pack(message: list) -> bytes:
40
+ body = msgpack.packb(message, default=_default)
41
+ n, prefix = len(body), bytearray()
42
+ while True:
43
+ b, n = n & 0x7F, n >> 7
44
+ prefix.append(b | (0x80 if n else 0))
45
+ if not n:
46
+ return bytes(prefix) + body
47
+
48
+
49
+ def _unpack(raw: bytes):
50
+ offset = 0
51
+ while offset < len(raw):
52
+ n = shift = 0
53
+ while True:
54
+ b = raw[offset]
55
+ offset += 1
56
+ n |= (b & 0x7F) << shift
57
+ shift += 7
58
+ if not b & 0x80:
59
+ break
60
+ yield msgpack.unpackb(raw[offset : offset + n], strict_map_key=False)
61
+ offset += n
62
+
63
+
64
+ def _ws_url(url: str) -> str:
65
+ parts = urlsplit(url)
66
+ scheme = {"http": "ws", "https": "wss"}.get(parts.scheme, parts.scheme)
67
+ return urlunsplit((scheme, parts.netloc, parts.path, parts.query, ""))
68
+
69
+
70
+ def _tls_context(url: str):
71
+ """For wss://: see :mod:`laborchestra._tls`. None for ws:// (websockets then does not use TLS)."""
72
+ if not url.startswith("wss://"):
73
+ return None
74
+ return _tls.context(url)
75
+
76
+
77
+ def error_text(exc: BaseException) -> str:
78
+ """The error as it is sent to the caller: JSON with type, message and traceback."""
79
+ if isinstance(exc, RemoteError):
80
+ return json.dumps({"type": exc.type, "message": exc.message, "traceback": exc.traceback})
81
+ return json.dumps(
82
+ {
83
+ "type": type(exc).__name__,
84
+ "message": str(exc),
85
+ "traceback": "".join(traceback.format_exception(exc)),
86
+ }
87
+ )
88
+
89
+
90
+ PROTOCOL = 1 # the wire protocol this package speaks; the server says when it does not understand it
91
+
92
+
93
+ class Hub:
94
+ def __init__(
95
+ self,
96
+ url: str,
97
+ token: str | None = None,
98
+ *,
99
+ on_connected: Callable[[], Awaitable[None]] | None = None,
100
+ retry_delay: float = 0.5,
101
+ ):
102
+ self.url = _ws_url(url) + ("&" if "?" in url else "?") + f"protocol={PROTOCOL}"
103
+ self.token = token
104
+ self.connects = 0
105
+ self.fatal: Exception | None = None
106
+ self._on_connected = on_connected
107
+ self._retry_delay = retry_delay
108
+ self._handlers: dict[str, Callable] = {}
109
+ self._pending: dict[str, asyncio.Future] = {}
110
+ self._ids = itertools.count(1)
111
+ self._connected = asyncio.Event()
112
+ self._ws = None
113
+ self._task: asyncio.Task | None = None
114
+
115
+ def on(self, name: str):
116
+ def register(fn):
117
+ self._handlers[name] = fn
118
+ return fn
119
+
120
+ return register
121
+
122
+ async def start(self) -> None:
123
+ if self._task is None:
124
+ self._task = asyncio.create_task(self._run(), name="hub")
125
+
126
+ async def wait_connected(self, timeout: float | None = None) -> None:
127
+ await asyncio.wait_for(self._connected.wait(), timeout)
128
+ if self.fatal:
129
+ raise self.fatal
130
+
131
+ @property
132
+ def is_connected(self) -> bool:
133
+ return self._connected.is_set() and not self.fatal
134
+
135
+ async def invoke(self, target: str, *args: Any, timeout: float | None = 30) -> Any:
136
+ await self.wait_connected()
137
+ iid = str(next(self._ids))
138
+ future = self._pending[iid] = asyncio.get_running_loop().create_future()
139
+ try:
140
+ await self._ws.send(_pack([1, {}, iid, target, list(args), []]))
141
+ return await asyncio.wait_for(future, timeout)
142
+ finally:
143
+ self._pending.pop(iid, None)
144
+
145
+ async def send(self, target: str, *args: Any) -> None:
146
+ await self.wait_connected()
147
+ await self._ws.send(_pack([1, {}, None, target, list(args), []]))
148
+
149
+ async def close(self) -> None:
150
+ if self._task:
151
+ self._task.cancel()
152
+ try:
153
+ await self._task
154
+ except asyncio.CancelledError:
155
+ pass
156
+ self._task = None
157
+
158
+ async def _run(self) -> None:
159
+ while True:
160
+ try:
161
+ headers = {"Authorization": f"Bearer {self.token}"} if self.token else None
162
+ async with websockets.connect(
163
+ self.url, additional_headers=headers, max_size=None, compression=None, open_timeout=10, ssl=_tls_context(self.url)
164
+ ) as ws:
165
+ await ws.send(json.dumps({"protocol": "messagepack", "version": 1}) + "\x1e")
166
+ raw = await ws.recv()
167
+ head, _, rest = (raw.encode() if isinstance(raw, str) else raw).partition(_RS)
168
+ if error := json.loads(head).get("error"):
169
+ self.fatal = ConnectionError(f"Server rejected the handshake: {error}")
170
+ self._connected.set()
171
+ return
172
+ self._ws = ws
173
+ self.connects += 1
174
+ self._connected.set()
175
+ background = {asyncio.create_task(self._ping(ws))}
176
+ if self._on_connected:
177
+ background.add(asyncio.create_task(self._safe(self._on_connected())))
178
+ try:
179
+ for message in _unpack(rest):
180
+ self._dispatch(ws, message, background)
181
+ async for raw in ws:
182
+ for message in _unpack(raw):
183
+ if self._dispatch(ws, message, background) == "close":
184
+ raise ConnectionError("closed by server")
185
+ finally:
186
+ for task in background:
187
+ task.cancel()
188
+ except ssl.SSLCertVerificationError as e: # waiting will not make the certificate trusted
189
+ self.fatal = ConnectionError(_tls.not_trusted(e.verify_message, self.url))
190
+ self._connected.set()
191
+ return
192
+ except InvalidStatus as e:
193
+ if e.response.status_code == 426: # the server does not speak our protocol: no use in trying again
194
+ try:
195
+ said = json.loads(e.response.body or b"{}").get("error", "")
196
+ except ValueError:
197
+ said = ""
198
+ self.fatal = ConnectionError(said or "The server does not understand this version of the laborchestra package")
199
+ self._connected.set()
200
+ return
201
+ if e.response.status_code in (401, 403):
202
+ self.fatal = AuthError(f"The server rejected the token (HTTP {e.response.status_code})")
203
+ self._connected.set()
204
+ return
205
+ log.warning("Connection failed: %s", e)
206
+ except (OSError, WebSocketException, ConnectionError, asyncio.TimeoutError) as e:
207
+ log.debug("Connection lost: %s", e)
208
+ self._connected.clear()
209
+ for future in self._pending.values():
210
+ if not future.done():
211
+ future.set_exception(ConnectionLost("Connection lost"))
212
+ self._pending.clear()
213
+ await asyncio.sleep(self._retry_delay)
214
+
215
+ async def _safe(self, coroutine) -> None:
216
+ try:
217
+ await coroutine
218
+ except asyncio.CancelledError:
219
+ raise
220
+ except Exception:
221
+ log.exception("Error after connecting")
222
+
223
+ async def _ping(self, ws) -> None:
224
+ while True:
225
+ await asyncio.sleep(10)
226
+ await ws.send(_pack([6]))
227
+
228
+ def _dispatch(self, ws, message: list, background: set) -> str | None:
229
+ kind = message[0]
230
+ if kind == 1: # invocation
231
+ task = asyncio.create_task(self._handle(ws, message[2], message[3], message[4]))
232
+ background.add(task)
233
+ task.add_done_callback(background.discard)
234
+ elif kind == 3: # completion
235
+ future = self._pending.get(message[2])
236
+ if future and not future.done():
237
+ if message[3] == 1:
238
+ future.set_exception(RemoteError.parse(message[4]))
239
+ else:
240
+ future.set_result(message[4] if message[3] == 3 else None)
241
+ elif kind == 7:
242
+ return "close"
243
+ return None
244
+
245
+ async def _handle(self, ws, iid: str | None, target: str, args: list) -> None:
246
+ try:
247
+ handler = self._handlers.get(target)
248
+ if handler is None:
249
+ if iid is None: # a notification nobody here cares about
250
+ log.debug("Ignoring '%s'", target)
251
+ return
252
+ raise LookupError(f"No handler for '{target}'")
253
+ result = handler(*args)
254
+ if inspect.isawaitable(result):
255
+ result = await result
256
+ # always a result (possibly null): SignalR rejects a void completion for a call that expects a result
257
+ reply = [3, {}, iid, 3, result]
258
+ except Exception as e:
259
+ if iid is None:
260
+ log.exception("Error in handler '%s'", target)
261
+ reply = [3, {}, iid, 1, error_text(e)]
262
+ if iid is not None:
263
+ try:
264
+ await ws.send(_pack(reply))
265
+ except WebSocketException:
266
+ pass
laborchestra/_load.py ADDED
@@ -0,0 +1,29 @@
1
+ """Loading a Python file of the workspace (a device, a procedure) as a module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import sys
7
+ from pathlib import Path
8
+ from types import ModuleType
9
+
10
+ from .errors import SchemaError
11
+
12
+
13
+ def load_file(path: str | Path, module_name: str) -> ModuleType:
14
+ """Runs the file as a module and returns it.
15
+
16
+ The source is compiled each time, and no bytecode cache is read or written: Python decides whether a cached copy is still good by the
17
+ modification time of the file in whole seconds and its size, so a file that is saved twice within a second, with a change that keeps
18
+ its length, would run as it was before. A device file is small and loaded once per start: the cache would buy nothing.
19
+ """
20
+ file = Path(path).resolve()
21
+ spec = importlib.util.spec_from_file_location(module_name, file)
22
+ if spec is None or spec.loader is None:
23
+ raise SchemaError(f"Cannot load {path}")
24
+ sys.path.insert(0, str(file.parent)) # the file may import a helper next to it
25
+ module = importlib.util.module_from_spec(spec)
26
+ sys.modules[module_name] = module
27
+ code = compile(file.read_bytes(), str(file), "exec") # bytes: the encoding line of the file is honoured
28
+ exec(code, module.__dict__)
29
+ return module
laborchestra/_patch.py ADDED
@@ -0,0 +1,77 @@
1
+ """State patches: ``{"set": {"channels.1.pressure": 3e-7}, "del": ["name"]}``.
2
+
3
+ Paths are dot separated keys; numeric parts index lists. Keys are snake_case and cannot contain dots, so paths
4
+ are unambiguous. Lists whose length changed are replaced as a whole (``set`` on the path of the list).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+
12
+ class PatchError(ValueError):
13
+ pass
14
+
15
+
16
+ def _same(a: Any, b: Any) -> bool:
17
+ if isinstance(a, float) and isinstance(b, float) and a != a and b != b:
18
+ return True # NaN == NaN here
19
+ return type(a) is type(b) and a == b
20
+
21
+
22
+ def diff(old: Any, new: Any) -> dict:
23
+ """The patch that turns ``old`` into ``new`` (both plain dicts); empty if they are equal."""
24
+ sets: dict[str, Any] = {}
25
+ dels: list[str] = []
26
+
27
+ def walk(a: Any, b: Any, path: str) -> None:
28
+ if isinstance(a, dict) and isinstance(b, dict):
29
+ for key in a.keys() - b.keys():
30
+ dels.append(f"{path}.{key}" if path else key)
31
+ for key, value in b.items():
32
+ child = f"{path}.{key}" if path else key
33
+ if key not in a:
34
+ sets[child] = value
35
+ else:
36
+ walk(a[key], value, child)
37
+ elif isinstance(a, list) and isinstance(b, list) and len(a) == len(b):
38
+ for i, (x, y) in enumerate(zip(a, b)):
39
+ walk(x, y, f"{path}.{i}")
40
+ elif not _same(a, b):
41
+ sets[path] = b
42
+
43
+ walk(old, new, "")
44
+ patch: dict = {}
45
+ if sets:
46
+ patch["set"] = sets
47
+ if dels:
48
+ patch["del"] = sorted(dels)
49
+ return patch
50
+
51
+
52
+ def _resolve(root: Any, path: str):
53
+ parts = path.split(".")
54
+ node = root
55
+ for part in parts[:-1]:
56
+ node = node[int(part)] if isinstance(node, list) else node[part]
57
+ return node, parts[-1]
58
+
59
+
60
+ def apply_patch(state: dict, patch: dict) -> None:
61
+ """Change ``state`` in place. Raises PatchError if a path does not exist (the caller then resyncs)."""
62
+ try:
63
+ for path in patch.get("del", []):
64
+ parent, key = _resolve(state, path)
65
+ if isinstance(parent, list):
66
+ raise PatchError(f"Cannot delete the list element {path}")
67
+ del parent[key]
68
+ for path, value in patch.get("set", {}).items():
69
+ parent, key = _resolve(state, path)
70
+ if isinstance(parent, list):
71
+ parent[int(key)] = value
72
+ else:
73
+ parent[key] = value
74
+ except (KeyError, IndexError, ValueError, TypeError) as e:
75
+ if isinstance(e, PatchError):
76
+ raise
77
+ raise PatchError(f"Cannot apply the patch: {type(e).__name__}: {e}") from e
@@ -0,0 +1,166 @@
1
+ """Derive the public description of a device (options, actions, state) and enforce conventions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import json
7
+ import re
8
+ import types
9
+ import typing
10
+ from typing import Any, Callable
11
+
12
+ from .errors import SchemaError
13
+
14
+ _SNAKE = re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$")
15
+ RESERVED = frozenset({"state", "persist", "id", "lab", "log", "running", "lock", "widget", "profiles", "units", "kind", "channel_names"})
16
+ MISSING = object()
17
+
18
+
19
+ def check_name(name: Any, what: str) -> None:
20
+ if not isinstance(name, str) or not _SNAKE.match(name):
21
+ raise SchemaError(f"{what} '{name}' must be snake_case (lowercase letters, digits, underscores)")
22
+
23
+
24
+ def _from_annotation(annotation: Any) -> str | None:
25
+ if isinstance(annotation, str):
26
+ parts = [p for p in annotation.replace(" ", "").split("|") if p != "None"]
27
+ return parts[0] if len(parts) == 1 and parts[0] in ("bool", "int", "float", "str") else None
28
+ if typing.get_origin(annotation) in (typing.Union, types.UnionType):
29
+ args = [a for a in typing.get_args(annotation) if a is not type(None)]
30
+ return _from_annotation(args[0]) if len(args) == 1 else None
31
+ return annotation.__name__ if annotation in (bool, int, float, str) else None
32
+
33
+
34
+ def base_type(annotation: Any = MISSING, default: Any = MISSING) -> str:
35
+ if annotation is not MISSING and annotation is not inspect.Parameter.empty:
36
+ if found := _from_annotation(annotation):
37
+ return found
38
+ if default is not MISSING and default is not inspect.Parameter.empty:
39
+ for python_type, name in ((bool, "bool"), (int, "int"), (float, "float"), (str, "str")):
40
+ if isinstance(default, python_type):
41
+ return name
42
+ return "json"
43
+
44
+
45
+ def _json_default(value: Any) -> Any:
46
+ try:
47
+ json.dumps(value)
48
+ return value
49
+ except (TypeError, ValueError):
50
+ return None
51
+
52
+
53
+ def config_options(cls: type, base: type) -> list[dict]:
54
+ """Options are class attributes: annotated without default = required, with default = optional."""
55
+ annotations: dict[str, Any] = {}
56
+ defaults: dict[str, Any] = {}
57
+ for klass in reversed(cls.__mro__):
58
+ if klass is object or klass is base:
59
+ continue
60
+ annotations.update(inspect.get_annotations(klass))
61
+ for name, value in vars(klass).items():
62
+ if name.startswith("_") or name in RESERVED:
63
+ continue
64
+ if callable(value) or isinstance(value, (property, classmethod, staticmethod)):
65
+ continue
66
+ defaults[name] = value
67
+ options = []
68
+ for name in {**annotations, **defaults}:
69
+ if name.startswith("_") or name in RESERVED:
70
+ continue
71
+ default = defaults.get(name, MISSING)
72
+ check_name(name, "Option")
73
+ options.append(
74
+ {
75
+ "name": name,
76
+ "type": base_type(annotations.get(name, MISSING), default),
77
+ "default": None if default is MISSING else _json_default(default),
78
+ "required": default is MISSING,
79
+ }
80
+ )
81
+ # a device with channels can name them (the framework puts the names into the state, see Device.channel_names): no driver has to say so
82
+ state = getattr(cls, "state", None)
83
+ if isinstance(state, dict) and "channels" in state and getattr(cls, "kind", "device") != "service" and not any(o["name"] == "channel_names" for o in options):
84
+ options.append({"name": "channel_names", "type": "json", "default": _json_default(list(getattr(cls, "channel_names", []) or [])), "required": False})
85
+ return options
86
+
87
+
88
+ def action_methods(cls: type) -> dict[str, Callable]:
89
+ found = {}
90
+ for name in dir(cls):
91
+ if name.startswith("_"):
92
+ continue
93
+ value = inspect.getattr_static(cls, name)
94
+ if inspect.isfunction(value) and getattr(value, "__lab_action__", False):
95
+ check_name(name, "Action")
96
+ found[name] = value
97
+ return found
98
+
99
+
100
+ def _parameters(fn: Callable) -> list[inspect.Parameter]:
101
+ params = list(inspect.signature(fn).parameters.values())[1:] # without self
102
+ for p in params:
103
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD, p.KEYWORD_ONLY):
104
+ raise SchemaError(f"Action '{fn.__name__}': parameter '{p.name}' must be a plain positional parameter")
105
+ check_name(p.name, f"Parameter of action '{fn.__name__}'")
106
+ return params
107
+
108
+
109
+ def action_schema(name: str, fn: Callable) -> dict:
110
+ params = [
111
+ {
112
+ "name": p.name,
113
+ "type": base_type(p.annotation, p.default),
114
+ "default": None if p.default is p.empty else _json_default(p.default),
115
+ "required": p.default is p.empty,
116
+ }
117
+ for p in _parameters(fn)
118
+ ]
119
+ return {"name": name, "doc": inspect.getdoc(fn), "params": params}
120
+
121
+
122
+ def validate_state(value: Any, path: str = "state") -> None:
123
+ if isinstance(value, dict):
124
+ for key, item in value.items():
125
+ check_name(key, f"Key in {path}")
126
+ validate_state(item, f"{path}.{key}")
127
+ elif isinstance(value, (list, tuple)):
128
+ for i, item in enumerate(value):
129
+ validate_state(item, f"{path}[{i}]")
130
+
131
+
132
+ def coerce(value: Any, type_name: str, what: str, allow_none: bool = False) -> Any:
133
+ if value is None:
134
+ if allow_none or type_name == "json":
135
+ return None
136
+ raise TypeError(f"{what} must be {type_name}, got None")
137
+ ok = isinstance(value, bool) if type_name == "bool" else not isinstance(value, bool)
138
+ if type_name == "float" and isinstance(value, (int, float)) and ok:
139
+ return float(value)
140
+ if type_name == "int" and ok:
141
+ if isinstance(value, int):
142
+ return value
143
+ if isinstance(value, float) and value.is_integer():
144
+ return int(value)
145
+ if type_name == "bool" and isinstance(value, bool):
146
+ return value
147
+ if type_name == "str" and isinstance(value, str):
148
+ return value
149
+ if type_name == "json":
150
+ return value
151
+ raise TypeError(f"{what} must be {type_name}, got {type(value).__name__}")
152
+
153
+
154
+ def coerce_arguments(fn: Callable, args: list) -> list:
155
+ params = _parameters(fn)
156
+ if len(args) > len(params):
157
+ raise TypeError(f"{fn.__name__}() takes {len(params)} argument(s), got {len(args)}")
158
+ result = []
159
+ for i, p in enumerate(params):
160
+ if i < len(args):
161
+ result.append(
162
+ coerce(args[i], base_type(p.annotation, p.default), f"Parameter '{p.name}'", p.default is None)
163
+ )
164
+ elif p.default is p.empty:
165
+ raise TypeError(f"{fn.__name__}() is missing the argument '{p.name}'")
166
+ return result