testflows.machine 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.

Potentially problematic release.


This version of testflows.machine might be problematic. Click here for more details.

@@ -0,0 +1,255 @@
1
+ # Copyright 2026 Katteli 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.
14
+ """Exceptions raised by the SDK.
15
+
16
+ Each type is a condition, not a resource: `NotFound` is raised for a session,
17
+ a run or a checkpoint, and the message names what was not found. Every
18
+ exception derives from `Error`.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import contextlib
25
+ from typing import Generator, Optional
26
+
27
+ from testflows.machine._core import api
28
+ from testflows.machine._core import disks
29
+ from testflows.machine._core import ipc
30
+ from testflows.machine._core import refused
31
+ from testflows.machine._core import replay
32
+ from testflows.machine._core import sessions as _sessions
33
+ from testflows.machine._core import wait
34
+
35
+
36
+ class Error(Exception):
37
+ """Base class of every exception the SDK raises.
38
+
39
+ Catch it to handle any SDK failure; the message says what went wrong in
40
+ one sentence, naming the run, session or disk involved.
41
+ """
42
+
43
+
44
+ class NotSignedIn(Error):
45
+ """There are no credentials: no stored login and no
46
+ TESTFLOWS_MACHINE_API_KEY.
47
+
48
+ Sign in with `login.start` and `login.verify`, or `machine login`, or
49
+ set TESTFLOWS_MACHINE_API_KEY.
50
+ """
51
+
52
+
53
+ class Unauthorized(Error):
54
+ """The credentials or the sign-in code were rejected.
55
+
56
+ The login expired or was revoked, the API key is not valid, or the code
57
+ was wrong. Sign in again.
58
+ """
59
+
60
+
61
+ class Forbidden(Error):
62
+ """The account may not do this, such as an account that is not active,
63
+ or a request beyond its plan's limits."""
64
+
65
+
66
+ class NoCapacity(Error):
67
+ """No host of the session's class has room for it now: not enough CPUs,
68
+ RAM or disk, which the message names.
69
+
70
+ Nothing about the request is wrong. The same create can succeed once
71
+ other sessions end; a smaller session or another class may fit now. A
72
+ session that was created and then lost its room raises this too, and
73
+ keeps its name until it is deleted.
74
+ """
75
+
76
+
77
+ class ClassUnavailable(Error):
78
+ """No machine of the session's class is in service.
79
+
80
+ Nothing about the request is wrong, and the class stays valid. A create
81
+ on it succeeds once a machine of it is in service; a smaller session
82
+ does not. Another class may be available now.
83
+ """
84
+
85
+
86
+ class NotFound(Error):
87
+ """No resource matches the name or id: a run, branch, checkpoint,
88
+ session, disk, file or container. The message names what was looked
89
+ for."""
90
+
91
+
92
+ class AlreadyExists(Error):
93
+ """A resource with that name already exists. Choose another name, or
94
+ use the existing resource."""
95
+
96
+
97
+ class InvalidArgument(Error, ValueError):
98
+ """An argument is not valid, or a reference matches more than one
99
+ resource. The message names the argument and what it accepts.
100
+
101
+ It is a `ValueError` too, so code that catches that also catches this.
102
+ """
103
+
104
+
105
+ class NotRunning(Error):
106
+ """The resource exists and is not running: a run with no machine, or a
107
+ session that is not `running`. Start it, or wait for it, first."""
108
+
109
+
110
+ class Conflict(Error):
111
+ """The request conflicts with the resource's current state, such as a
112
+ machine already running, a command in progress, a guest that has halted,
113
+ or branches in the way of a delete. The message says which; change the
114
+ state, then retry."""
115
+
116
+
117
+ class Diverged(Error):
118
+ """A recorded run could not be followed: `Run.play` stopped where the
119
+ machine no longer matched the recording. `Run.replay` reports a
120
+ divergence in its result instead."""
121
+
122
+
123
+ class Timeout(Error, TimeoutError):
124
+ """A wait ran out of time before the expected state was reached.
125
+
126
+ The work goes on in the service: a run keeps booting, a session keeps
127
+ starting. Wait again, or undo it. It is a `TimeoutError` too.
128
+ """
129
+
130
+
131
+ class ServiceUnavailable(Error):
132
+ """The service could not be reached, or cannot answer right now.
133
+
134
+ The account's service did not answer, a session's tunnel is down, or
135
+ the network failed. Retrying later is safe.
136
+ """
137
+
138
+
139
+ class ApiError(Error):
140
+ """The service failed to carry out the request for a reason of its own.
141
+ The message is the service's reason."""
142
+
143
+
144
+ #: Engine exception type -> the public exception it becomes. Checked in order,
145
+ #: so a subclass is listed before its base.
146
+ _MAPPING: tuple[tuple[type[BaseException], type[Error]], ...] = (
147
+ (api.auth.NotSignedIn, NotSignedIn),
148
+ (api.client.Unauthorized, Unauthorized),
149
+ (api.client.InvalidLoginCode, Unauthorized),
150
+ (api.client.AccountInactive, Forbidden),
151
+ (api.client.AccountClosing, Forbidden),
152
+ (api.client.NoCapacity, NoCapacity),
153
+ (api.client.ClassUnavailable, ClassUnavailable),
154
+ (api.client.ServiceUnavailable, ServiceUnavailable),
155
+ (api.client.SessionNameTaken, AlreadyExists),
156
+ (api.transport.TransportError, ServiceUnavailable),
157
+ (_sessions.SessionNotFound, NotFound),
158
+ (_sessions.AmbiguousSession, InvalidArgument),
159
+ (_sessions.SessionNoCapacity, NoCapacity),
160
+ (_sessions.SessionNotRunning, NotRunning),
161
+ (_sessions.NameTaken, AlreadyExists),
162
+ (_sessions.Unreachable, ServiceUnavailable),
163
+ (disks.NotFound, NotFound),
164
+ (api.client.NotFound, NotFound),
165
+ (api.client.Conflict, Conflict),
166
+ (api.client.Forbidden, Forbidden),
167
+ (api.client.Invalid, InvalidArgument),
168
+ (api.client.ApiError, ApiError),
169
+ (replay.Diverged, Diverged),
170
+ (ipc.RunNotFound, NotFound),
171
+ (ipc.AmbiguousRun, InvalidArgument),
172
+ (refused.NotFound, NotFound),
173
+ (refused.AlreadyExists, AlreadyExists),
174
+ (refused.Invalid, InvalidArgument),
175
+ (refused.NotRunning, NotRunning),
176
+ (refused.Diverged, Diverged),
177
+ (refused.TimedOut, Timeout),
178
+ (refused.Refused, Conflict),
179
+ (ipc.ProtocolError, ServiceUnavailable),
180
+ (TimeoutError, Timeout),
181
+ (ConnectionError, ServiceUnavailable),
182
+ (argparse.ArgumentTypeError, InvalidArgument),
183
+ (ValueError, InvalidArgument),
184
+ )
185
+
186
+ _C = ipc.IpcErrorCode
187
+
188
+ #: The service's refusal code -> the public exception it becomes. A code not
189
+ #: listed is the service's own failure, ApiError.
190
+ _CODES: dict[int, type[Error]] = {
191
+ int(_C.NOT_RUNNING): NotRunning,
192
+ int(_C.TERMINATED): NotRunning,
193
+ int(_C.ALREADY_EXISTS): AlreadyExists,
194
+ int(_C.INVALID): InvalidArgument,
195
+ int(_C.OUT_OF_RANGE): InvalidArgument,
196
+ int(_C.NOT_ANCESTOR): InvalidArgument,
197
+ int(_C.NO_SUCH_PATH): NotFound,
198
+ int(_C.NO_SUCH_RUN): NotFound,
199
+ int(_C.NO_SUCH_TASK): NotFound,
200
+ int(_C.NO_SUCH_STOP): NotFound,
201
+ int(_C.NOT_A_FILE): InvalidArgument,
202
+ int(_C.READ_ONLY): Conflict,
203
+ int(_C.BUSY): Conflict,
204
+ int(_C.ALREADY_PENDING): Conflict,
205
+ int(_C.HASHING): Conflict,
206
+ # The run was created without an RNG device; no later command adds one.
207
+ int(_C.NO_RNG): InvalidArgument,
208
+ int(_C.NOT_PENDING): Conflict,
209
+ int(_C.STARTING): Conflict,
210
+ int(_C.HAS_CHILDREN): Conflict,
211
+ int(_C.NOT_SYNCED): Conflict,
212
+ int(_C.REWIND_UNFINISHED): Conflict,
213
+ int(_C.NEEDS_RECOVERY): Conflict,
214
+ int(_C.IS_RUNNING): Conflict,
215
+ int(_C.HALTED): Conflict,
216
+ int(_C.NEVER_RAN): Conflict,
217
+ int(_C.ALREADY_RAN): Conflict,
218
+ int(_C.PUBLISH_SETTLING): Conflict,
219
+ int(_C.PARENT_NOT_PUBLISHED): Conflict,
220
+ int(_C.RUNNING_ELSEWHERE): Conflict,
221
+ int(_C.NOT_READY): Conflict,
222
+ int(_C.DESYNC): Diverged,
223
+ int(_C.TIMEOUT): Timeout,
224
+ int(_C.NOT_RESPONDING): ServiceUnavailable,
225
+ int(_C.STORE_UNAVAILABLE): ServiceUnavailable,
226
+ }
227
+
228
+
229
+ def _public(exc: BaseException) -> Optional[type[Error]]:
230
+ """The public exception type for an engine exception, or None."""
231
+ for engine_type, public_type in _MAPPING:
232
+ if isinstance(exc, engine_type):
233
+ return public_type
234
+ if isinstance(exc, (ipc.MachineError, wait.WaitAborted)):
235
+ return _CODES.get(exc.code, ApiError)
236
+ # A failure the engine reports with no type of its own: the service could
237
+ # not carry out the request. Exactly RuntimeError, so a subclass that is a
238
+ # bug, such as RecursionError, still surfaces as itself.
239
+ if type(exc) is RuntimeError:
240
+ return ApiError
241
+ return None
242
+
243
+
244
+ @contextlib.contextmanager
245
+ def _translated() -> Generator[None, None, None]:
246
+ """Raise the public exception for an engine exception, message unchanged."""
247
+ try:
248
+ yield
249
+ except Error:
250
+ raise
251
+ except Exception as exc:
252
+ public = _public(exc)
253
+ if public is None:
254
+ raise
255
+ raise public(str(exc)) from None
@@ -0,0 +1,107 @@
1
+ # Copyright 2026 Katteli 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.
14
+ """Sign in with a code sent by email, and sign out.
15
+
16
+ Signing in is two calls because the code arrives by email between them:
17
+
18
+ machine.login.start("me@example.com")
19
+ client = machine.login.verify("me@example.com", code="123456")
20
+
21
+ The login is stored where `machine login` keeps it, so the CLI and the SDK
22
+ share it. Automation uses TESTFLOWS_MACHINE_API_KEY instead.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from typing import Optional
28
+
29
+ import testflows.machine._core.login as _login
30
+
31
+ from .client import Client
32
+ from .errors import _translated
33
+
34
+
35
+ def start(email: str, *, api_url: Optional[str] = None) -> None:
36
+ """Send a sign-in code to `email`, as `machine login` does first.
37
+
38
+ The code arrives by email; pass it to `verify` to finish signing in. The
39
+ service answers the same whether or not an account exists, so this
40
+ returning is not proof that a code was sent. A program that runs
41
+ unattended sets TESTFLOWS_MACHINE_API_KEY instead of signing in.
42
+
43
+ Args:
44
+ email (str): The account's email address.
45
+ api_url (str, optional): The service's URL; defaults to
46
+ TESTFLOWS_MACHINE_API_URL, else the public service.
47
+
48
+ Raises:
49
+ ServiceUnavailable: The service could not be reached.
50
+ """
51
+ with _translated():
52
+ client, _ = _login.client_for(api_url)
53
+ _login.start(client, email)
54
+
55
+
56
+ def verify(
57
+ email: str, *, code: str, api_url: Optional[str] = None, save: bool = True
58
+ ) -> Client:
59
+ """Sign in with the code `start` sent to `email`.
60
+
61
+ With `save`, the login is stored where `machine login` keeps it, so the
62
+ CLI and every later `Client` use it until it expires or `logout` removes
63
+ it. Without it, only the returned client is signed in.
64
+
65
+ Args:
66
+ email (str): The account's email address, as passed to `start`.
67
+ code (str): The code from the email.
68
+ api_url (str, optional): The service's URL; defaults to
69
+ TESTFLOWS_MACHINE_API_URL, else the public service.
70
+ save (bool, optional): Store the login. Defaults to True.
71
+
72
+ Returns:
73
+ Client: A client with no session, signed in;
74
+ `client.sessions.use` gives it one.
75
+
76
+ Raises:
77
+ Unauthorized: The code is wrong or has expired; call `start` again.
78
+ ServiceUnavailable: The service could not be reached.
79
+ """
80
+ with _translated():
81
+ client, base_url = _login.client_for(api_url)
82
+ _, token = _login.verify(client, base_url, email, code, save=save)
83
+ return Client._signed_in(
84
+ client, {"access_token": token, "base_url": base_url}, api_url
85
+ )
86
+
87
+
88
+ def logout(*, everywhere: bool = False, api_url: Optional[str] = None) -> bool:
89
+ """Sign out the stored login, as `machine logout` does.
90
+
91
+ The stored login is removed even when the service cannot be reached; the
92
+ login then stays valid on the service until it expires, and this returns
93
+ False. An API key in TESTFLOWS_MACHINE_API_KEY is not affected.
94
+
95
+ Args:
96
+ everywhere (bool, optional): Sign out every login of the account,
97
+ on every machine. Defaults to False.
98
+ api_url (str, optional): The service's URL; defaults to
99
+ TESTFLOWS_MACHINE_API_URL, else the public service.
100
+
101
+ Returns:
102
+ bool: True when the service revoked the login; False when there was
103
+ none, or the service could not be told.
104
+ """
105
+ with _translated():
106
+ out = _login.logout(api_url, everywhere=everywhere)
107
+ return out.revoked is _login.Revoked.YES
@@ -0,0 +1,70 @@
1
+ # Copyright 2026 Katteli 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.
14
+ """Reachability and latency of the service and the sessions."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Any, Optional
20
+
21
+ from testflows.machine._core import ping as _ping
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Ping:
26
+ """A service's reachability and latency, as `Client.ping` measured it.
27
+
28
+ Attributes:
29
+ ok (bool): Whether the service was reached.
30
+ samples (tuple[float, ...]): Warm round trips in milliseconds, after
31
+ the connection was made.
32
+ connect_ms (float, optional): Milliseconds to make the connection;
33
+ None when it was not made.
34
+ error (str): Why the service was not reached, in a few words; empty
35
+ when `ok` is True.
36
+ """
37
+
38
+ ok: bool
39
+ samples: tuple[float, ...]
40
+ connect_ms: Optional[float]
41
+ error: str
42
+
43
+ @property
44
+ def rtt_ms(self) -> Optional[float]:
45
+ """float: The average round trip in milliseconds; None when the
46
+ service was not reached."""
47
+ return sum(self.samples) / len(self.samples) if self.samples else None
48
+
49
+ def as_json(self) -> dict[str, Any]:
50
+ """The fields as a JSON-serializable dict.
51
+
52
+ Returns:
53
+ dict[str, Any]: One key per attribute.
54
+ """
55
+ return {
56
+ "ok": self.ok,
57
+ "samples": list(self.samples),
58
+ "connect_ms": self.connect_ms,
59
+ "error": self.error,
60
+ }
61
+
62
+
63
+ def _public(probe: _ping.Probe) -> Ping:
64
+ """The public form of a probe."""
65
+ return Ping(
66
+ ok=probe.ok,
67
+ samples=tuple(probe.samples),
68
+ connect_ms=probe.connect_ms,
69
+ error=probe.error,
70
+ )