testflows.machine 0.1.4__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,125 @@
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
+ """The service a session's runs live in, and how to reach it."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import logging
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Generator, Optional
22
+
23
+ from testflows.machine._core import api
24
+ from testflows.machine._core import ipc
25
+ from testflows.machine._core import machines
26
+ from testflows.machine._core import sessions as _sessions
27
+ from testflows.machine._core import tunnel
28
+
29
+ from .errors import NotFound, ServiceUnavailable, _translated
30
+
31
+ #: Where the SDK says what a call waits on, such as a session moving to
32
+ #: another host. At INFO: the call goes on by itself.
33
+ _log = logging.getLogger("testflows.machine")
34
+
35
+
36
+ class _Service:
37
+ """One session's service: where its socket is and how disks are named.
38
+
39
+ `socket` is None for the local service's default socket. `disks` lists
40
+ the account's disks, which a cloud session names by; None for the
41
+ local service, which takes a path. `renew` keeps a cloud session's
42
+ access current before each connection; None for the local service.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ socket: Optional[Path],
48
+ disks: Optional[Callable[[], list[dict[str, Any]]]],
49
+ label: str,
50
+ renew: Optional[Callable[[], None]] = None,
51
+ follow: Optional[Callable[[], Optional[Path]]] = None,
52
+ ) -> None:
53
+ self.socket = socket
54
+ self.disks = disks
55
+ self.label = label
56
+ self.renew = renew
57
+ #: Follows the session when it moved, `sessions migrate`, and gives the
58
+ #: socket of where it went: a call that meets the move goes on there.
59
+ self.follow = follow
60
+
61
+ @contextlib.contextmanager
62
+ def client(self) -> Generator[ipc.Client, None, None]:
63
+ """A connection to the service, closed on exit, with engine errors
64
+ translated to the SDK's."""
65
+ with _translated():
66
+ if self.socket is None and not ipc.Client.is_available():
67
+ raise ServiceUnavailable(f"The {self.label} is not running.")
68
+ if self.renew is not None:
69
+ self.renew()
70
+ client = ipc.Client(
71
+ socket_path=self.socket, follow=self.follow, notice=_log.info
72
+ )
73
+ try:
74
+ client.connect()
75
+ except OSError as exc:
76
+ raise ServiceUnavailable(
77
+ f"Could not reach the {self.label}: {exc}"
78
+ ) from None
79
+ try:
80
+ yield client
81
+ finally:
82
+ client.close()
83
+
84
+ def disk(self, disk: str) -> "machines.DiskRef":
85
+ """What the service takes for `disk`, and what the catalog says about
86
+ it: an absolute path for the local service, or the content hash of the
87
+ named disk plus its labels for a cloud session."""
88
+ with _translated():
89
+ return machines.resolve_disk(
90
+ disk, local=self.disks is None, list_disks=self.disks
91
+ )
92
+
93
+
94
+ def local() -> _Service:
95
+ """The local service, on its default socket."""
96
+ return _Service(None, None, "local service")
97
+
98
+
99
+ def of_session(
100
+ client: api.client.Client,
101
+ creds: dict[str, Any],
102
+ session_id: str,
103
+ name: str,
104
+ follow: Optional[Callable[[], Optional[Path]]] = None,
105
+ ) -> _Service:
106
+ """A cloud session's service, through this machine's tunnel to it.
107
+
108
+ Opens the tunnel when it is not up; reuses it when it is.
109
+ """
110
+ with _translated():
111
+ _sessions.connect(client, creds, session_id, wait=False)
112
+ socket = api.store.session_socket(session_id)
113
+ sdir = api.store.session_dir(session_id)
114
+
115
+ def renew() -> None:
116
+ if not tunnel.renew_stale_cert(sdir, session_id, client, creds):
117
+ raise NotFound(f"Session {name} no longer exists.")
118
+
119
+ return _Service(
120
+ socket,
121
+ lambda: api.auth.authed(creds, client.disk_list),
122
+ f"service of session {name}",
123
+ renew,
124
+ follow,
125
+ )
@@ -0,0 +1,16 @@
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
+ """The SDK's version."""
15
+
16
+ __version__ = "0.1.4"
@@ -0,0 +1,38 @@
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
+ """Warnings attributed to the program's own call."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import os
20
+ import sys
21
+ import types
22
+ import warnings
23
+ from typing import Optional
24
+
25
+ #: Frames a warning is never attributed to: the SDK's own, and contextlib's,
26
+ #: which a `with` on the SDK's connections passes through.
27
+ _SKIPPED = (os.path.dirname(__file__) + os.sep, contextlib.__file__)
28
+
29
+
30
+ def warn(message: str, category: type[Warning]) -> None:
31
+ """Warn at the first frame outside the SDK: the program's call, however
32
+ many of the SDK's own calls lie between."""
33
+ level = 1
34
+ frame: Optional[types.FrameType] = sys._getframe(1)
35
+ while frame is not None and frame.f_code.co_filename.startswith(_SKIPPED):
36
+ frame = frame.f_back
37
+ level += 1
38
+ warnings.warn(message, category, stacklevel=level + 1)
@@ -0,0 +1,55 @@
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
+ """The time bounds a listing takes: a datetime, Unix seconds, or text naming a
15
+ date (`2026-06-01`, any ISO form) or an age (`7d`, `24h`, `30m`). A naive
16
+ datetime is read as UTC."""
17
+
18
+ from __future__ import annotations
19
+
20
+ from datetime import datetime, timezone
21
+ from typing import Optional, Union
22
+
23
+ from testflows.machine._core import disks as _disks
24
+
25
+ from .errors import InvalidArgument
26
+
27
+ When = Union[datetime, int, str]
28
+
29
+
30
+ def iso(when: Optional[When]) -> Optional[str]:
31
+ """`when` as an ISO 8601 UTC instant, or None."""
32
+ if when is None:
33
+ return None
34
+ return _instant(when).isoformat()
35
+
36
+
37
+ def unix_seconds(when: Optional[When]) -> Optional[int]:
38
+ """`when` in Unix seconds, or None."""
39
+ if when is None or isinstance(when, int):
40
+ return when
41
+ return int(_instant(when).timestamp())
42
+
43
+
44
+ def _instant(when: When) -> datetime:
45
+ """`when` as an aware UTC datetime."""
46
+ if isinstance(when, int):
47
+ return datetime.fromtimestamp(when, timezone.utc)
48
+ if isinstance(when, str):
49
+ try:
50
+ return datetime.fromisoformat(_disks.parse_since(when, "time"))
51
+ except RuntimeError as exc:
52
+ raise InvalidArgument(str(exc)) from None
53
+ if when.tzinfo is None:
54
+ return when.replace(tzinfo=timezone.utc)
55
+ return when