loop-link 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loop_link/tool.py ADDED
@@ -0,0 +1,343 @@
1
+ """The tool connection: one request and its reply frames on the ``/tool`` path of the viewer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from pathlib import Path
9
+ from typing import Any, NoReturn
10
+
11
+ from loop_link import discovery, encode, protocol
12
+ from loop_link._websocket import WebSocketClient, WebSocketClosed, WebSocketError
13
+ from loop_link.errors import (
14
+ BusyError,
15
+ CancelledError,
16
+ InvalidInputError,
17
+ MissingFeatureError,
18
+ Refusal,
19
+ StaleRevisionError,
20
+ ViewerClosedError,
21
+ ViewerRefusedError,
22
+ )
23
+ from loop_link.protocol import Frame, ProtocolError
24
+
25
+ _LINK_ERRORS = (OSError, WebSocketClosed, WebSocketError)
26
+ _POLL = 0.1
27
+
28
+
29
+ def raise_for_request_error(error: Mapping[str, Any], *, object_id: str | None) -> NoReturn:
30
+ """Raise the loop_link error that matches a ``request.error`` body.
31
+
32
+ Parameters
33
+ ----------
34
+ error : mapping
35
+ The ``error`` body of the frame, with the keys ``code``, ``message`` and ``field``.
36
+ object_id : str, optional
37
+ The identifier of the object that the request is about.
38
+
39
+ Raises
40
+ ------
41
+ loop_link.errors.StaleRevisionError
42
+ The code is ``invalid_input`` and the field is ``revision``.
43
+ loop_link.errors.InvalidInputError
44
+ The code is ``invalid_input`` and the field is another field.
45
+ loop_link.errors.MissingFeatureError
46
+ The code is ``needs_window``.
47
+ loop_link.errors.CancelledError
48
+ The code is ``cancelled``.
49
+ loop_link.errors.BusyError
50
+ The code is ``busy``.
51
+ loop_link.errors.ViewerRefusedError
52
+ The code is another code.
53
+ """
54
+ code = str(error.get("code", ""))
55
+ message = str(error.get("message", ""))
56
+ if code == "invalid_input":
57
+ if error.get("field") == "revision":
58
+ raise StaleRevisionError(object_id or "")
59
+ raise InvalidInputError(f"The viewer refused the request: {message}")
60
+ if code == "needs_window":
61
+ raise MissingFeatureError("a viewer window (this viewer has no window)")
62
+ if code == "cancelled":
63
+ raise CancelledError
64
+ if code == "busy":
65
+ raise BusyError
66
+ raise ViewerRefusedError([Refusal(object_id or "", code, message)])
67
+
68
+
69
+ class ToolConnection:
70
+ """A connection to the ``/tool`` path of the viewer.
71
+
72
+ The connection sends one request at a time. It opens when the first request needs it.
73
+
74
+ Parameters
75
+ ----------
76
+ port : int, optional
77
+ The port of the viewer. The default is to search for it.
78
+ token : str, optional
79
+ The access token. The default is to read it from the environment or the settings.
80
+ host : str
81
+ The host of the viewer.
82
+ settings_dir : pathlib.Path, optional
83
+ The settings folder of the viewer.
84
+ timeout : float
85
+ The time in seconds to wait for the connection and for each reply frame.
86
+ resolve : callable, optional
87
+ Returns the address of the viewer. When it is given, the connection uses it in
88
+ place of its own search, so that it connects to the same viewer as another
89
+ connection. The other address parameters are then not used.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ *,
95
+ port: int | None = None,
96
+ token: str | None = None,
97
+ host: str = "127.0.0.1",
98
+ settings_dir: Path | None = None,
99
+ timeout: float = 5.0,
100
+ resolve: Callable[[], discovery.ViewerAddress] | None = None,
101
+ ) -> None:
102
+ self._resolve = resolve
103
+ self._port = port
104
+ self._token = token
105
+ self._host = host
106
+ self._settings_dir = settings_dir
107
+ self._timeout = timeout
108
+ self._lock = threading.Lock()
109
+ self._client: WebSocketClient | None = None
110
+ self._number = 0
111
+
112
+ @property
113
+ def connected(self) -> bool:
114
+ """True while the connection is open."""
115
+ return self._client is not None
116
+
117
+ def connect(self) -> ToolConnection:
118
+ """Connect to the ``/tool`` path of the viewer. No ``hello`` is sent.
119
+
120
+ Raises
121
+ ------
122
+ loop_link.errors.NoViewerError
123
+ No viewer was found.
124
+ loop_link.errors.TokenError
125
+ The viewer refused the token.
126
+
127
+ Returns
128
+ -------
129
+ ToolConnection
130
+ The connection itself.
131
+ """
132
+ with self._lock:
133
+ self._connect_locked()
134
+ return self
135
+
136
+ def close(self) -> None:
137
+ """Close the connection. It is safe to call it more than one time."""
138
+ with self._lock:
139
+ self._drop_locked()
140
+
141
+ def request(
142
+ self,
143
+ build: Callable[[int], bytes],
144
+ *,
145
+ until: Sequence[str],
146
+ feature: str,
147
+ object_id: str | None = None,
148
+ on_frame: Callable[[Frame], None] | None = None,
149
+ progress: Callable[[float], None] | None = None,
150
+ cancel: threading.Event | None = None,
151
+ timeout: float | None = None,
152
+ ) -> Frame:
153
+ """Send one request and read frames until the reply ends.
154
+
155
+ Parameters
156
+ ----------
157
+ build : callable
158
+ Gets the request number and returns the frame to send.
159
+ until : sequence of str
160
+ The frame types that end the request. The matching frame is returned.
161
+ feature : str
162
+ The name of the feature, for the error when the viewer does not know the message.
163
+ object_id : str, optional
164
+ The identifier of the object that the request is about, for error messages.
165
+ on_frame : callable, optional
166
+ Called with each frame of the request, except ``command.progress`` and
167
+ ``request.error`` frames.
168
+ progress : callable, optional
169
+ Called with the fraction of each ``command.progress`` frame.
170
+ cancel : threading.Event, optional
171
+ When it is set, one ``command.cancel`` frame is sent.
172
+ timeout : float, optional
173
+ The time in seconds to wait for the next frame. The default is the
174
+ timeout of the connection.
175
+
176
+ Returns
177
+ -------
178
+ loop_link.protocol.Frame
179
+ The frame whose type is in ``until``.
180
+
181
+ Raises
182
+ ------
183
+ loop_link.errors.NoViewerError
184
+ No viewer was found.
185
+ loop_link.errors.TokenError
186
+ The viewer refused the token.
187
+ loop_link.errors.ViewerClosedError
188
+ The connection closed, the viewer did not answer in time, or it sent a bad frame.
189
+ loop_link.errors.MissingFeatureError
190
+ The viewer does not know the message or the protocol version.
191
+ loop_link.errors.CancelledError
192
+ The request was cancelled.
193
+ loop_link.errors.ViewerRefusedError
194
+ The viewer refused the request.
195
+ """
196
+ wait = self._timeout if timeout is None else timeout
197
+ with self._lock:
198
+ client = self._connect_locked()
199
+ self._number += 1
200
+ number = self._number
201
+ try:
202
+ client.send_binary(build(number))
203
+ return self._read_locked(
204
+ client, number, until, feature, object_id, on_frame, progress, cancel, wait
205
+ )
206
+ except _LINK_ERRORS as error:
207
+ self._drop_locked()
208
+ raise ViewerClosedError from error
209
+
210
+ def post(self, build: Callable[[int], bytes]) -> int:
211
+ """Send one request and do not wait for a reply.
212
+
213
+ The reply frames of the request stay in the socket. A later request skips them,
214
+ because their request number is not its own.
215
+
216
+ Parameters
217
+ ----------
218
+ build : callable
219
+ Gets the request number and returns the frame to send.
220
+
221
+ Returns
222
+ -------
223
+ int
224
+ The request number.
225
+
226
+ Raises
227
+ ------
228
+ loop_link.errors.NoViewerError
229
+ No viewer was found.
230
+ loop_link.errors.TokenError
231
+ The viewer refused the token.
232
+ loop_link.errors.ViewerClosedError
233
+ The connection closed.
234
+ """
235
+ with self._lock:
236
+ client = self._connect_locked()
237
+ self._number += 1
238
+ number = self._number
239
+ try:
240
+ client.send_binary(build(number))
241
+ except _LINK_ERRORS as error:
242
+ self._drop_locked()
243
+ raise ViewerClosedError from error
244
+ return number
245
+
246
+ # -- helpers --------------------------------------------------------------
247
+
248
+ def _connect_locked(self) -> WebSocketClient:
249
+ """Return the open client, or open one. The caller holds the lock."""
250
+ if self._client is not None:
251
+ return self._client
252
+ if self._resolve is not None:
253
+ address = self._resolve()
254
+ else:
255
+ address = discovery.find_viewer(
256
+ port=self._port,
257
+ token=self._token,
258
+ host=self._host,
259
+ settings=self._settings_dir,
260
+ )
261
+ self._client = WebSocketClient.connect(
262
+ address.host, address.port, token=address.token, timeout=self._timeout, path="/tool"
263
+ )
264
+ return self._client
265
+
266
+ def _drop_locked(self) -> None:
267
+ """Close the socket, if there is one. The caller holds the lock."""
268
+ client, self._client = self._client, None
269
+ if client is not None:
270
+ try:
271
+ client.close()
272
+ except Exception:
273
+ pass
274
+
275
+ def _read_locked(
276
+ self,
277
+ client: WebSocketClient,
278
+ number: int,
279
+ until: Sequence[str],
280
+ feature: str,
281
+ object_id: str | None,
282
+ on_frame: Callable[[Frame], None] | None,
283
+ progress: Callable[[float], None] | None,
284
+ cancel: threading.Event | None,
285
+ wait: float,
286
+ ) -> Frame:
287
+ """Read the frames of one request. The caller holds the lock."""
288
+ last_frame = time.monotonic()
289
+ cancel_sent = False
290
+ while True:
291
+ if cancel is not None and cancel.is_set() and not cancel_sent:
292
+ client.send_binary(encode.cancel_frame(number))
293
+ cancel_sent = True
294
+ data = client.receive(_POLL)
295
+ if data is None:
296
+ if time.monotonic() - last_frame >= wait:
297
+ self._drop_locked()
298
+ raise ViewerClosedError(
299
+ "The viewer did not answer in time. Check the viewer and retry."
300
+ )
301
+ continue
302
+ try:
303
+ frame = protocol.decode_frame(data)
304
+ except ProtocolError as error:
305
+ self._drop_locked()
306
+ raise ViewerClosedError(
307
+ "The viewer sent a frame that is not valid. The connection is closed."
308
+ ) from error
309
+ header = frame.header
310
+ kind = header.get("type")
311
+ if kind == "error":
312
+ self._raise_error_frame(header, feature)
313
+ if header.get("request") != number:
314
+ continue
315
+ last_frame = time.monotonic()
316
+ if kind == "request.error":
317
+ raise_for_request_error(header.get("error") or {}, object_id=object_id)
318
+ if kind == "command.progress":
319
+ fraction = header.get("fraction")
320
+ if progress is not None and isinstance(fraction, (int, float)):
321
+ progress(float(fraction))
322
+ continue
323
+ if on_frame is not None:
324
+ try:
325
+ on_frame(frame)
326
+ except BaseException:
327
+ # The viewer can continue to send the frames of this request. Close
328
+ # the connection so that they stop and a later request does not
329
+ # read them.
330
+ self._drop_locked()
331
+ raise
332
+ if kind in until:
333
+ return frame
334
+
335
+ @staticmethod
336
+ def _raise_error_frame(header: Mapping[str, Any], feature: str) -> NoReturn:
337
+ """Raise the error for an ``error`` frame, which has no request number."""
338
+ code = str(header.get("code", ""))
339
+ if code == "unknown_message":
340
+ raise MissingFeatureError(feature)
341
+ if code == "unsupported_version":
342
+ raise MissingFeatureError("protocol " + str(header.get("supported")))
343
+ raise ViewerRefusedError([Refusal("", code, str(header.get("message", "")))])
loop_link/version.py ADDED
@@ -0,0 +1,12 @@
1
+ """The version of loop_link, read from the installed package metadata."""
2
+
3
+ # The version is set in pyproject.toml. Do not write a version string here:
4
+ # release-please changes each "__version__ = ..." string in every version.py
5
+ # file in the repository to the version of the release it makes.
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ try:
9
+ __version__ = version("loop-link")
10
+ except PackageNotFoundError:
11
+ # the package is imported from source and is not installed
12
+ __version__ = "unknown"